boom boom - 3 months ago 8
C++ Question

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++?

Answer

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;
}