Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invoke base class function as derived

Tags:

c++

c++11

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

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;
    b.a(); //prints 1A, I want it to print 1B, is it even possible?
}
like image 580
jkbz64 Avatar asked Sep 23 '16 13:09

jkbz64


1 Answers

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).

like image 190
Barry Avatar answered Oct 19 '22 06:10

Barry