Click here to Skip to main content
15,886,422 members

Response to: dynamic array of interfaces

Revision 1
If you are using polymorphism then you have to use a pointer or reference, you can not achieve polymorphism with values.
In this case:
C++
MyInterface *a;
a = new MyClass[n];
for (int i=0; i<n;>    a[i].myFunction ();
}

Your MyInterface *a "array" stores the the class instances themselves as values. Your assignment a = new MyClass[n]; compiles (compiles - not works) just because you explited a relatively dangerous trait of C, that is array identifiers of type T and pointers to type T are exchangeable and auto-casted in most situations (except for a few cases with templates and function parameters).

Both solution A and B are correct though. Your A case takes much more memory because you allocated a lot of small chunks instead of one big chunk and that can lead to memory fragmentation if you regularly free/allocate chunks but in your case the extra wasted space probably comes from memory usage of your allocator that uses some extra memory per allocated block to keep track of allocated/free space in your heap.

However if you need to provide MyInterface **a then you can mix solution A and B as an optimization, you allocate both a MyInterface **a like in solution A and a MyClass *b like in solution B and then later you can fill in the a interface pointers to point to the items of the b array.
Posted 21-Sep-12 4:08am by pasztorpisti.
Tags: