Abstract Classes

From Appmethod Topics
Jump to: navigation, search

Go Up to Polymorphic Classes Index

An abstract class is a class with at least one pure virtual function. A virtual function is specified as pure by setting it equal to zero.

An abstract class can be used only as a base class for other classes. No objects of an abstract class can be created. An abstract class cannot be used as an argument type or as a function return type. However, you can declare pointers to an abstract class. References to an abstract class are allowed, provided that a temporary object is not needed in the initialization. For example,

class shape {       // abstract class
    point center;
    // …
    where() { return center; }
    move(point p) { center = p; draw(); }
    virtual void rotate(int) = 0; // pure virtual function
    virtual void draw() = 0;      // pure virtual function
    virtual void hilite() = 0;    // pure virtual function
    // …

shape x;            // ERROR: attempt to create an object of an abstract class
shape* sptr;        // pointer to abstract class is OK
shape f();          // ERROR: abstract class cannot be a return type
int g(shape s);     // ERROR: abstract class cannot be a function argument type
shape& h(shape&);   // reference to abstract class as return
                    // value or function argument is OK

Suppose that D is a derived class with the abstract class B as its immediate base class. Then for each pure virtual function pvf in B, if D does not provide a definition for pvf, pvf becomes a pure member function of D, and D will also be an abstract class.

For example, using the class shape previously outlined,

class circle : public shape {  // circle derived from abstract class
    int radius;// private
    void rotate(int) { }  // virtual function defined: no action
                          //  to rotate a circle
    void draw();  // circle::draw must be defined somewhere

Member functions can be called from a constructor of an abstract class, but calling a pure virtual function directly or indirectly from such a constructor provokes a run-time error.

See Also