1

I have this code :

 Derived **args = new Derived*[2];
 args[0] = new Derived();
 args[0]->setname("BLABLA \n");
 cout << args[0]->getname();
 delete args[0];

 args[1] = new Derived();
 args[1]->setname("BLABLABLA\n");
 cout << args[1]->getname();
 delete args[1];
 delete [] args;

Is delete [] args required? And why?

Also, what does Derived **args = new Derived*[2] really do? Does it allocate space for two pointers to Derived? If so, then how can I dynamically create an array that contains 2 objects of type Derived on the heap?

trincot
  • 317,000
  • 35
  • 244
  • 286
Kam
  • 5,878
  • 10
  • 53
  • 97

1 Answers1

1

Is delete [] args required? And why?

Yes it is. It frees the memory allocated by new Derived*[2].

Also, what does Derived **args = new Derived*[2] really do?

It allocates space for two pointers to Derived. It does not allocate space for any Derived objects.

how can I dynamically create an array that contains 2 objects of type Derived on the heap?

Just remove one level of indirection:

 Derived *args = new Derived[2];

 args[0].setname("BLABLA \n");
 cout << args[0].getname();

 args[1].setname("BLABLABLA\n");
 cout << args[1].getname();

 delete [] args;

But bear in mind that arrays and polymorphism don't mix. For details, see How to make an array with polymorphism in C++?

Community
  • 1
  • 1
NPE
  • 486,780
  • 108
  • 951
  • 1,012
  • 1
    @SteveWellens: To be specific, it frees the array of pointers but definitely does __not__ free the objects the pointers point to. – Blastfurnace Dec 09 '12 at 18:20
  • Right, I just deleted my comment. – Steve Wellens Dec 09 '12 at 18:20
  • What do you mean by "It allocates space for two pointers to Derived"? so basically I just created an array of size 2 that hold pointers to an object of type Derived? if so, then how can I dynamically create an array that contains 2 objects of type Derived on the heap? – Kam Dec 09 '12 at 18:21
  • @NPE: Yes polymorphism! exactly, I need to use args[0] as a pointer to Dervived object since I'd like to use polymorphism on that object later on :$ That's why I couldn't go with the second solution you proposed – Kam Dec 09 '12 at 18:28