I'm trying to find a good way to store two different class objects within one vector each object having it's own location within the vector, so the objects can be stored and accessed later when needed.
I have used a structure but then I store everything which the structure has to the vector which isn't what I want, I'll give an example of what I mean.
Class A{
public:
void changeNumber(int x) {number = x;}
private:
int number;
};
Class B{
public:
void changeNumber(int x) {number = x;}
private:
int number;
};
struct Object{
A a;
B b;
};
Class Main{
public:
void storeObject(Object ob) {object.push_back(ob);}
private:
std::vector<Object> objects; //when an object is passed both A and B objects are stored within the vector in the same location
};
Is there a way where I can store two different class objects within one object but only pass one at a time to be stored so I has it's own index within the vector?
If
A
andB
have common functions and you'll be calling only these on the elements of a vector, you can take all common members and member functions and make a base class out of it. Then makeA
andB
derived class ofObject
:In this case,
A
is no different fromB
, so everything is implemented inObject
.Finally, your vector will look like this:
And here's more preferred solution with
std::shared_ptr
which frees the memory for you after the element is removed from the vector or destructed otherwise.Store object:
boost::variant
is the way to go when storing multiple different types on which you cannot use inheritance.If you prefer to use your own "
variant
equivalent". You could do something along the lines ofHowever, I still think that solving this with an appropriate inheritance scheme (as in the other answer) is much cleaner.
You can use
boost::variant
. It is type that can represent a finite set of types, in your example you would have anAn alternative (which does not really fit your usecase, but may for future readers) is
boost::any
. It can represent any type which is useful if you do not have a finite list of possible types at compile time.