Destructors of derived class

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream>
using namespace std;

class B {
public: 
static B* create(int);
virtual ~B() {cout<< "B\n";}
B(){}
};

class D1 : public B {
protected:
~D1 () {cout<<"D1\n";}
};

class D2 : public B {
protected:
~D2 () {cout<<"D2\n";}
};

B* B::create (int i) {
if (i%2) return new D1();
else return new D2();
}

void main () {
B array_B [10];
for (int i=0, i<10; i++)
array_B[i] = *B::create(i);
}
***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.

You want something like this:
 
B *pB = B::create(i);
Last edited on
Topic archived. No new replies allowed.