C++ This Pointer

In C++ programming, this is a keyword that refers to the current instance of the class. A class object can access itself using this pointer inside its member functions. Understanding this pointer serves as a key prerequisite when we need to operate within object-oriented structures for functions, such as self-reference calls, method chaining, and operator overloading.

In other words, this pointer operates as an implicit built-in pointer that operates inside all member functions of a class except static members. Through this pointer, the calling object obtains its memory address while enabling member accessibility.

Syntax

A simple syntax defines this pointer. A member function can use this keyword to access the pointer, which points to the calling object.

Example

Public:

    void show() {

        cout << "Address of current object: " << this << endl;

    }

};

C++ Simple this Pointer Example

Let's look at simple example to demonstrate this pointer in C++.

Example

Example

#include <iostream>

using namespace std;

class Thispointer {

public:

    void display() {

        cout << "This pointer holds: " << this << endl;

    }

};

int main() {

    Thispointer obj;

    obj.display();

    return 0;

}

Output:

Output

This pointer holds: 0x7fff8452e647

C++ another This Pointer Example

Let us take another example of this keyword in C++ that refers to the fields of the current class.

Example

Example

#include <iostream>  

using namespace std;  

class Employee {  

   Public:  

       int id; //data member (also instance variable)      

       string name; //data member(also instance variable)  

       float salary;  

       Employee(int id, string name, float salary)    

        {    

             this->id = id;    

            this->name = name;    

            this->salary = salary;   

        }    

       void display()    

        {    

            cout<<id<<"  "<<name<<"  "<<salary<<endl;    

        }    

};  

int main(void) {  

    Employee e1 =Employee(101, "John", 890000); //creating an object of Employee   

    Employee e2=Employee(102, "Alice", 59000); //creating an object of Employee  

    e1.display();    

    e2.display();    

    return 0;  

}

Output:

Output

101 John 890000

102 Alice 59000

Characteristics of this Pointer

Several characteristics of this pointer in C++ are as follows:

  • This Pointer exists exclusively in member functions because static functions remain part of the class structure instead of an object structure.
  • The system automatically creates this pointer during a member function execution.
  • This pointer contains the address of the calling object yet remains accessible for modification.
  • Static functions do not allow this keyword usage since static members operate on non-specific instances.
  • Method chaining and operator overloading, along with naming conflict resolution, all depend on using this pointer.
  • Uses of this pointer in C++

  • It can be used to pass a current object as a parameter to another method.
  • It can be used to refer current class instance variable.
  • It can be used to declare indexers.
  • Function parameters and member variables can receive resolution through this pointer.
  • It provides an approach to writing cleaner code that operates more efficiently with method chaining.
  • The use of this enables operator overloading when returning an object reference from the current instance.
  • Different Ways to Use this Pointer

There are several ways to use this pointer in C++ . Some of them are as follows:

1. Accessing Data Members

In C++, this pointer is used to resolve naming conflicts when a function contains parameters that share their name with object member variables.

C++ Accessing Data Member Example using This Pointer:

Let's see the example program of this pointer in accessing data members.

Example

Example

#include<iostream>

using namespace std;

class Test {

private:

    int x;

public:

    void setX(int x) {

        this->x = x;  // Resolves name conflict

    }

    void print() {

cout<< "value of x: "<<x<<endl;

    }

};

int main()

{

    Test obj;

    obj.setX(10);

    obj.print();

    return 0;

}

Output:

Output

value of x:10

Explanation:

The class data member x and the parameter x in the setX function share the same name. By using this->x = x;, ambiguity is avoided and the value of the parameter is assigned to the object's data member.

2. Returning the Object (Method Chaining)

In C++, the method chaining technique becomes possible because returning *this (this pointer) enables multiple function calls in one statement.

C++ Method Chaining Example using This Pointer:

Let's see the example program of this pointer in method chaining.

Example

Example

class Chain {

private:

    int value;

public:

    Chain& setValue(int v) {

        this->value = v;

        return *this;  // Returning the current object

    }

    void display() {

        cout << "Value: " << value << endl;

    }

};

int main() {

    Chain obj;

    obj.setValue(10).display();  // Method chaining

    return 0;

}

Output:

Output

Value: 10

Explanation:

The program uses method chaining, where setValue(int v) sets the value and returns the object, allowing display to be called in the same statement: obj.setValue(10).display;.

3. Passing the Current Object

In C++, this pointer solves the requirement to transmit the current object instance to any function or method that accepts objects.

C++ Passing the Current Object Example:

Let's see the example program of this pointer in passing the current objects.

Example

Example

class PassExample {

public:

    void show() {

        cout << "Inside show() function" << endl;

    }

    void invoke(PassExample* obj) {

        obj->show();

    }

    void execute() {

        invoke(this);  // Passing the current object

    }

};

int main() {

    PassExample obj;

    obj.execute();

    return 0;

}

Output:

Output

Inside show() function

Explanation:

The program demonstrates passing the current object using the this pointer. The execute function calls invoke(this), which then calls show on the passed object, printing "Inside show function".

4. Using "this" pointer in Operator Overloading

In operator overloading the "this" pointer provides a way to return a reference to the modified object.

C++ Operator Overloading Example using This Pointer:

Let's see the example program of this pointer in operator overloading.

Example

Example

class Overload {

private:

    int num;

public:

    Overload(int n) : num(n) {}

    Overload& add(int n) {

        this->num += n;

        return *this;

    }

    void print() {

        cout << "Number: " << num << endl;

    }

};

int main() {

    Overload obj(5);

    obj.add(10).print();  // Chaining with operator overloading

    return 0;

}

Output:

Output

Number: 15

