Function Overloading in Classes in C++

Function Overloading in Classes in C++

Sometimes it is required to define more than one functions having same name in the same class. If it is the case then we need to bring some differences in both the functions sharing same name. There are two ways through which they can be made distinct.

  1. By number of arguments
  2. By type of arguments

Function Overloading By Changing Number of Arguments

Probably the most common way of function overloading is by changing the number of arguments. For instance if a function having name abc is accepting two arguments of integer type (void abc(int,int)), then we can define another function having same name abc but accepting either one argument or three arguments.

The following program segment shows an illustration of function overloading by changing number of arguments.

void abc(int a, int b)

{

      …

}

void abc(int a, int b, int c)

{

      …

}

We can see that both functions have same name but the number of arguments are different. One of them is accepting 2 arguments while the other is accepting three arguments. We can also define another function having same name but different number of arguments.

It is important to note that return type has nothing to do with function overloading. If we just change the return type of the functions but number of arguments remain same then it will lead to a syntax error as in the following case.

void abc(int a, int b)

{

      …

}

int abc(int a, int b)

{

      …

      return (value);

}

These functions are called identical functions and will not be allowed to be used in the same class.

Function Overloading By Changing Data Types of Arguments

Another way of function overloading is to change the data type of at least one of the arguments. For instance if we have a function having name abc and accepting two integer arguments, then we can redefine the same function in the same class but the data type of one of the argument must be other than integer.

Probably the most common way of function overloading is by changing the number of arguments. For instance if a function having name abc is accepting two arguments of integer type (void abc(int,int)), then we can define another function having same name abc but accepting either one argument or three arguments.

The following program segment shows an illustration of function overloading by changing type of arguments.

void abc(int a, int b)

{

      …

}

void abc(int a, double b)

{

      …

}

void abc(double a, int b)

{

      …

}

void abc(double a, double b)

{

      …

}

It is allowed if we define the above functions in the same class as all of them have same name but the data types of the arguments are different.

More Related Articles For You

    C++ Tutorial

    C++ Quizzes