class Foo
{
public:
void action();
};
class Bar : public Foo
{
public:
void action();
};
void Foo::action ()
{
cout << "parent\n";
};
void Bar::action ()
{
cout << "child\n";
};
int main()
{
Foo* foo = new Bar ();
foo->action(); // returns "parent" - "child" expected
return 1;
}
I’m sorry for a probably trivial question, but I’m new to C++…
The ‘foo’ pointer must point to an instance of Foo class, since it can be any of Foo’s childs e.g. Bar, Bar1, Bar2, Bar3 etc.
And at the same time ‘foo->action()’ should run an overridden function of the child.
Tell me please, how do I correct the code to reach my goals…
Thanks!
Unlike other languages, like Java, in C++ base class have to specifically mark the methods it allows overriding of by using keyword
virtual