Question

Two compilers I tried accept this syntax but I read somewhere that pure virtual destructor definition should be always outside the class. My code which compiles:

class AbstractBase
{
public:
    virtual ~AbstractBase() = 0
    {}

    virtual void foo()
    {
        ...
    }
};
Was it helpful?

Solution

As per the standard you cannot define a pure virtual function inside the class body.
Some compilers do support this functionality as an extension though. Note that using this extension will make your code non-portable accross different compilers.

Reference:

C++03 10.4 paragraph 2:

[Note: a function declaration cannot provide both a pure-specifier and a definition —end note] [Example:

struct C 
{ 
    virtual void f() = 0 { }; // ill-formed 
}; 

—end example]

OTHER TIPS

The syntax doesn't allow for both = 0 and { } at the same, so you are supposed to define the destructor separately, like in the .cpp file.

Some compilers might allow your version as an extension.

Microsoft Visual Studio accepts this syntax, and, frankly, gcc compiler also does not seem to be unhappy about it. However, it's not the compiler you should be worried about, it's linker. Having defined pure virtual destructor inside the class definition (in header file) results in multiple definition of the same symbol. I am not 100% sure how exactly MSVC complier handles this case, but gcc might complain. Also, even with MSVC you may run into a trouble when projects grows and gets split into multiple static/dynamic libraries.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top