Tuesday, January 20, 2009

"this" pointer

The this pointer is a pointer accessible only within the nonstatic 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. An object's this pointer is not part of the object itself; it is not reflected in the result of a sizeof statement on the object.

  • this pointer stores the address of the class instance, to enable pointer access of the members to the member functions of the class.
  • this pointer is not counted for calculating the size of the object.
  • this pointers are not accessible for static member functions.
  • this pointers are not modifiable.
void Date::setMonth(int mn)
{
month = mn; // These three statements
this->month = mn; // are equivalent
(*this).month = mn;
}
The this pointer is passed as a hidden argument to all nonstatic member function calls and is available as a local variable within the body of all nonstatic functions. The type of the this pointer for a member function of a class type X, is X* const. If the member function is declared with the const qualifier, the type of the this pointer for that member function for class X, is const X* const.

The following two are the same:

struct X {
private:
int len;
char *ptr;
public:
int GetLen() {
return len;
}
char * GetPtr() {
return ptr;
}
X& Set(char *);
};

X& X::Set(char *pc) {
len = strlen(pc);
ptr = new char[len];
strcpy(ptr, pc);
return *this;
}

-

struct X {
private:
int len;
char *ptr;
public:
int GetLen (X* const THIS) {
return THIS->len;
}
char * GetPtr (X* const THIS) {
return THIS->ptr;
}
X& Set(X* const, char *);
};

X& X::Set(X* const THIS, char *pc) {
THIS->len = strlen(pc);
THIS->ptr = new char[THIS->len];
strcpy(THIS->ptr, pc);
return *THIS;
}

No comments:

Post a Comment