You are on page 1of 5

this pointer

To understand ‘this’ pointer, it is important to know how objects look at functions and
data members of a class.

1.Each object gets its own copy of the data member.


2.All-access the same function definition as present in the code segment.

Then now question is that if only one copy of each member function exists
and is used by multiple objects, how are the proper data members are
accessed and updated?

•The compiler supplies an implicit pointer along with the names of the functions as
‘this’.

•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.
#include<iostream>
class box
{ smallBox mediumBox largeBox
public :
int l;
int b;
L L L
int h; B B B
box(int x, int y, int z) H H H
{
l=x;
b=y;
h=z;
} volume
int volume()
{
return (l*b*h); //[(this->l)*(this->b)*(this->h)]
}
};
int main()
{
int vol1, vol2, vol3;
box smallBox(5,2,4), mediumBox(10,5,10), largeBox(8,6,4);
vol1 = smallBox.volume();
vol2 = mediumBox.volume();
vol3 = largeBox.volume();
std::cout<<vol1<<std::endl<<vol2<<std::endl<<vol3;
return 0;
}
this pointer
• this is a local object pointer in every instance
member function containing address of caller
object.
• this pointer can not be modified.
• It is used to refer caller object in member
function.
• #include<iostream>
• using namespace std;
1) When local variable’s
/* local variable is same as a member's name */ name is same as member’s
• class Test
name
• {
• private:
• int x;
• public:
• void setX (int x)
• {
// The 'this' pointer is used to retrieve the object's x
// hidden by the local variable 'x'
• this->x = x;
• }
• void print() { cout << "x = " << x << endl; }
• };

• int main()
• {
• Test obj;
• int y = 20;
• obj.setX(y);
• obj.print();
• return 0;
• }

Output : X = 20
2) To return reference to the calling object

#include<iostream> int main()


{
Class Max Max obj1(10), obj2(20), obj3;
{ Obj3 = obj1.greater(obj2); // this will point obj1
private: Obj3.disp();
int no; return 0;
public:
}
Max (int num = 0) //constructor
{
no =num;
}
Max &greater(Max &x)
{
if(x.no > no) //if(obj2.no > this->no)
{
retutn x;
} (pointer to caller object i.e. obj1)
else
{
return *this;
}
}
void disp() { cout << “Greater value : " << no<< endl; }
};

You might also like