Implementing pure virtual functions

January 09, 2013

Dan_Saks-January 09, 2013

C++ makes calling a pure virtual function nearly impossible. A class with at least one pure virtual function is called an abstract class. C++ doesn't let you create an abstract class object except as the base class subobject of some derived class object. For example, these declarations won't compile:

shape s;            // compile error
shape x[10];        // compile error

You can declare a pointer to a shape, as in:

shape *ps;          // OK

However, the compiler will reject a new-expression that tries to construct an abstract base class object, as in:

ps = new shape;     // compiler error

Again, any class with at least one pure virtual function is an abstract class. If you can't create any such objects, then you don't have to worry that you might call a pure virtual function. Unfortunately, C++ compilers have trouble detecting all possible calls to pure virtual functions, such as when the constructor of an abstract class indirectly calls a pure virtual function of the same class. Thus, most compilers provide another line of defense. More on this shortly.

The definition for our circle class derived from shape looks like:

class circle: public shape {
   circle(double r, color o, color f);   // constructor
   virtual double area() const;
   virtual double perimeter() const;
   double radius;

If you don't declare the area and perimeter functions in circle, then circle will inherit them as pure virtual functions, and circle will be an abstract class. You won't be able to create any circle objects. However, the class definition above does declare area and perimeter, so they're not pure virtual and circle isn't an abstract class. Now you're on the hook to define circle's area and perimeter functions.

Inasmuch as circle is not an abstract class, you can create circle objects, as in:

circle c (3);


shape *ps = new circle (4);

If the compiler could detect and prevent all calls to pure virtual functions, implementing pure virtual functions would be trivial--simply initialize the vtbl entry for each pure virtual function as a null pointer. In C, the code to define the vtbl for the shape base class would look something like:

typedef struct shape_vtbl shape_vtbl;
struct shape_vtbl {
   double (*area)(shape const *);
   double (*perimeter)(shape const *);

shape_vtbl the_shape_vtbl = {
   0,    // 0 converted to null pointer
   0     // ditto

< Previous
Page 2 of 3
Next >

Loading comments...