Home  >  Article  >  Backend Development  >  Why Declare Private Virtual Methods in C ?

Why Declare Private Virtual Methods in C ?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-24 14:09:31491browse

Why Declare Private Virtual Methods in C  ?

Making Private Virtual Methods in C

One might wonder why a private method is declared virtual in C . An example from an open source project illustrates this:

<code class="cpp">class HTMLDocument : public Document, public CachedResourceClient {
private:
    virtual bool childAllowed(Node*);
    virtual PassRefPtr<Element> createElement(const AtomicString& tagName, ExceptionCode&);
};</code>

To understand the advantage of this, we turn to Herb Sutter's insights:

Guideline #2: Prefer Private Virtual Functions

According to Sutter, virtual functions should be declared private. This allows derived classes to override these functions for customization without exposing them directly, as would be the case if they were merely protected.

Virtual functions are meant to provide flexibility, not to be invoked directly from derived class code. Therefore, unless there's a specific need for direct invocation, private is the most appropriate access level for virtual functions.

The above is the detailed content of Why Declare Private Virtual Methods in C ?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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