Search code examples
c++dynamic-memory-allocation

Generic class for dynamic arrays in c++


Is it possible to make a generic class that acts as a dynamic array of objects of any type? I want a class that basically does this:

MyObj * obj1 = new MyObj();
MutableArray * arr = new MutableArray();
arr->addObject(obj1);
MyObj * obj2 = arr->objectAtIndex(0);
// obj1 and obj2 now points to the same object

This is what the code would look like. I know this doesn't work, but you get the idea. What I need is some generic type for an object. The array itself just consists of pointers so the size of the object shouldn't matter, right?

So, is this possible?

.h-file

class MutableArray
{
    private:
        class * objs;
        int length;
        int capacity;

    public:
        MutableArray();
        void add(class * obj);
        class objectAtIndex(int index);
};

cpp-file

MutableArray::MutableArray()
{
    length = 0;
    capacity = 0;
}

void MutableArray::add(class * obj)
{
    if(length >= capacity)
    {
        this->enlarge();
    }
    objs[length] = obj;
    length++;
}

void MutableArray::enlarge()
{
    int newCapacity = (capacity * 2)+1;
    class * newObjs = new class[newCapacity]

    if(capacity != 0)
    {
        delete [] objs;
    }

    objs = newObjs;
    capacity = newCapacity;
}

class MutableArray::objectAtIndex(int index)
{
    return objs[index];
}

Solution

  • This has already been invented and is called std::vector<>.