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!