←Back to Subject
Notes
Notes
Study material and explanations
Diagrams
Diagrams
Visualize concepts easily
Mnemonics
Mnemonics
Tricks to remember faster
One Night Prep
One Night Prep
Short and focused revision
Revision
Revision
Quick summary and key points
Important Questions
Important Questions
Practice most relevant questions
Notes

Pointers with Arrays & The 'this' Pointer in C++

Study material and explanations for Unit 5

Pointers with Arrays & The ‘this’ Pointer in C++

1. What is a Pointer? (In Simple Words)

A Pointer is a special variable that stores the memory address of another variable.

Real-Life Analogy: Think of your house address written on a piece of paper. The paper is NOT your house, but it tells anyone exactly where your house is located in the city! In C++, a pointer is that piece of paper holding a memory address.

  • Address-of Operator (&): Gives the memory address of a variable (e.g. &age).
  • Dereference Operator (*): Gets the actual value stored at that address (e.g. *ptr).

Pointer Arithmetic:

When you write ptr++, the computer does not just add 1 to the address number. It advances by the size of that data type:

  • For an int pointer: ptr + 1 jumps ahead by 4 bytes.
  • For a double pointer: ptr + 1 jumps ahead by 8 bytes.

2. Pointers with Arrays

In C++, an array name without any brackets is actually a pointer to its first element (arr == &arr[0]).

Whenever you write arr[i], the C++ compiler internally converts it to pointer arithmetic:

arr[i]   <─── EXACT SAME AS ───>   *(arr + i)
#include <iostream>
using namespace std;

int main() {
    int numbers[5] = {10, 20, 30, 40, 50};
    int *ptr = numbers; // Points to the first element (&numbers[0])

    cout << "Reading array elements using pointer arithmetic:" << endl;
    for (int i = 0; i < 5; i++) {
        // *(ptr + i) gives the value stored at index i
        cout << "Index " << i << " Value: " << *(ptr + i) << endl;
    }
    return 0;
}

3. Pointers to Objects & The Arrow Operator (->)

Just like primitive integers, you can also create pointers that point to class objects.

When using an object pointer, instead of writing awkward syntax like (*ptr).show(), C++ gives us the clean Arrow Operator (->):

#include <iostream>
using namespace std;

class Box {
    public:
        int length = 10;
        void show() { 
            cout << "Length = " << length << endl; 
        }
};

int main() {
    Box *bPtr = new Box(); // Pointer to Box object on heap

    // Using the Arrow Operator (->)
    bPtr->length = 25;
    bPtr->show(); // Prints: Length = 25

    delete bPtr; // Free heap memory
    return 0;
}

4. The this Pointer in C++

When you have 5 objects of a class and one of them calls obj1.display(), how does the function know which object called it?

C++ solves this with a hidden pointer called the this pointer.

The this pointer is an automatic constant pointer passed secretly into every non-static member function. It always points to the calling object.

The Three Critical Roles of the 'this' Pointer
1. Resolving Name Conflicts
Separates class variables from function parameters when both have the exact same name (this->age = age;).
2. Method Chaining
Returning *this allows you to chain multiple function calls in one single line: obj.setName("Aman").setAge(21);
3. Self-Assignment Check
Used in operator overloading to make sure an object isn't being assigned to itself (if (this != &obj)).

5. Practical Code Example: Name Conflict & Method Chaining

#include <iostream>
#include <string>
using namespace std;

class Person {
    private:
        string name;
        int age;

    public:
        // ROLE 1: Resolving name conflict between parameter and member variable
        Person(string name, int age) {
            // 'this->name' is the class variable, 'name' is the incoming parameter!
            this->name = name; 
            this->age = age;
        }

        // ROLE 2: Method Chaining (returns reference to calling object via *this)
        Person& setName(string name) {
            this->name = name;
            return *this; // Returning the current calling object!
        }

        Person& setAge(int age) {
            this->age = age;
            return *this; // Returning the current calling object!
        }

        void display() const {
            cout << "Name: " << name << "\tAge: " << age << endl;
        }
};

int main() {
    Person p("Aman", 20);
    p.display();

    // METHOD CHAINING: Chaining two function calls on the exact same line!
    p.setName("Aman Sharma").setAge(21);
    p.display();

    return 0;
}

DAVV Exam Preparation Tips

Frequently Asked 5-Mark Questions:

  1. Explain the relationship between pointers and 1D arrays in C++.
    Model Answer:
    • Array name is a constant pointer to the first element (arr == &arr[0]).
    • Accessing arr[i] is internally evaluated by compiler as *(arr + i).
  2. What is the this pointer in C++? State two of its uses.
    Model Answer:
    • An implicit pointer available in all non-static member functions pointing to the calling object.
    • Use 1: Resolving name conflicts when parameters have the same name as data members (this->age = age;).
    • Use 2: Returning *this to enable method chaining (p.setName("A").setAge(20);).

Frequently Asked 10-Mark Questions:

  1. Explain Pointers to Objects and the this pointer in C++. Write a complete program demonstrating how this resolves name conflicts and enables method chaining.
    Model Answer:
    • Explain how pointers to objects work using the arrow operator (->).
    • Define the this pointer and explain that static member functions do not have a this pointer.
    • Write out the complete Person program with constructor parameter disambiguation and chained setters returning *this.