I am working on an exercise which asks me to take a base class Rodent an开发者_开发知识库d make it a pure abstract class. My understanding of a pure abstract class is that it acts as an interface and only contains pure virtual functions. Although this is an easy exercise I have a problem with the solution provided by the book:
class Rodent
{
public:
virtual ~Rodent() {cout << "Destroy rodent" << endl;}
virtual void run() = 0;
virtual void squeak() = 0;
};
As you can see the author has added a dummy definition for the destructor. Does the adding of this definition not mean that this is an abstract class and not a 'pure' abstract class?
An Abstract class must contain atleast one pure virtual function.
Your class already has two pure virtual functions run()
and squeak()
, So your class is Abstract because of these two pure virtual functions.
You cannot create any objects of this class.
EDIT:
A pure abstract class, is a class that exclusively has pure virtual functions (and no data). Since your destructor is not pure virtual your class is not Pure Abstract Class.
A destructor is required for every class by the rules of C++. If you don't provide one, the compiler will generate one for you.
In my opinion this is still a pure abstract class, because the destructor is an exception to the rule.
The virtual
keyword means something a bit different for destructors. When a base class's dtors are virtual, it means all dtors in the inheritance hierarchy are called. You can't really override it as such.
Usually you'd expect it to be empty:
class Rodent {
public:
virtual ~Rodent() {}
virtual void run() = 0;
virtual void squeak() = 0;
};
I see very little difference. It is possible that because the empty body is a no-op the compiler can ignore it through some language lawyer statute.
I don't think you'd confuse anyone by calling yours pure virtual.
As far as I understand, the C++ standard does not specify a pure abstract class. The C++0x (n3290) however specifies abstract class.
10.4/2 A class is abstract if it has at least one pure virtual function.
The pure abstract class is a conventional term and describes an abstract class that;
- does not have of data members
- does not have of any non-pure virtual functions
- does not have of any concrete functions
specified by user.
So, according to this convention, the class Rodent
is not a pure abstract class.
Consider implementing your interface like so
class Rodent {
public:
virtual ~Rodent() = 0;
virtual void run() = 0;
virtual void squeak() = 0;
};
inline Rodent::~Rodent() {}
Specifying your destructor as pure virtual and inlining the implementation avoids the following warning in MSVC2010 when exporting subclasses:
warning C4275: non dll-interface class 'A' used as base for dll-interface class 'B'
Yes, it is not a pure class anymore. A pure, abstract class has no functionality in it, it just provides a framework. cout is functionality.
精彩评论