How can I create an array which can hold objects of different classes in C++?
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.
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
Have a look at boost::fusion which is an stl-replica, but with the ability to store different data types in containers
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With