Home > Backend Development > C++ > body text

How Can Derived Classes Implement Private Pure Virtual Functions in a Base Class?

Mary-Kate Olsen
Release: 2024-11-04 06:45:02
Original
150 people have browsed it

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;    
};
Copy after login

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 */}
};
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!