How does the this pointer behaves when used inside a base class method:
class Base{
public:
int a;
Base() : a(5) {}
void func(){
std::cout << " value is : " << this->a << std::endl;
}
};
class Derived : public Base{
private:
int a;
public:
Derived() : a(1){}
void func1(){
std::cout << " value is : " << this->a << std::endl;
}
};
int main(){
Derived d;
d.func();
d.func1();
}
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 ?
this->ais equivalent toain that context, so it has nothing to do with the base pointer.The member
ais resolved statically, and the derived class hides the base class member, since they’re both nameda.To check the
thispointer itself, you can print it directly:It will be the same for both objects.
The main thing to take from this is that
Base::aandDerived::aare different. Try the following inDerived: