An abstract class is one that has at least one abstract method. An abstract method is a virtual method that is just a “stub”, and is not implemented. Listing 1 is an example.
Listing 1: | abstractclass |
Note that an abstract class may have members like any other class. It can have public data members, private methods and etc. Aside from having an abstract method, an abstract class (as opposed to a concrete class) also has a restriction: it cannot be used to create objects. In our example, we cannot create objects of class A using A myA; or pA = new A;. This is quite understandable, as the class is not fully implemented.
In order to use an abstract class, a subclass in the inheritance hierarchy needs to implement all the abstract methods. In our example, let us continue the code in listing 2.
Note that method B::m1 is said to implement A::m1, not to override. Because class B has no abstract methods, we can create objects of B.
Other than the fact that we cannot objects from class A, it can still serve most of the functions of a polymorphic superclass. Let us continue our code in listing 3.
Listing 3: | useabsclass |
In this class, pA[0]->m1() invokes B::m1(void), while pA[1]->m1() invokes C::m1(void) because m1 is a virtual method. Not surprisingly, pA[0]->concrete() ends up calling B::m1(void), and pA[0]->concrete() ends up calling C::m1(void).