C++ Abstract Class Concept - dummies

By Stephen R. Davis

An abstract class in C++ is a class with one or more pure virtual functions. A pure virtual function is a virtual member function that is marked as having no implementation. Most likely it has no implementation because no implementation is possible with the information provided in the class, including any base classes.

A conventional, run-of-the-mill non-pure virtual function is known as a concrete function (note that a concrete function may be virtual — unfortunately, C++ uses this term to mean polymorphic.

The syntax for declaring a function pure virtual is demonstrated in the following class Account:

// Account - this class is an abstract class
class Account
    Account(unsigned accNo, double initialBalance = 0.0);
    // access functions
    unsigned int accountNo( );
    double acntBalance( );
    static int noAccounts( );
    // transaction functions
    void deposit(double amount);
    // the following is a pure virtual function
    virtual void withdrawal(double amount) = 0;
    // keep accounts in a linked list so there's no limit
    // to the number of accounts
    static int count;     // number of accounts
    unsigned  accountNumber;
    double    balance;

The = 0 after the declaration of withdrawal() indicates that the programmer does not intend to define this function. The declaration is a placeholder for the subclasses. The subclasses of Account are expected to override this function with a concrete function. The programmer must provide an implementation for each member function not declared pure virtual.

Some programmers think this notation is silly. But it’s here to stay, so you just have to learn to live with it. There is a reason, if not exactly a justification, for this notation. Every virtual function must have an entry in a special table.

This entry contains the address of the function. Presumably, at least at one time, the entry for a pure virtual function was 0. In any case, it’s the syntax you’re stuck with now.

An abstract class cannot be instanced with an object; that is, you can’t make an object out of an abstract class. For example, the following declaration is not legal:

void fn( )
    // declare an account with 100 dollars
    Account acnt(1234, 100.00);// this is not legal
    acnt.withdrawal(50);       // what would you expect
}                              // this call to do?

If the declaration were allowed, the resulting object would be incomplete, lacking in some capability. For example, what should the preceding call do? Remember, there is no Account::withdrawal().

Abstract classes serve as base classes for other classes. An Account contains all the properties associated with a generic bank account. You can create other types of bank accounts by inheriting from Account.

The technical term is to instantiate. You say that the Account class cannot be instantiated with an object or a given object instantiates the Savings class.