CPP Programming
About Lesson

A function having different definitions and number or type of arguments is known as function overloading.  Through this feature a function is taking excess responsibility than performing a single task.

//Example program for Function Overloading

#include

int volume(int);

double volume(double, int);

main()

{

cout<<volume(10)<< “n”;

cout<<volume(2.5,8);

}

int volume(int s)//for volume of cube

{

return(s*s*s);

}

double volume(double r, int h)// for volume of cylinder

{

return(3.14519*r*r*h);

}

OVERLOADING OF CONSTRUCTORS

Since constructors too like members of a class, they can also be overloaded.  When the object of class is creating, the corresponding constructor definition will be called based on the type and number of arguments we are passing.

//Example code showing how constructor of a class can be overloaded

#include

using namespace std;

class sample

{

    int x;

    float y;

public:

    sample()

    {

        x=1;

        y=1.2;

    }

    sample(int a,float b)

    {

        x=a;

        y=b;

    }

    void show()

    {

    cout<<“Value of x is :”<<x<<endl;

    cout<<“Value of y is :”<<y<<endl;

    }

};

int main()

{

    sample obj1;

    sample obj2(2,3.4);

    obj1.show();

    cout<<“nn”;

    obj2.show();

}

Rules of Function Overloading

A function is said to be overloaded, when it has more than one definitions in the same program or same class

  1. With different number of arguments
  2. With different type of arguments

But different return type is not valid to take as a qualification of overloading.

You cannot copy content of this page