Test1: # Include < Iostream >
Using Namespace STD;
Class Base
{
Public :
Virtual ~ Base ()
{
Cout < " Base dtor! " < Endl;
}
};
Class Derived: Public Base
{
Private :
Virtual ~ Derived ()
{
Cout < " Derived dtor! " < Endl;
}
};
Int Main ()
{
Derived * PD = New Derived;
// Delete PD; // Error, which is equivalent to calling Pd-> ~ Derived ()
Base * PB = New Derived;
Delete Pb;
Return 0;
}
/*
* The base dtor is visible. Although it is virtual to the derived dtor, the so-called dynamic binding can break through the access permission. In fact, the access permission is only valid during the compilation period, it is easy to understand the above when you think about the compilation phase and runtime.Code
*
*/
Test2:# Include<Iostream>
Using NamespaceSTD;
Class Base
{
Public :
Void Destroy () // Pseudo destructor
{
Cout < " Dtor " < Endl;
Delete This ;
}
Private:
~Base (){}
};
int main ()
{< br> base * Pb = New base; // OK
Pb -> destroy ();
Base B;//Error: "cannot access private member declared in class 'base '"
B. Destroy ();
Return 0;
}
/*
Both static and common member functions can delete such an object through delete or delete this.
This type of private dtor, coupled with the pseudo-destructed member function just mentioned, allows only new to be used to create object instances,
You cannot directly define the effect of an instance.
*/
/*Because B is a local variable (auto), The Destructor will be called at the end of life, and the Destructor is private*/