Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange syntax in some Design Pattern code: explanation?

OK, I ran into this today, when the TI TMS470 C++ compiler refused to take it.

This comes from the Silver version of the C++ translation of the "Head First Design Patterns" example code.

class foo {
   ...
protected:
   virtual ~foo() = 0 {};  // compiler barfs on this line
};

The compiler refused to accept the combination of "= 0" (pure virtual) and "{}" (I'm guessing that this is to let a derived class throw the destructor up anyway.

What exactly are they trying to do with that line, is it really legal C++, and how critical is it?

like image 402
John R. Strohm Avatar asked Apr 12 '26 02:04

John R. Strohm


1 Answers

It is not legal C++. Pure virtual function can have a body, but the definition has to be made out-of-class.

In this particular case (the function is a destructor), the function must have a body if the class is used anywhere in the program (i.e. if it is used as a base class somewhere, since this is the only way one can use an abstract class).

The proper way do define the whole thing is as follows

class foo {
   ...
protected:
   virtual ~foo() = 0;
};

inline foo::~foo()
{
}
like image 176
AnT Avatar answered Apr 13 '26 16:04

AnT