There is a base-class Base and two possible derived classes DerivedA and DerivedB. How can I declare a variable without specifying (at the point of declaration) which of the two derived classes will be in use?
I have tried the following example:
#include <iostream>
#include <vector>
#include <memory>
using namespace std;
#include <stdlib.h>
struct Base
{
int base = 0;
};
struct DerivedA : Base
{
int x = 1;
};
struct DerivedB : Base
{
int y = 1;
};
class Test
{
public:
Test(int a)
{
Base TestObj;
if (a==0)
{
DerivedA TestObj; // intention: change type of TestObj to DerivedA
}
else
{
DerivedB TestObj; // intention: change type of TestObj to DerivedB
}
TestObj.base = 7;
if (a==0)
{
TestObj.x = 2;
}
else
{
TestObj.y = 4;
}
myObjs.push_back(make_shared<Base>(TestObj));
}
private:
vector<shared_ptr<Base>> myObjs;
};
The compiler will throw an error saying "error: ‘struct Base’ has no member named ‘x’ " (or 'y' respectively).
A trivial solution would be to include everything in the first if (a==0) / else statements using a separate myObjs.push_back call for the two cases. However, I am interested in a solution where I can stay more flexible, ideally by e.g. only changing the line 'Base TestObj;' to something more general. Thanks in advance.
If you want to keep the flow the same, then you just need to make TestObj
a std::shared_ptr<Base>
to begin with. That would make the code
Test(int a)
{
std::shared_ptr<Base> TestObj;
if (a==0)
{
TestObj = std::make_shared<DerivedA>();
}
else
{
TestObj = std::make_shared<DerivedB>();
}
TestObj->base = 7;
if (a==0)
{
static_cast<DerivedA&>(*TestObj).x = 2; // need the cast so you can set the member
}
else
{
static_cast<DerivedB&>(*TestObj).y = 4; // need the cast so you can set the member
}
myObjs.push_back(TestObj);
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments