How can I create an array which can hold objects of different classes in C++?
4 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.
2 Comments
Variant over Any if the collection is known. Static check is a huge appeal. It's also a faster, which is a nice bonus.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
6 Comments
Have a look at boost::fusion which is an stl-replica, but with the ability to store different data types in containers
Comments
If you want to create your own, wrap access to a pointer/array using templates and operator overloading. Below is a small example:
#include <iostream> using namespace std; template <class T> class Array { private: T* things; public: Array(T* a, int n) { things = new T[n]; for (int i=0; i<n; i++) { things[i] = a[i]; } } ~Array() { delete[] things; } T& operator [](const int idx) const { return things[idx]; } }; int main() { int a[] = {1,2,3}; double b[] = {1.2, 3.5, 6.0}; Array<int> intArray(a, 3); Array<double> doubleArray(b, 3); cout << "intArray[1]: " << intArray[1] << endl; }