View Single Post
Old Apr 13th, 2006, 11:44 PM   #2
grumpy
Programming Guru
 
grumpy's Avatar
 
Join Date: Jun 2005
Location: Adelaide, South Australia
Posts: 1,223
Rep Power: 5 grumpy is on a distinguished road
Very loosely, yes. You've mixed up a couple of terms.

If you wish to create a set of classes that are all derived from a common base, but don't wish to instantiate the base class, give it at least one pure virtual function. For example, if your base class is Fish, and derived classes represent specific species of fish, it does not make sense to instantiate a Fish.

The other purpose of pure virtual functions is to force derived classes to specialise particular behaviours offered by the base class. All a user of the class needs is a pointer (or reference) to the base class, and it can call a member function and know that the behaviour for the actual (instantiated) class will occur. Using my Fish example, one candidate for a pure virtual function would be named Feed(). All types of fish will have some type of feeding behaviour, but it doesn't necessarily make sense for a representation of a generic Fish to to be specific about what that behaviour is.

Technically, a base class can declare a pure virtual function, and also [optionally] define it (provide an implementation). A derived class, unless it overrides that inherited function (i.e. declares it) cannot be instantiated. As a rough rule, if a derived class overrides an inherited pure virtual function, it must also provide a definition (i.e. provide an implementation of it). The compiler won't complain about a lack of definition of an overridden virtual function, but the linker probably will (with the result that it is not possible to build the overall application).

Destructors can also be pure virtual: a simple way to ensure a base class cannot be instantiated even if it has no other pure virtual functions.
grumpy is offline   Reply With Quote