I have the following code, in which is created array of 10 elements (5 objects of class D1 and 5 of class D2). At the end, the program calls base class destructor (ten times), because of automatic conversion of D1* (or D2*) to B*, right? My problem is how to make the program calls the destructors from derived classes. Can you help me? Thanks.
***I think you are labouring under an illusion here.***
B array_B [10]; is an array of class B objects.
if you create any of the derived classes and then try to
assign it to an object of class B (like you are trying to do here - array_B[i] = *B::create(i);)
then only the B part of the derived object will be copied over to B object.
B object = derived object ;// only the B object from the derved object will be copied.
**ALSO**
You will have major memory leaks - you have lost the pointers to all those objects that werecreated in the create function using new - so you can no
longer delete them.
To answer the original question, use a virtual destructor. This is the exact reason that you should always use a virtual destructor if you think you will derive from a class.
Also, like gulkan pointed out, you're only assigning the base, since you're using values and not pointers.
array_B[i] = */*HERE*/B::create(i);
Where I marked HERE, you are taking the value of the pointer that create returns and trying to assign it to a B object.