Take the 2-minute tour ×

How does the this pointer behaves when used inside a base class method:

class Base{
   int a;
   Base() : a(5) {}
   void func(){
       std::cout << " value is : " << this->a << std::endl;

class Derived : public Base{
   int a;
   Derived() : a(1){}
   void func1(){

int main(){
   Derived d;

the output of the code is :

value is : 5

value is : 1

As i am using the same object to call both the functions. So will the value of this pointer differ in methods for base and derived class ?

share|improve this question

3 Answers 3

up vote 2 down vote accepted

this->a is equivalent to a in that context, so it has nothing to do with the base pointer.

The member a is resolved statically, and the derived class hides the base class member, since they're both named a.

To check the this pointer itself, you can print it directly:

std::cout << this;

It will be the same for both objects.

The main thing to take from this is that Base::a and Derived::a are different. Try the following in Derived:

void func1(){
    std::cout << "derived value is : " << a << std::endl;
    std::cout << "   base value is : " << Base::a << std::endl;
share|improve this answer
this pointer is actually the address of the created object. and derived class object has values for both the variables (Base and derived). so why does this->a behaves differently in both the methods ? –  Dexter Sep 25 '12 at 11:43
@HellBoy yes. And your point is? –  Luchian Grigore Sep 25 '12 at 11:44

You would have to do this->Base::a to access Base's a. Else you always access Derived::a.

share|improve this answer

this pointer will always point to current object in which it exists.

When func is called, Base class is used and base class field is printed. but,

When func1 is called, Derived class is used and it's field is printed.

Try commenting this line Derived() : a(1){} and you'll get more clarity.

share|improve this answer
It points to the object, not the class. You can't point to a class. –  SingerOfTheFall Sep 25 '12 at 11:30
Yes, but to make OP understand, i wrote that way. and in brackets gave more clear explanation. –  Azodious Sep 25 '12 at 11:33
But it isn't clearer. It's wrong. –  EJP Sep 25 '12 at 12:05
Updated!! thanks for improving my answers. –  Azodious Sep 25 '12 at 12:12

Your Answer


