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

Why Declare Private Virtual Methods in C ?

Mary-Kate Olsen
Release: 2024-10-24 14:09:31
Original
587 people have browsed it

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

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!

source:php
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