Reputation: 6166
How can I create an array which can hold objects of different classes in C++?
Upvotes: 6
Views: 4382
Reputation: 523344
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.
Upvotes: 11
Reputation: 13767
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;
}
Upvotes: 1
Reputation: 13099
Have a look at boost::fusion which is an stl-replica, but with the ability to store different data types in containers
Upvotes: 2
Reputation: 5585
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
Upvotes: 3