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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With