Generic Programming in C++

An object of a derived class can be passed wherever an object of a base type parameter is required. Thus a function can be used generically for a wide range of object arguments. This is known as generic programming.

If a function’s parameter type is a base class (e.g., GeometricObject), you may pass an object to this function of any of the parameter’s derived classes (e.g., Circle or Rectangle). For example, suppose you define a function as follows:

void displayGeometricObject(const GeometricObject& shape) {

cout << shape.getColor() << endl;

}

The parameter type is GeometricObj ect. You can invoke this function in the following code:

disp1ayGeometncObject(GeometncObject(“black”, true));

disp1ayGeometricObject(Circ1e(5));

disp1ayGeometricObject(Rectang1e(2, 3));

Each statement creates an anonymous object and passes it to invoke displayGeomet- ricObject. Since Circle and Rectangle are derived from GeometricObject, you can pass a Circle object or a Rectangle object to the GeometricObject parameter type in the displayGeometricObject function.

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 *