Home > Article > Backend Development > How Can Derived Classes Implement Private Pure Virtual Functions in a Base Class?
Pure Virtual Functions within Private Scope
When encountering code with private, pure virtual functions in a base class, such as in the example provided:
class Engine { public: void SetState( int var, bool val ); void SetState( int var, int val ); private: virtual void SetStateBool( int var, bool val ) = 0; virtual void SetStateInt ( int var, int val ) = 0; };
it may seem like derived classes cannot access these functions to implement them. However, derived classes can override private virtual functions, providing their own implementations. This is not to be confused with the inability of derived class methods to call virtual functions from the base class.
Separation of Interface and Implementation
Private virtual functions allow for the separation of interface specification from the implementation that can be customized in derived classes. The public interface consists of a set of overloaded non-virtual functions that call private, non-overloaded virtual functions. This idiom, known as "Public Overloaded Non-Virtuals Call Protected Non-Overloaded Virtuals," helps manage the hiding rule.
Preventing Hiding
In a scenario where the public interface is not virtual and the virtual implementation is private, the author of the derived class can simply provide their own implementation of the virtual functions without worrying about hiding the base class's members. For example:
class MyTurbochargedV8 : public Engine { private: void SetStateInt(int var, int val ) {/* new implementation */} };
The above is the detailed content of How Can Derived Classes Implement Private Pure Virtual Functions in a Base Class?. For more information, please follow other related articles on the PHP Chinese website!