CPP Function Overloading

What is Functions Overloading?

  • In C++ you can create several functions with the same name. We says that these functions overload each other.
  • C++ require that those functions must differ in their parameter list with a different type of parameter, a different number of parameters or both.
    Overload Function example:
    Source code Result
    // Demonstrates function polymorphism
    #include <iostream>
    // two function, getVolume, that overload each other
    int getVolume(int length, int width , int height );
    double getVolume(double length, double width );
    
    int main() {
      int length = 100;
      int width = 50;
      int height = 2;
      int volume;
    // The result of this should be 100*50*2=10000  
      volume = getVolume(length, width, height);
      std::cout << "1.volume equals:" << volume << "\n";
      double len = 120.2;
      double wid = 54.2;
      double vol;
    // The result of this should be 120.2*54.2*1= 6514.84   
      vol = getVolume(len, wid);
      std::cout << "2.volume equals:" << vol << "\n";
      return 0;
    }
    // Implementation of the function  
    int getVolume(int length, int width, int height) {
      return (length * width * height);
    }
    double getVolume(double length, double width) {
      return (length * width * 1.0);
    }
    1.volume equals: 10000
    2.volume equals: 6514.84

    You can download this example here (needed tools can be found in the right menu on this page).

  • Function overloading is also called function polymorphism. Poly means many, and morph means form: A polymorphic function is many-formed
© 2010 by Finnesand Data. All rights reserved.
This site aims to provide FREE programming training and technics.
Finnesand Data as site owner gives no warranty for the correctness in the pages or source codes.
The risk of using this web-site pages or any program codes from this website is entirely at the individual user.