4

Question:

Create an array of at least four pointers to Reader objects. Use the New operator to create at least four pointers to derived class objects and assign them to the array.

I'm not sure If I did it right or not.

Reader is the base class. John, David, Daniel, Mark are the derived class

int main(void)
{
     Reader *obj[4];

    obj[0] = new John();
    obj[1] = new David();
    obj[3] = new Daniel();
    obj[2] = new  Mark();

}

Would this be right???

7
  • Looks OK to me. Add return 0; to the end though. Commented Jun 2, 2011 at 8:36
  • 1
    You've got a memory leak - you have to delete them later. Commented Jun 2, 2011 at 8:36
  • 1
    @Segey: Bad suggestion here. He has been specifically asked to use pointer array. This seems to be a homework kind of thing. I am all in favor of std::vector but not a good suggestion in this particular case. Commented Jun 2, 2011 at 8:52
  • Especially if he wants polymorphism. Commented Jun 2, 2011 at 9:31
  • @DeadMG do you think that polymorph pointers can not be stored in std::vector? Commented Jun 5, 2011 at 0:36

1 Answer 1

5

Your code is correct.

And as @sharptooth suggested, make a practice of delete on the allocated obj[]s. In C++ new allocates memory and delete deallocates.

Sign up to request clarification or add additional context in comments.

3 Comments

in this case, delete[] obj is needed to correctly destruct and delete all objects and their pointers in the array
@eFloh delete [] obj is a terrible idea. It is wrong. 'obj' is a local variable. It is not allocated so you must not delete it. It will be destroyed when it goes out of scope. This destruction will do nothing because pointers don't have destructors. However, obj[0-3] contain pointers to allocated objects. Those must be deleted with "delete obj[0];", etc. Note that since this is incomplete code we cannot tell whether it is correct. Does Reader have a virtual destructor?
sorry, jumped up on @sharptooth proposal without noticing this. I mainly focused on the fact that arrays should be allocated using new[] and destroyed using the array variant of delete...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.