2 Definition and usage

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
 
1class A 
2{ 
3  public
4    virtual void m1(void) = 0; 
5    void concrete(void{ m1(); } 
6};

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.


Listing 2:subclass
 
7class B : public A 
8{ 
9  public
10    virtual void m1(void{ ... } 
11};

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
 
12class C : public A 
13{ 
14  public
15    virtual void m1(void{ ... } 
16}
17 
18void test(void
19{ 
20  A *pA[2]; 
21 
22  pA[0] = new B; 
23  pA[1] = new C; 
24  for (int i = 0; i < 2; ++i) 
25  { 
26    pA[i]>m1(); 
27    pA[i]>concrete(); 
28  } 
29  for (int i = 0; i < 2; ++i) 
30  { 
31    delete pA[i]; 
32  } 
33}

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).