C++ copy pointer value to pointer array

时间:2015-10-29 15:52:32

标签: c++ pointers const abstract

i am having problem with my code.

I have one abstract class Object and 4 other classes which inherit from Object. Then i have something like Collection class which stores Objects in pointer array. I had a problem to create such array but i have found this:

Object** array = new Object*[count];

which solved my problem.

Problem is with method in my collection which looks like this:

class Collection
{
public:
   void addObjectToArray(const Object* const obj)
private:
   Object **array;
   size_t size, capacity
}

Then comes the problem. In my main i can make something like this: lets assume that one of inherited class is Ball.

Object* ball = new Ball();

this works fine but if i call method addObjectToArray in my collection then it crashes. Here is body of the method:

void addObjectToArray(const Object* const obj)
    {
       if (size < capacity)
       {
           *array[size] = *obj;  <<<----- problem
           ++size;
       }
       else
       {
           throw std::out_of_range("No more space for objects");
       }
    }

I think that main problem is that i do not create copy.

Any help? Thank you

<-----> UPDATE <-----> Solved this by

array[size] = const_cast<Object*>(obj)

But i think that this is not great way of programming. What do you think?

0 个答案:

没有答案