4 Pointers References And Memory Management

Object Oriented Programming · Unit 4

Pointers, References, and Memory Management

Exam-focused notes for Pointers, References, and Memory Management (Object Oriented Programming, BIT153): what the TU syllabus asks and how it has actually been tested, with 7 solved past questions from this unit.

Pointers, References, and Memory Management in short

This chapter covers the this pointer, ways of passing arguments, dynamic memory and static members. These topics help us manage memory and share data between objects.

Pointers, References, and Memory Management: notes

This pointer concept and uses

The this pointer is a hidden pointer available inside every non-static member function. It holds the address of the object that called the function.

Its main uses are:

  • To tell apart a data member and a parameter with the same name.
  • To return the current object, so calls can be chained (return *this;).
  • To pass the current object to another function.
class Demo {
    int x;
public:
    Demo(int x) { this->x = x; }
    Demo& add(int n) { x += n; return *this; }
    void show() { cout << x << endl; }
};

int main() {
    Demo d(5);
    d.add(2).add(3);     // chained calls
    d.show();            // 10
}

this cannot be used in static member functions, because they are not tied to any object.

This pointer for name conflict resolution

If a parameter has the same name as a data member, the parameter hides the member inside the function. Writing this->name selects the data member.

class Student {
    int roll;
public:
    void set(int roll) {
        this->roll = roll;   // member = parameter
    }
};

Without this->, the line roll = roll; would assign the parameter to itself and the member would stay unchanged.

What this unit covers

  • This pointer concept and uses
  • This pointer for name conflict resolution
  • Call by value and call by reference
  • Memory management operators: new and delete
  • Dynamic memory allocation
  • Static data members and static functions

This pointer concept and uses

2082 · 5 marks

What is the use of this pointer? Write a program to demonstrate it. [5]

Show solved answer

The this Pointer in C++

Definition and Use

The this pointer is an implicit pointer available inside every non-static member function of a class. It automatically points to the object that invoked the member function.

Uses of this Pointer

UseDescription
Resolve name conflictDistinguish between member variables and parameters with the same name
Return current objectReturn *this to enable method chaining
Pass current objectPass the calling object to another function
Self-reference checkCheck if two pointers point to the same object

Program to Demonstrate this Pointer

#include <iostream>
using namespace std;

class Student {
private:
    int id;
    string name;
    float marks;

public:
    // Use 1: Resolving name conflict between parameter and data member
    void setData(int id, string name, float marks) {
        this->id    = id;      // 'this->id' is member, 'id' is parameter
        this->name  = name;
        this->marks = marks;
    }

    // Use 2: Returning current object to enable method chaining
    Student& setId(int id) {
        this->id = id;
        return *this;          // returns reference to calling object
    }

    Student& setName(string name) {
        this->name = name;
        return *this;
    }

    Student& setMarks(float marks) {
        this->marks = marks;
        return *this;
    }

    void display() {
        cout << "ID    : " << this->id    << endl;
        cout << "Name  : " << this->name  << endl;
        cout << "Marks : " << this->marks << endl;
    }

    // Use 3: Compare if two objects are the same using this pointer
    bool isSame(Student &s) {
        if (this == &s) {
            return true;   // same object in memory
        }
        return false;
    }
};

int main() {
    // Demonstrating Use 1: Resolving name conflict
    cout << "--- Using setData (name conflict resolution) ---" << endl;
    Student s1;
    s1.setData(101, "Ram Sharma", 85.5);
    s1.display();

    // Demonstrating Use 2: Method chaining using *this
    cout << "\n--- Using Method Chaining ---" << endl;
    Student s2;
    s2.setId(102).setName("Sita Thapa").setMarks(90.0);
    s2.display();

    // Demonstrating Use 3: Self-reference check
    cout << "\n--- Self-reference Check ---" << endl;
    if (s1.isSame(s1)) {
        cout << "s1 and s1 are the SAME object." << endl;
    }
    if (!s1.isSame(s2)) {
        cout << "s1 and s2 are DIFFERENT objects." << endl;
    }

    return 0;
}

Output

--- Using setData (name conflict resolution) ---
ID    : 101
Name  : Ram Sharma
Marks : 85.5

--- Using Method Chaining ---
ID    : 102
Name  : Sita Thapa
Marks : 90

