Program To Access Data Members Of A Class Using (this) Pointer In C++

LEVEL: Beginner

Whats in this post?

  1. Code
  2. Output
  3. Background and Explanation of the code

Code


To copy code: Click View Source “View Source” on the right of this code snippet.


Background and Explanation of the code


When the member function setdata ( ) is called in association with object r1 on executing the statement

r1.setdata (10, 15);

then in addition to passing values 10 and 15 , the address of object r1 that generates the call is automatically passed to the function setdata ( ) within the definition of the member function setdata ( ).A this pointer variable of type rectangle is implicitly defined in setdata ( ) which receives the address of the passed object.

The first statement in the setdata ( ) member function definition displays the address of the object that generates the call using this pointer .The remaining statements

this -> l = i;

this -> b =j;

refer to the data members  l and b of the object r1 explicitly using this pointer.this is equivalent to the statements that are already being used in which this pointer is implicitly used

l = i;

b = j;

As data members are manipulated using this pointer within function definition , so any modification made are reflected back to the object that generates the call.

Similarly the statement in main ( ),

r1.area ( );

on execution , calculates the area of rectangle by accessing the data members l and b using this pointer

OUTPUT

Address of object that generates setdata ( ) call  :  0x8fb0fff2

Address of object that generates area ( ) call  =  0x8fb0fff2

Area  =  150