Concepts of Programming Languages

(Sean Pound) #1

546 Chapter 12 Support for Object-Oriented Programming


ptr_shape = sq; // Now ptr_shape points to a
// Square object
ptr_shape->draw(); // Dynamically bound to the draw
// in the Square class
rect->draw(); // Statically bound to the draw
// in the Rectangle class

This situation is shown in Figure 12.6.
Notice that the draw function in the definition of the base class shape is set
to 0. This peculiar syntax is used to indicate that this member function is a pure
virtual function, meaning that it has no body and it cannot be called. It must be
redefined in derived classes if they call the function. The purpose of a pure virtual
function is to provide the interface of a function without giving any of its imple-
mentation. Pure virtual functions are usually defined when an actual member

Figure 12.6


Dynamic binding


Shape

virtual void draw ( ) = 0

Rectangle

Rectangle

Rectangle*

Square

Objects

Square*

Class Hierarchy

Types Pointers Bindings

sq

rect

Shape*

void draw ( ) { ... }

void draw ( ) { ... }

void draw ( ) { ... }

void draw ( ) { ... } void draw ( ) { ... }

Circle

ptr_shape Square
Free download pdf