It looks like you have provided a simplified version of your code to make it more readable, but you have oversimplified inadvertently.
The most likely reasons for your behaviour are:
- Slicing in
FuncCaller()
(see quamrana's answer for the details)
- Wrong overriding, such as making the derived class function
const
, while the base class function is not const
EDIT: After reading the edited question, it is clearly the second reason. You are not overriding the base class function, but hiding it in the derived classes with a new definition. You need to keep exactly the same signature (covariance does not apply here, since the function returns void
) in the derived classes. In code, you need to do either:
class SomeParam;
class IBase
{
public:
virtual void Func(SomeParam* param = NULL)
{
cout << "Base func";
}
};
class DerivedA : public IBase
{
public:
void Func(SomeParam* param = NULL)
{
//do some custom stuff
cout << "DerivedA func";
IBase::Func();
}
};
class DerivedB : public IBase
{
public:
void Func(SomeParam* param = NULL)
{
//do some custom stuff
cout << "DerivedB func";
IBase::Func();
}
};
//at somewhere else
void FuncCaller(IBase *instance1, IBase *instance2)
{
IBase *i1 = instance1;
IBase *i2 = instance2;
i1->Func();
i2->Func();
}
DerivedA *a = new DerivedA;
DerivedB *b = new DerivedB;
FuncCaller(a,b);
or
class SomeParam;
class IBase
{
public:
virtual void Func()
{
cout << "Base func";
}
};
class DerivedA : public IBase
{
public:
void Func()
{
//do some custom stuff
cout << "DerivedA func";
IBase::Func();
}
};
class DerivedB : public IBase
{
public:
void Func()
{
//do some custom stuff
cout << "DerivedB func";
IBase::Func();
}
};
//at somewhere else
void FuncCaller(IBase *instance1, IBase *instance2)
{
IBase *i1 = instance1;
IBase *i2 = instance2;
i1->Func();
i2->Func();
}
DerivedA *a = new DerivedA;
DerivedB *b = new DerivedB;
FuncCaller(a,b);