Class base {
Public:
Void novirtualfun ()
{
Printf ("base: novirtualfun ()! /N ");
}
Virtual void virtualfun ()
{
Printf ("base: virtualfun ()! /N ");
}
};
Class classa {
PRIVATE:
Base * m_pbase;
Public:
Classa (): m_pbase (null)
{}
Void addbase (base * pbase)
{
M_pbase = pbase;
}
Void print ()
{
// The access permission used here is the base: virtualfun () access permission (public)
// Therefore, you can use this virtual function in classa, and ignore the permission settings of this function in the derived class child.
M_pbase-> virtualfun ();
}
};
// Note: private inheritance
Class child: Private base {
PRIVATE:
Classa * m_pclassa;
PRIVATE: // Private
Virtual void virtualfun ()
{
Printf ("Child: virtualfun ()! /N ");
}
Public:
Child (classa * pclassa)
{
M_pclassa = pclassa;
M_pclassa-> addbase (this );
}
};
// 1. After private inheritance is used, polymorphism cannot be directly used outside the class scope,
// The pointer of the derived class cannot be automatically converted to the base class pointer.
// 2. After the virtual function is inherited from the base class private, if the virtual function is overloaded in the derived class,
// Set the access permission to public. The virtual function will be a public member function.
Int main (INT argc, char * argv [])
{
Classa * classa = new classa ();
Child * CHD = new child (classa );
// Classa-> addbase (base *) CHD); allows forced transformation as the base class pointer
// Classa-> addbase (CHD); error, cannot be automatically converted to base class pointer
Classa-> Print ();
// If virtualfun () is specified as public in child, this function will be used as a public member function,
// Instead of private member functions inherited by private
// CHD-> virtualfun (); error is a private member. If chlid: virtualfun () is set to public, it is correct.
Delete CHD;
Delete classa;
Return 0;
}
Conclusion:
1. The access permission of a private-inherited virtual function can be specified by the derived class.
2. After private inheritance, the polymorphism cannot be performed outside the scope of the derived class, And the pointer of the derived class cannot be automatically converted to the base class pointer (but the type conversion can be forced ).
3. when a derived class reloads a virtual function with the public permission in the base class and limits it to private or protected, directly using the base class pointer for Polymorphism will ignore the changes to the access permission of the derived class for this virtual function, call the virtual function based on the access permission of the base function.