oskob
oskob

Reputation: 1376

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

Upvotes: 1

Views: 1770

Answers (4)

K-ballo
K-ballo

Reputation: 81389

Is it possible to make a generic class that acts as a dynamic array of objects of any type?

For the dynamic array use std::vector, for objects of any type use boost::any.

std::vector< boost::any > anything;

Upvotes: 3

cpx
cpx

Reputation: 17577

You want to use STL std::vector.

Upvotes: 2

littleadv
littleadv

Reputation: 20282

Yes. It actually exists and is called std::vector.

Upvotes: 1

David Heffernan
David Heffernan

Reputation: 613412

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

Upvotes: 5

Related Questions