--- Self-reference Check ---
s1 and s1 are the SAME object.
s1 and s2 are DIFFERENT objects.

Key Points to Remember

  • this is a constant pointer (its address cannot be changed).
  • It holds the address of the calling object: this == &callingObject
  • It is not available in static member functions (static functions have no object context).
  • Dereferencing it (*this) gives the actual calling object.
Open this answer on its own page →

0 · 5 marks

What are the uses of this pointer? Discuss its concept with suitable example. [5]

The this pointer is an implicit (hidden) pointer available inside every non-static member function of a class. It automatically holds the address of the object that invoked the member function. The compiler passes it as a hidden argument to every non-static member function call. Syntax: --- Use D...

Open this answer on its own page →

This pointer for name conflict resolution

2080 · 5 marks

How 'this' pointer is used to resolve name conflict between local variable and member variable in C++? Explain with example. [5]

The this pointer is an implicit pointer available inside every non-static member function of a class. It automatically holds the address of the object that called the member function. Its type is ClassName. --- A name conflict arises when a local variable (or parameter) inside a member function h...

Open this answer on its own page →

Static data members and static functions

2080 · 5 marks

Illustrate the use of static variable with a simple program. [5]

A static variable is a variable that retains its value between function calls. It is initialized only once (at the first call) and exists for the entire lifetime of the program, even though its scope may be local to a function. --- Property Description ------ Initialization Done only once Lifetim...

Open this answer on its own page →

2079 · 5 marks

What is the task of static data members and function? Illustrate with an example. [5]

Show solved answer

Static Data Members and Static Member Functions in C++

Static Data Members

A static data member is a class variable that is shared among all objects of that class. Unlike regular data members (which have separate copies for each object), only one copy of a static data member exists, regardless of how many objects are created.

Key characteristics:

  • Declared with the keyword static inside the class
  • Defined and initialized outside the class (in global scope)
  • Shared by all objects of the class
  • Exists even if no object is created

Static Member Functions

A static member function can be called without creating any object of the class. It can only access static data members and other static member functions.

Key characteristics:

  • Declared with the keyword static
  • Called using the class name and scope resolution operator (::)
  • Does not have access to this pointer
  • Cannot access non-static members directly

Example

#include <iostream>
using namespace std;

class Student {
private:
    int rollNo;
    static int count;       // static data member: shared by all objects

public:
    Student(int r) {
        rollNo = r;
        count++;            // incremented each time an object is created
    }

    // static member function
    static void showCount() {
        cout << "Total Students: " << count << endl;
    }

    void showRoll() {
        cout << "Roll No: " << rollNo << endl;
    }
};

// Definition and initialization of static data member (outside class)
int Student::count = 0;

int main() {
    Student::showCount();   // called without any object -> Total Students: 0

    Student s1(101);
    Student s2(102);
    Student s3(103);

    s1.showRoll();          // Roll No: 101
    s2.showRoll();          // Roll No: 102

    Student::showCount();   // called using class name -> Total Students: 3

    return 0;
}

Output:

Total Students: 0
Roll No: 101
Roll No: 102
Total Students: 3

Summary Table

FeatureStatic Data MemberStatic Member Function
Shared among objectsYesN/A
Accessed via class nameYesYes
Needs object to callNoNo
Can access non-static membersN/ANo
this pointer availableN/ANo

Task in short: Static data members maintain common/shared state across all objects (e.g., counting objects), while static member functions provide utility operations that belong to the class as a whole rather than to any individual object.

Open this answer on its own page →

Memory management operators

2078 · 5 marks

Explain Memory Management Operators of C++ with example. [5]

C++ provides two special memory management operators for dynamic memory allocation and deallocation at runtime: 1. new operator 2. delete operator These operators allow programs to request memory from the heap (free store) during program execution, rather than using fixed compile-time allocation....

Open this answer on its own page →

Call by value and call by reference

2078 · 5 marks

Explain Call by Value and Call by Reference with appropriate example. [5]

In Call by Value, a copy of the actual argument is passed to the formal parameter of the function. Any changes made to the formal parameter inside the function do not affect the original (actual) argument. - The actual and formal parameters occupy separate memory locations. - It is the default me...

Open this answer on its own page →