Search code examples
c++inheritancepolymorphismvirtual-functionsdynamic-binding

Trying to understand dynamic binding and virtual functions


Given the codes below:

class Base
{
public:    
    virtual void f()
    {
        std::cout << "virtual Base::f()\n";
    }
};

class D1 : public Base
{
public:
    virtual void f()
    {
        std::cout << "virtual D1::f()\n";
    }
};

int main()
{
    D1 d1;
    Base *bp = &d1;
    bp->f();
    return 0;
}

The output was exactly what I had expected:

virtual D1::f()
Press <RETURN> to close this window...

But once I removed the virtual void f() from class Base, the compiler complained that:

error: 'class Base' has no member named 'f'

Can anyone tell me why compiler didn't generate codes such that it can bind virtual functions at rum time?


Solution

  • You are calling virtual member functions via a pointer to Base. That means that you can only call methods that exist in the Base class. You cannot simply add methods to a type dynamically.