Search code examples
c++pure-virtual

Is this a legal way to implement impure virtual functions?


By an "impure virtual function", I mean pure virtual functions that also have implementations (as described at http://www.gotw.ca/gotw/031.htm) for diagnostic purposes.

The kosher way to implement them is to do:

class Foo
{
public:
    ...
    virtual void Bar() = 0;
};

void Foo::Bar() { assert(false); }

But this is kind of tedious, especially for a class has a number of pure virtual methods. Also, it's hard to ensure that someone doesn't accidentally add a new pure virtual function without also adding a corresponding implementation.

Ideally what I'd like to do is:

class Foo
{
public:
    ...
    virtual void Bar() = 0
    {
        assert(false);
    }
};

but the C++ standard explicitly disallows this (section 10.4/2 in the ISO C++ 2003 standard).

As an alternative, I've thought of the following hack. In the Foo.h header:

#ifndef ABSTRACT_METHOD
#define ABSTRACT_METHOD = 0
#endif

class Foo
{
public:
    ...
    virtual void Bar() ABSTRACT_METHOD;
};

and then in the corresponding Foo.cpp source file:

#define ABSTRACT_METHOD { assert(false); }

#include "Foo.h"

...

so that it gets a single compiled implementation.

Would doing so be legal?


Solution

  • No, it's not legal. The one definition rule says that a class can have multiple definitions in a program (from different translation units), but those definitions must all consist of identical sequences of tokens (3.2/5). ABSTRACT_METHOD is a preprocessing token (prior to macro replacement), but that's not good enough.

    So your .cpp file can't validly be used in the same program as another .cpp that includes the header.