Nikola Smiljanić Nikola Smiljanić - 2 months ago 10
C++ Question

Call virtual method from base class on object of derived type

class Base
{
public:
virtual void foo() const
{
std::cout << "Base";
}
};

class Derived : public Base
{
public:
virtual void foo() const
{
std::cout << "Derived";
}
};

Derived d; // call Base::foo on this object


Tried casting and function pointers but I couldn't do it. Is it possible to defeat virtual mechanism (only wondering if it's possible)?

Answer

To explicitly call the function foo() defined in Base, use:

d.Base::foo();