Question

I am in the process of making a very simple game whereby objects (elements Either A or B) fly around the screen, colliding etc.

The only difference between A and B is the color of the object (A = black B = white).

Is it possible to have an Element container container (or 20 elements) to hold 10 A's and 10 B's. I have had a look around, and I can do it if I have a Vector of either type A or Type B but NOT a mixture.

Any help would be much appreciated! Thanks - and Happy belated Easter

KJ

edit: There are a number of different characteristics that A and B both have, for example different speeds they can move about, as well as different abilities. E,g A can shoot a laser but B can't. That is why I am using different classes.

Was it helpful?

Solution

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);

OTHER TIPS

If you really need to store different objects in containers, then maybe:

`boost::any`

is the correct answer?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top