Home > Back-end >  How to store different class objects in a single array/vector?
How to store different class objects in a single array/vector?

Time:04-10

The program I'm writing requires me to implement a certain code so that every class instance that is stored in vectors is accessible within a single array or vector. The problem is that the instances belong to different classes and cannot be stored in a single array/vector by itself. Is there any way that this is possible? I implemented the code below, but unfortunately I got an error message which I couldn't seem to get rid of.

class A {...}; //abstract

class B : public A {...};
class C : public A {...};
class D : public A {...};
class E : public A {...};

vector <B> vecb;
vector <C> vecc;
vector <D> vecd;
vector <E> vece;
vector <A*> mainvec = { vecb, vecc, vecd, vece };

Here is the error I get:

Severity    Code    Description Project File    Line    Suppression State
Error (active)  E0289   no instance of constructor "std::vector<_Ty, _Alloc>::vector [with _Ty=A *, _Alloc=std::allocator<A *>]" matches the argument list       

CodePudding user response:

vector <A*> mainvec = { vecb, vecc, vecd, vece };

This can never work. mainvec expects to hold raw A* pointers, but you are trying to pass it vectors of objects instead.

If you really want a vector to hold other types of vectors, you could use std::variant for that, eg:

std::vector<B> vecb;
std::vector<C> vecc;
std::vector<D> vecd;
std::vector<E> vece;

using VectorVariant = std::variant< std::vector<B>*, std::vector<C>*, std::vector<D>*, std::vector<E>* >;

std::vector<VectorVariant> mainvec = { &vecb, &vecc, &vecd, &vece };
  • Related