The members functions of every object have access to a sort of magic pointer named
this, which points to the object itself. Thus any member function can find out the
address of the object of which it is a member.
Example:
// demonstration of this key word
# include<iostream.h>
class sample
{
private:
char chararra[10];
public:
void reveal( )
cout<<"my object's address is "<< this;
};
void main( )
{
sample s1,s2,s3;
s1.reveal( );
s2.reveal( );
s3.reveal( );
}
}
The main( ) program in this example creates three objects of type sample, then asks each object to
print its address, using the reveal( ) member function. This function prints out the value of the
this pointer.
Out put is
my object's address is 0x8f5effec
my object's address is ox8f5effec
my object's address is ox8f5effec
Accessing Member data with this
When you call a member function, it comes into existence with the value of this set of the address of the object for which it was called. The this pointer can be treated like any other pointer to an object and can thus be used to access the data in the object to points.
// demonstration of accessing member function using this keyword
# include<iostream.h>
class example
{
private:
int value;
public:
inline void display( );
{
this-> value = 35;
cout<<"contents of the value =" <<this->value;
cout<<endl;
}
void main( )
{
example obj1;
obj1.display( );
}
the output is
contents of the value = 20
0 Comments