Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

creating an array which can hold objects of different classes in C++

How can I create an array which can hold objects of different classes in C++?

like image 680
boom Avatar asked May 04 '10 11:05

boom


3 Answers

You can use boost::any or boost::variant (comparing between the two: [1]).

Alternatively, if the "objects of different classes" have a common ancestor (say, Base), you could use a std::vector<Base*> (or std::vector<std::tr1::shared_ptr<Base> >), and cast the result to Derived* when you need it.

like image 86
kennytm Avatar answered Sep 28 '22 07:09

kennytm


define an base class and derive all your classes from this.

Then you could create a list of type(base*) and it could contain any object of Base type or derived type

like image 30
SysAdmin Avatar answered Sep 28 '22 07:09

SysAdmin


Have a look at boost::fusion which is an stl-replica, but with the ability to store different data types in containers

like image 41
Viktor Sehr Avatar answered Sep 28 '22 05:09

Viktor Sehr