C++ containers are homogeneous meaning you can't store different typed objects in them. However you can store pointers to a base type and use two derived A
and B
classes.
However in your case if the only difference is color, I don't see a reason to have different classes. Just have a color property on the class.
In case you need different classes you can use a base class as shown below :
class Base
{
public:
// base properties both classes share
// virtual methods etc.
};
class A : public Base
{
public:
// class A specific methods/properties
};
class B : public Base
{
public:
// class B specific methods/properties
};
Now you can have a vector of Base object pointers these can be either of type A
or B
.
std::vector<Base*> objects;
A *a = new A();
B *b = new B();
objects.push_back(a);
objects.push_back(b);