Answer: When your class is ready to give others inherit, provide a false argument function.
Consider the following example:
Class A
{{
Public:
A () {cout << "in a constructor" << Endl;
~ A () {cout << "in a destructor" << endl;}
}
Class B: Public A
{{
Public:
B ()
{{
COUT << "in b constructor" << endl;
M_P = new char [10];
}
~ B ()
{{
COUT << "in b destructor" << endl;
IF (m_p) delete [] m_p;
}
Private:
CHAR * M_P;
}
Int Main (int Argc, char * argv [])
{{
// Printf ("Hello World! / N");
A * p = new b;
Delete P;
RETURN 0;
}
output results:
In a constructor
b constructor
In a destructor
There is no call to the destructor, and the memory from New has not recycled memory leaks in time.
To solve this problem, just define a destructive function as a virtual function: ~ a () {cout << "in a destructor" << endl;}. Why can you solve it as a virtual function? I understand this:
like other imaginary functions, ~ b () redefine (OVERRIDEN) is ~ a (), which pointing to the pointer to derived class to call B's destructor based on the state of the runtime. There is another problem here: Why will I call A destructor? I can only understand that the destructor is a special function, which is maintained by the system. Just like B. ~ a () is wrong, B. ~ B () (although logically is wrong, the syntax is correct, compiling and running is completely no problem) is the same.
An Idea for this?