Here we declared a virtual function bark(), but assign its address to 0. In this case, bark() is a pure virtual function. A class with pure virtual functions is called an abstract class. An abstract class can not be instantiated, but can have pointers and references:
intmain() { Animal a; // No Animal *pa; // Yesreturn0;}
Let's look at another example. Here we defined an abstract class Car, and has a method which returns remaining miles under the current fuel level.
Moreover, we provide an interface to get the remaining miles of the car, and passes in different objects:
doubleshowCarLeftMiles(Car&car) { cout <<car.getName() <<" "<<car.getLeftMiles() << endl;}​intmain() { Benz a("Benz",20.0); Audi b("Audi",20.0); BMW c("BWM",20.0);showCarLeftMiles(a); // Benz 400showCarLeftMiles(b); // Audi 360showCarLeftMiles(c); // BMW 380return0;}
Now in showCarLeftMiles(), the parameter is a Car object instead of a pointer, isn't it a static binding? How can we achieve polymorphism? Of course it is a static binding here, but notice that in Car::getLeftMiles(), the virtual function getMilesPerGallon() is called with this->getMilesPerGallon(). Since *this is a Car pointer, it is still a dynamic binding, so the corresponding method of different objects is called.