Mismatch of 'this' address when base class is not polymorphic but derived is

Viewed 2117

There is this code:

#include <iostream>

class Base
{
public:
    Base() {
        std::cout << "Base: " << this << std::endl;
    }
    int x;
    int y;
    int z;
};

class Derived : Base
{
public:
    Derived() {
        std::cout << "Derived: " << this << std::endl;
    }

    void fun(){}
};

int main() {
   Derived d;
   return 0;
}

The output:

Base: 0xbfdb81d4
Derived: 0xbfdb81d4

However when function 'fun' is changed to virtual in Derived class:

virtual void fun(){} // changed in Derived

Then address of 'this' is not the same in both constructors:

Base: 0xbf93d6a4
Derived: 0xbf93d6a0

The other thing is if class Base is polymorphic, for example I added there some other virtual function:

virtual void funOther(){} // added to Base

then addresses of both 'this' match again:

Base: 0xbfcceda0
Derived: 0xbfcceda0

The question is - why 'this' address is different in Base and Derived class when Base class is not polymorphic and Derived class is?

3 Answers
Related