Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create an array of classes in c++?

Tags:

c++

arrays

Code:

struct Base { ... };

struct A : public Base { ... };
struct B : public Base { ... };
struct C : public Base { ... };

Is it possible to create an array, that holds that types of struct? sample/expected result:

Type inheritedTypesOfStruct[3] = {A, B, C};

The purpose of this is that I later want to create an object with a random class retrieved from the array.

like image 460
justi Avatar asked Jan 02 '12 15:01

justi


1 Answers

You could create an array of functions, each of which returns a base pointer(or smart pointer) that each point to objects of your various derived classes. e.g.

typedef std::unique_ptr<Base> base_ptr;

template<typename Derived>
base_ptr CreateObject()
{
    return base_ptr(new Derived);
}

int main()
{
    std::function<base_ptr(void)> f[3] = {
        CreateObject<A>, CreateObject<B>, CreateObject<C>
    };

    base_ptr arr[10];
    for (int i=0; i<10; ++i)
        arr[i] = f[rand()%3]();
}

Here it is in action: http://ideone.com/dg4uq

like image 181
Benjamin Lindley Avatar answered Sep 21 '22 10:09

Benjamin Lindley