After some searching I've yet to find an existing question which address this issue. My apologies if I missed something.
I have a base class with a params structure and setter. I would like to redefine what that params structure looks like in a derived class and set it via a base class pointer. Something like the following for example.
class A
{
public:
struct paramsType
{
int a;
int b;
};
protected:
paramsType params;
public:
void setParams(const paramsType& params) { this->params = params; }
};
class B : public A
{
public:
struct paramsType
{
int c;
int d;
int e;
};
};
class C : public A
{
public:
struct paramsType
{
int f;
};
};
int main () {
A* ptrB = new B();
A* ptrC = new C();
B::paramsType paramsB;
paramsB.c = 0;
paramsB.d = 1;
paramsB.e = 2;
C::paramsType paramsC;
paramsC.f = 3;
ptrB->setParams(paramsB);
ptrC->setParams(paramsC);
delete ptrB;
delete ptrC;
}
I've tried making the base class "setParams" virtual and redefining it in the derived class, however when I call the method via the base class pointer, it has incompatible types.
In the real use case B and C share a ton of functionality which is implemented in A. They just have different parameter sets. I only have access to a base class pointer, but will know if the object is a B or a C. Is there an elegant way to address this?
Thanks!