How to allocate memory to an array of instances using an abstract class?

There is only a slight misunderstanding in that code. Instead of allocating Base objects, you have to allocate pointers. A pointer can exist at any time.

A pointer to a abstract class, to an incomplete type, and even to void is valid: int main(int argc, char* argv) { int size = 0; Base** bases = new Base*10; basessize++ = new A(); basessize++ = new B(); for (int I = 0; I Test(); } }.

Great answer. I'd throw in some defensive programming.. Set all the pointers to NULL. Memset(bases, NULL, sizeof(Base*)*10); Just to protect myself.

Great answer though. – baash05 Dec 15 '08 at 16:57 baash05, thanks for the praise :) new Base*10(); is enough to nullify them all. I like that feature of new.

– Johannes Schaub - litb Dec 15 '08 at 17:02 Not exception safe. Use boost:ptr_vector rather than an array. – Loki Astari Dec 15 '08 at 18:32 Now that I look at you also leak!

– Loki Astari Dec 15 '08 at 18:33 uk.youtube. Com/watch? V=wRrunDtDqSQ have fun :) – Johannes Schaub - litb Dec 15 '08 at 19:06.

First, make sure that your destructor is also declared as virtual: virtual ~Base(); You're better off storing a an array of pointers to instances: Base** bases = new Base *10.

An array relies on all of its element being of the same size. When you have C++ classes derived from the same base, the instances can be any size at all. So, no matter whether the base is abstract or not, you can't allocate array of base instances, and then put derived instances there.As other answers say, you need to use pointers.

Allocate an array of pointers to base, and then allocate various derived instances and store pointer to them in the array.

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions