Redefining Functions in C++

A function defined in the base class can be redefined in the derived classes.

The toString() function is defined in the GeometricObject class to return a string “Geometric object” (lines 35-38 in Listing 15.2) as follows:

string GeometricObject::toString() const {

return “Geometric object”;

}

To redefine a base class’s function in the derived class, you need to add the function’s pro­totype in the derived class’s header file, and provide a new implementation for the function in the derived class’s implementation file.

The toString() function is redefined in the Circle class (lines 55-58 in Listing 15.4) as follows:

string Circle::toString() const {

return “Circle object”;

}

The toString() function is redefined in the Rectangle class (lines 63-66 in Listing 15.6) as follows:

string Rectangle::toString() const {

return “Rectangle object”;

}

So, the following code

1 GeometricObject shape;
2 cout <<
“shape.toString() returns ” << shape.toString() << endl;
3

4 Circle circle(5);
5 cout <<
“circle.toString() returns ” << circle.toString() << endl;
6
7 Rectangle rectangle(
4, 6);
8 cout <<
“rectangle.toString() returns ”
9 << rectangle.toString() << endl;

displays:

The code creates a GeometricObject in line 1. The toString function defined in GeometricObject is invoked in line 2, since shape’s type is GeometricObject.

The code creates a Circle object in line 4. The toString function defined in Circle is invoked in line 5, since circle’s type is Circle.

The code creates a Rectangle object in line 7. The toString function defined in Rectangle is invoked in line 9, since rectangle’s type is Rectangle.

If you wish to invoke the toString function defined in the GeometricObject class on the calling object circle, use the scope resolution operator (::) with the base class name. For example, the following code

Circle circle(5);

cout << “circle.toStringO returns ” << circle.toStringO << endl;

cout << “invoke the base class’s toString() to return “

<< circle.GeometricObject::toString();

displays

Source: Liang Y. Daniel (2013), Introduction to programming with C++, Pearson; 3rd edition.

Leave a Reply

Your email address will not be published. Required fields are marked *