Explanation:

The program demonstrates method chaining using the this pointer. The add(int n) function modifies num and returns *this, allowing obj.add(10).print; to execute both functions in a single statement.

Using this Pointer in a Constructor in C++

Inside a class constructor, this pointer serves as a reference to the active object instance. In C++, this pointer provides multiple benefits, which include object initialization alongside name resolution services for method chaining functionality.

1. Resolving Name Conflict in Constructor

When constructor parameters share identical names with the class members, this pointer functions as a distinction method.

  • The Constructor returns this pointer to enable Method Chaining
  • A method chain becomes possible through this pointer because it returns the current instance of the object.

Let's see the example of this pointer to solve the name conflict in the constructor in C++.

Example

Example

#include <iostream>

using namespace std; //using standard namespace

class Example {

private:

    int x;

public:

    // Constructor using 'this' pointer to resolve name conflict

    Example(int x) {

        this->x = x;

        cout << "Constructor called. Value initialized: " << this->x << endl;

    }

    // Method chaining using 'this' pointer

    Example* setValue(int val) {

        this->x = val;

        return this;

    }

    void display() {

        cout << "Current Value of x: " << x << endl;

    }

};

int main() //main function

{

    Example obj(10);  // Constructor initializes x = 10

    obj.setValue(20)->display();  

    return 0;

}

Output:

Output

Constructor called. Value initialized: 10

Current Value of x: 20

Explanation:

The program displays constructor initialization and method chaining using this pointer. The constructor resolves name conflicts, while Setvalue (Int Val) updates X and returns it, allowing obj.setvalue (20)-> display ; To execute both tasks in a statement.

2. Removing "this" pointer in C ++

In C++, "this" pointer is an implicit address that exists for each class member function during their execution time to access the current object. Deleting the this pointer is generally avoided unless it is too necessary.

Member function can delete this pointer only when the following two conditions are found:

  • A dynamic allocation of this object occurs through new.
  • Deletion of the object prevents any new system access from starting.

Syntax:

It has the following syntax:

Example

class Test {

public:

    void destroy() {

        delete this; // Deletes the current object

    }

};

int main() {

    Test* obj = new Test();

    obj->destroy(); // Deleting the object inside the function

    return 0;

}

C++ Removing This Pointer Example:

Let's give an example to remove this pointer in C ++.

Example

Example

#include<iostream>

using namespace std;

class Test {

public:

    void destroy() {

        cout << "Deleting the current object..." << endl;

        delete this; // Deletes the dynamically allocated object

    }

};

int main()

{

    Test* obj = new Test(); // Dynamically allocating the object

    obj->destroy(); // Deleting the object inside the function

    // obj is now a dangling pointer and should not be used further.

    return 0;

}

Output:

Output

Deleting the current object...

Explanation:

The program exhibits the method chaining using the this pointer, where destroy dynamically removes the allocated objects. The add(int n) function modifies num and returns *this, allowing obj.add(10).print; to execute both functions in a single statement.

Effects of this Pointer in C++

The "this" pointer provides various operations in C ++ programming.

  • Accessing Current Object: Programming access to current object members becomes possible through the use of this pointer.
  • Method Chaining: Method Chaining is possible through this pointer because it provides a reference to the calling object.
  • Avoiding Name Conflicts: The use of this resolves conflicts that occur between names used for local variables that match with data member names.
  • Operator Overloading: Operator overloading functionality depends on this pointer, which returns the object reference from the calling location.
  • Limitations of this Pointer

Several limitations of this pointer in C++ are as follows:

  • Can not be modified: A programmer cannot change the fundamental properties of this pointer as it remains default and irreversible.
  • Not available in static functions: This ponter is inaccessible in static functions because they do not belong to any object example.
  • Limited to class scope: Only non-static class members can appoint this indicator as an operation.
  • Conclusion

Finally, a reliable object handling in C ++ software development occurs through this pointer, which helps developers to write clear codes simultaneously. Proper use of this indicator improves the efficiency of the program, mostly when developing object-oriented codebase.

Developers can create a small adaptable and easy-to-maintain C ++ code through proper use of this pointer. The main drawback of this pointer emerges through static work as well as its inaccessible nature within its only read-only characteristic.

C++ this pointer MCQs

  1. What reference does a c++ pointer has?
  • Base class address
  • Calling object address
  • Object memory size
  • Value of first data member of object
  1. Evaluate the following assertions about this indicator:

Stable members can use this indicator.

  • Static member functions can access this pointer.
  • It functions to assign another object address.
  • A non-static member function initialization automatically happens when it gets invoked.
  • Member variables require this pointer for their access.
  1. How can this pointer be used to resolve name conflicts in a class?
  2. Example
    
    class Demo {
    
        int x;
    
    public:
    
        void setX(int x) {
    
            _____ = x;
    
        }
    
    };
    

What should fill in the missing space to properly set the parameter x value on the data member x?

  • this->x
  • Demo::x
  • *this.x
  1. What can be the output for the below following C++ Program?
  2. Example
    
    class Test {
    
    public:
    
        void show() {
    
            cout << this << endl;
    
        }
    
    };
    
    int main()
    
    {
    
        Test obj1, obj2;
    
        obj1.show();
    
        obj2.show();
    
        return 0;
    
    }
    
  • The program displays the same address two times.
  • Different memory addresses printed
  • Compiler error
  • Garbage values printed
  1. Which of the following is a valid use case for this pointer?
  • Accessing static data members
  • When used for method chaining, the current object can be returned to the calling context.
  • Initializing the base class in a constructor
  • Storing it in a global pointer variable

Input Required

This code uses input(). Please provide values below: