I executed the following code.
#include <iostream>
class Base
{
public:
virtual void func()
{
std::cout<<"Base func called"<<std::endl;
}
};
class Derived: public Base
{
public:
virtual void func() override
{
std::cout<<"Derived func called"<<std::endl;
}
};
int main()
{
void (Base::*func_ptr)()=&Base::func; //Yes, the syntax is very beautiful.
Base* bptr=new Derived();
(bptr->*func_ptr)();
}
My expected output was Base func called
. However, Instead, the output was
Derived func called
Which surprised me, because I think that func_ptr
should be able to see only Base
members(because I thought that func_ptr
doesn't access the member function via _vptr
, but the function address itself.
I would like to know, how the virtual dispatch takes place in this case(how the access to virtual table takes place), and where this behavior is defined in C++ standard(I couldn't find anything)?
this
pointer plus the offset. Since it is pointing to an actual Derived object, that is the function that is running. – Compulsivebptr->func
, the compiler resolvesfunc
toBase::func
too, only then during runtime it is resolved to the correct call. – Whipperin