jkbz64 jkbz64 - 10 months ago 66
C++ Question

Invoke base class function as derived

Is there any way to call base class method from virtual function as derived class, not as base one?
Example code:

class A
virtual void a() = 0;
void print() { std::cerr << typeid(decltype(*this)).name(); };

class B : public A
virtual void a() { print(); }

int main()
B b;
b.a(); //prints 1A, I want it to print 1B, is it even possible?


Just drop the decltype:

void print() { std::cerr << typeid(*this).name(); };

this always points to an instance of the class whose member function its in. this inside A is always an A*. So typeid(decltype(*this)) always gives you A.

On the other hand, typeid(*this) will lookup runtime type information, which will determine that this is really a B (because A is a polymorphic type).