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?
Yes it is. It frees the memory allocated by
new Derived*[2].It allocates space for two pointers to
Derived. It does not allocate space for anyDerivedobjects.Just remove one level of indirection:
But bear in mind that arrays and polymorphism don’t mix. For details, see How to make an array with polymorphism in C++?