C++ This Pointer - C++ Programming Tutorial
C++ Course / Pointers & References / C++ This Pointer

C++ This Pointer

BLUF: Mastering C++ This Pointer is a critical step in becoming a proficient C++ developer. This lesson provides a deep dive into the syntax, performance considerations, and real-world applications of this concept.
Key Performance Insight: C++ This Pointer

C++ is renowned for its efficiency. Learn how C++ This Pointer enables low-level control and high-performance computing in the tutorial below.

In C++ programming, this keyword signifies the current instance of the class. Within its member functions, a class object is able to refer to itself by utilizing this pointer. Proficiency in handling this pointer is essential for tasks involving object-oriented paradigms, including self-referential calls, method cascading, and overloading operators.

Put differently, this pointer serves as an implied internal pointer functioning within all class member functions except for static ones. By utilizing this pointer, the object making the call can access its memory location and access class members.

Syntax

A straightforward syntax defines this pointer. The this keyword enables a member function to access the pointer that references the object making the call.

Example

Public:

    void show() {

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

    }

};

C++ Simple this Pointer Example

Let's examine a straightforward illustration to showcase 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's consider another instance of this keyword in C++ which points to the attributes of the present 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 multiple techniques for utilizing this pointer in C++. A few of them include:

1. Accessing Data Members

In C++, the 'this' pointer is employed to mitigate naming clashes in situations where a function's parameters have the same names as object member variables.

Accessing Data Member Example using This Pointer in C++:

Let's examine an illustrative program showcasing the usage of pointers to access data attributes.

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 data member x within the class and the parameter x in the setX function are named identically. To prevent ambiguity, assigning this->x = x; ensures clarity and assigns the parameter's value to the object's data member.

2. Returning the Object (Method Chaining)

In C++, the concept of method chaining is made feasible by utilizing the return of *this (this pointer), which allows for executing multiple function calls within a single statement.

C++ Method Chaining Example using This Pointer:

Let's examine an example program showcasing the usage of pointers 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 software employs method chaining, in which setValue(int v) is responsible for assigning a value and then returning the object, enabling the invocation of display within the same line: obj.setValue(10).display;.

3. Passing the Current Object

In C++, the "this" pointer addresses the need to pass the current object instance to any function or method that expects objects.

C++ Passing the Current Object Example:

Let's examine an example program showcasing the utilization of pointers to pass 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 code illustrates the utilization of the this pointer to pass the current object. Within the execute function, the invoke(this) method is invoked, subsequently executing the show function on the provided object, displaying the message "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.

In this C++ tutorial example, we will demonstrate operator overloading with the use of the 'this' pointer.

Let's examine a sample program showcasing the overloading of the pointer in operator.

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 software illustrates method chaining by leveraging the this pointer. The add(int n) method alters the value of num and then returns *this, enabling the execution of both obj.add(10) and print within a single line of code.

Using this Pointer in a Constructor in C++

Within a class constructor, the "this" pointer functions as a reference to the current object instance. In C++, this pointer offers various advantages such as facilitating object initialization and providing name resolution services for supporting method chaining capabilities.

1. Resolving Name Conflict in Constructor

When the constructor parameters have the same names as the class members, the 'this' pointer serves as a differentiator.

  • Utilizing the 'this' pointer in the constructor allows for Method Chaining.
  • This pointer facilitates method chaining by returning the existing object instance.

Let's examine an illustration of employing this pointer to address the naming clash in the constructor within 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 software demonstrates constructor initialization and method chaining by utilizing the 'this' pointer. Constructors are responsible for resolving any conflicts related to names. The 'Setvalue(Int Val)' function updates the value of X and then returns it. This enables the execution of both tasks by calling 'obj.setvalue(20)->display;' within a single statement.

2. Removing "this" pointer in C ++

In C++, the "this" pointer represents an implicit address available to every member function of a class while they are running, enabling them to interact with the current object. Removing the this pointer is typically discouraged unless absolutely required.

A member function is permitted to delete this pointer solely under the condition that the subsequent two criteria are met:

  • The object is dynamically allocated using the new keyword.
  • Deleting the object prevents the initiation of any new system access.

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 provide an illustration on how to delete 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 software demonstrates method chaining by leveraging the this pointer, with the destroy method responsible for dynamically deallocating objects. By utilizing the add(int n) function to adjust num and return *this, it becomes possible to execute both obj.add(10) and print within 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 dependable method for managing objects in C++ software development involves the this pointer, aiding developers in crafting concise and readable code. The effective utilization of this pointer enhances program efficiency, particularly in the creation of object-oriented codebases.

Developers have the ability to craft a compact, flexible, and easily maintainable C++ code by effectively utilizing the this pointer. One of the primary limitations of this pointer arises from its static functionality, along with its restricted accessibility due to its read-only nature.

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

B. Invoking Object Location

  1. Assess the validity of the statements regarding this metric:

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.

A. An automatic initialization of a non-static member function occurs upon its invocation.

  1. What is the purpose of utilizing this pointer to address name clashes within a class?
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

Option B. this->x

What result could be produced by the following C++ code snippet?

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

When employed for method chaining, the present object can be sent back to the invoking context.

Input Required

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

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience