Friday, May 30, 2008

What is this pointer?

  • Every object has a special pointer "this" which points to the object itself.
  • This pointer is accessible to all members of the class but not to any static members of the class.
  • Can be used to find the address of the object in which the function is a member.
  • Presence of this pointer is not included in the sizeof calculations.

Demonstrate the usage of C++ this pointer

#include <iostream>
using namespace std;

class MyClass {
        int data;
    public:
        MyClass() {data=100;};
        void Print1();
        void Print2();
};

// Not using this pointer
void MyClass::Print1() {
    cout << data << endl;
}

// Using this pointer
void MyClass::Print2() {
    cout << "My address = " << this << endl;
    cout << this->data << endl;
}


int main()
{
    MyClass a;
    a.Print1();
    a.Print2();

    // Size of doesn't include this pointer
    cout << sizeof(a) << endl;
}
OUTPUT:
100
My address = 0012FF88
100
4

Practical use. Use this pointer to resolve ambiguity

#include <iostream>
using namespace std;

class MyClass {
        int data;
    public:
        void SetData(int data);
        int GetData() { return data; };
};

// Same name for function argument and class member
// this pointer is used to resolve ambiguity
void MyClass::SetData(int data) {
    this->data = data;
}

int main()
{
    MyClass a;
    a.SetData(100);
    cout << a.GetData() << endl;
}

Practical use. In assignment operators to reduce memory usage

#include <iostream>
using namespace std;

class MyClass {
        int data1;
        int data2;
    public:
        MyClass(int data1, int data2) {
            this->data1 = data1;
            this->data2 = data2;
        }

    /* Return by value
    MyClass operator = ( MyClass& c ) {
        this->data1 = c.data1;
        this->data2 = c.data2;
        return MyClass(100, 200);
    }
    */

    // Return by reference. Less memory usage
    MyClass& operator = ( MyClass& c ) {
        this->data1 = c.data1;
        this->data2 = c.data2;
        return *this;
    }

    void Print() {
        cout << data1 << endl;
        cout << data2 << endl;
    }
};

int main() 
{
    MyClass obj1(100, 200);
    MyClass obj2 = obj1;
    obj2.Print();
}
OUTPUT:
100
200

Trending

Contact Form

Name

Email *

Message *

Back to Top