User Tools

Site Tools


negix:purevirtualisnt

Pure virtual isn't that pure

Anyone who has dabbled with C++ for a while has come about the construct for a “pure virtual” function. Generally speaking, it is a function whose existence is declared in an abstract base class, but for which a definition is only provided in a derived class.

At least, that is what I thought for many, many years:

class Base
{
    public:
        virtual void func() = 0;
};

Imagine my surprise when I found that, given the above declaration, it is perfectly legal to define that “pure virtual” function:

virtual void Base::func()
{
    std::cout << "Hello\n";
}

While it doesn’t make much sense to me on the semantic level, it allows an abstract base class to define “common denominator” code for derived classes to call:

class Derived : public Base
{
    public:
        virtual void func()
        {
            Base::func();
            std::cout << "Hello again!\n";
        }
};

Is it possible? Yes. Is it surprising to even seasoned C++ coders? Yes. (A quick poll at the office showed four out of four people didn’t know about it, and thought the above code to be illegal.) Should you use this construct? In my opinion, only if there is a very compelling reason to do so, simply because it is so surprising. I don’t like to be surprised by code.

negix/purevirtualisnt.txt · Last modified: 2018/09/10 16:21 (external edit)