C++ Programming (using this pointer)

In C++, the this pointer is a pointer accessible only within the member functions of a class, struct, or union type. It points to the object for which the member function is called. Static member functions do not have a this pointer.


void Date::setMonth( int mn )
month = mn; // These three statements
this->month = mn; // are equivalent
(*this).month = mn;

In the above example, all the three statements are equivalent.

One common usage of this pointer is for concatenating member function calls:

class Time {
Time(int hour=0, int minute=0, int second=0); //Default constructor
Time& SetHour(int hour) { m_hour = hour;
return *this; }
Time& SetMinute(int minute) { m_minute = minute;
return *this; }
Time& SetSecond(int second) { m_second = second;
return *this; }
int hour;
int minute;
int second;

main( )
Time t;
t.SetHour(18).SetMinute(30).SetSecond(20); //Concatenating member function calls
return 0;

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>