Call a base class function as a derivative

Is there a way to call a base class method from a virtual function as a derived class, and not as a base? Code example:

class A { public: virtual void a() = 0; void print() { std::cerr << typeid(decltype(*this)).name(); }; }; class B : public A { public: virtual void a() { print(); } }; int main() { B b; ba(); //prints 1A, I want it to print 1B, is it even possible? } 
+7
c ++ c ++ 11
source share
1 answer

Just omit decltype :

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

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

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

+14
source share

All Articles