Friday, May 30, 2008

C++ this pointer

2 comments
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.

EXAMPLE: Demonstrate the basic usage of "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


EXAMPLE: 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;
}



EXAMPLE: 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
If You Enjoyed This, Take 5 Seconds To Share It

2 comments:

  1. What is exactly done in the return by value example?

    /* Return by value
    MyClass operator = ( MyClass& c ) {
    this->data1 = c.data1;
    this->data2 = c.data2;
    return MyClass(100, 200);
    }
    */
    And why is there a greater memory usage?

    Regards,

    ReplyDelete
  2. I would like to answer:
    In the return statement we are calling the constructor.
    This creates a temporary object and later the object is destroyed upon return.
    Hence with this return statement we use some memory and some additional machine cycles.

    ReplyDelete