Now suppose that you want to deal with tank cars as well as box cars. You need to add only another class and another definition of volume.
#includeconst double pi = 3.14159; class box_car {public: double height, width, length;}; class tank_car {public: double radius, length;}; double volume (box_car b) { return b.height * b.width * b.length; } double volume (tank_car t) { return pi * t.radius * t.radius * t.length; } main ( ) { box_car x; x.height = 10.5; x.width = 9.5; x.length = 40.0; tank_car y; y.radius = 3.5; y.length = 40.0; cout << "The volume of the box car is " << volume (x) << endl << "The volume of the tank car is " << volume (y) << endl; } --- Result --- The volume of the box car is 3990 The volume of the tank car is 1539.38
Because there is more than one definition of the
volume
function, volume
is said to be overloaded.
Wherever an overloaded function appears, the C++ compiler determines
which version is to be used by looking for the function definition in which
the parameter data type matches the data type of the argument that appears
in the function call.