Home > Back-end >  Pointer to the parent class c subclass object, how to release the clean subclass object?
Pointer to the parent class c subclass object, how to release the clean subclass object?

Time:09-21

Small white has just started to learn c + +, for help: the problem is more specific point: pointer is rely on what to judge how much space I should release?
Class A {
Int a=20;
};
Class B: public A {
Int b=30;
};
Int main ()
{
cout <"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --" & lt; for (int i=0; I & lt;=10000; + + I) {
Pr=new B * B;
A * pt=pr;//the use of a parent class pointer to a subclass object.
cout <"The space object b & lt;" cout <"Access to the pointer points to the space size:" & lt; The delete pt;//use the pointer to the parent class release, whether can cause memory leaks?
}
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 knew

CodePudding user response:

Add A virtual destructor function, b plus A destructor

CodePudding 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,
  • Related