How do I make a base class virtual function so that it always is called when a derived class calls its version of the function? I know I can call the base classes function by writing something like BaseClass::foo()
at the beginning of the the function DerivedClass::foo()
, but what if I want it to be called by default, without the creator of the derived class even knowing that the base classes function does anything?
class BaseClass
{
BaseClass();
virtual void foo() {
printf("base");
}
}
class DerivedClass : public BaseClass
{
DerivedClass();
void foo() {
printf("derived");
}
}
int main()
{
DerivedClass dc;
dc.foo();
}
Should print:
base
derived