/************************************************************************ *
The following example shows code using class
members without the this pointer. The comments on each line show
the equivalent code with the hidden use of the this pointer.
* ************************************************************************/
// This example uses class members without the this pointer.
#include <string.h>
#include <iostream.h>
class X
{
int len;
char *ptr;
public:
int GetLen() // int GetLen (X* const this)
{ return len; } // { return this->len; }
char * GetPtr() // char * GetPtr (X* const this)
{ return ptr; } // { return this->ptr; }
X& Set(char *);
X& Cat(char *);
X& Copy(X&);
void Print();
};
X& X::Set(char *pc) // X& X::Set(X* const this, char *pc)
{
len = strlen(pc); // this->len = strlen(pc);
ptr = new char[len]; // this->ptr =
// new char[this->len];
strcpy(ptr, pc); // strcpy(this->ptr, pc);
return *this;
}
X& X::Cat(char *pc) // X& X::Cat(X* const this, char *pc)
{
len += strlen(pc); // this->len += strlen(pc);
strcat(ptr,pc); // strcat(this->ptr,pc);
return *this;
}
X& X::Copy(X& x) // X& X::Copy(X* const this, X& x)
{
Set(x.GetPtr()); // this->Set(x.GetPtr(&x));
return *this;
}
void X::Print() // void X::Print(X* const this)
{
cout << ptr << endl; // cout << this->ptr << endl;
}
void main()
{
X xobj1;
xobj1.Set("abcd").Cat("efgh");
// xobj1.Set(&xobj1, "abcd").Cat(&xobj1, "efgh");
xobj1.Print(); // xobj1.Print(&xobj1);
X xobj2;
xobj2.Copy(xobj1).Cat("ijkl");
// xobj2.Copy(&xobj2, xobj1).Cat(&xobj2, "ijkl");
xobj2.Print(); // xobj2.Print(&xobj2);
}
/************************************************************************ *
This example produces the following output:
abcdefgh abcdefghijkl
* ************************************************************************/