Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Virtual Const Function

Tags:

c++

Given the following snippet,

class Base
{
public:
    virtual void eval() const
    {
        std::cout<<"Base Const Eval\n";
    }
};

class Derived:public Base
{
public:
    void eval()
    {
        std::cout<<"Derived Non-Const Eval\n";
    }
};

int main()
{

    Derived d;
    Base* pB=&d;

    pB->eval(); //This will call the Base eval()

    return 0;
}

Why the pB->eval() will call the Base::eval()?

Thank you

like image 370
q0987 Avatar asked Sep 30 '10 02:09

q0987


1 Answers

In your Derived class, the prototype for eval doesn't match the one for the virtual function in Base. So it won't override the virtual function.

Base::eval() const;
Derived::eval(); //No const.

If you add the const for Derived::eval(), you should get virtual behavior.

like image 138
JoshD Avatar answered Oct 11 '22 19:10

JoshD