Class A {
Int a=20;
};
Class B: public A {
Int b=30;
};
Int main ()
{
cout <"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --" & lt;
Pr=new B * B;
A * pt=pr;//the use of a parent class pointer to a subclass object.
cout <"The space object b & lt;"
}
return 0;
}
//pt pointer can traverse to the child object released clean? Pointer to release mechanism is what?
CodePudding user response:
Write a destructor, output a information in the destructor you knewCodePudding user response:
Add A virtual destructor function, b plus A destructorCodePudding user response:
As long as it is on the heap of new pointer or malloc, release it when the system natural know its size, there's no need to worry programmers,Writing the cause of the destructor is, if the class has a pointer, such as
The class T {
Char * STR
};
T t1;
So when you delete a t1, he will not automatically release the STR; Need to release in the destructor, and delete is actually a two step, 1, calling the destructor, 2 release the memory t1,
Besides, the destructor
If A class A, to write A class B inheritance in A
In the destructor of B, he will automatically call A destructor, this is the c + + compiler automatically add,
Back to your question, if A pointer pointing to an object of B is, when you delete this pointer, he won't call B destructor, so let's put A destructor set as virtual.
Because he is A virtual function of the destructor virtual table points to the actual B destructor, when you delete the destructor will automatically call B, and in B destructor compiler will automatically add A, A: : ~ A (), and then delete A resource,