Reputation: 31
Here is the code:
#include <iostream>
class A
{
public:
void foo()
{
cout<<"this is base foo()"<<endl;
}
void callfoo()
{
foo();
}
};
class B: public A
{
public:
void foo()
{
cout<<"this is child foo()"<<endl;
}
};
int main()
{
B b;
b.callfoo(); //Output: "this is base foo()"
b.foo(); //Output: "this is child foo()"
return 0;
}
Now when I call b.callfoo()
, instead of calling the foo()
of child class B, callfoo()
calls foo()
of base class A. In class B we have overridden foo()
with a new implementation, but still callfoo()
is calling the base foo()
instead of the child foo()
. Please help if you have any explanation for this behaviour.
Upvotes: 2
Views: 2025
Reputation: 37940
In C++, you need to explicitly mark methods as overridable by adding the virtual
keyword: virtual void foo()
.
Upvotes: 3