Private virtual method in C++

silverburgh picture silverburgh · Jan 31, 2010 · Viewed 68.7k times · Source

What is the advantage of making a private method virtual in C++?

I have noticed this in an open source C++ project:

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

Answer

Prasoon Saurav picture Prasoon Saurav · Jan 31, 2010

Herb Sutter has very nicely explained it here.

Guideline #2: Prefer to make virtual functions private.

This lets the derived classes override the function to customize the behavior as needed, without further exposing the virtual functions directly by making them callable by derived classes (as would be possible if the functions were just protected). The point is that virtual functions exist to allow customization; unless they also need to be invoked directly from within derived classes' code, there's no need to ever make them anything but private