Functions that cannot be overloaded in C++

C++Server Side ProgrammingProgramming

Function overloading is also known as method overloading. Function overloading is the feature provided by the concept of polymorphism which is widely used in object-oriented programming.

To achieve function overloading, functions should satisfy these conditions −

  • Return type of functions should be same

  • Name of the functions should be same

  • Parameters can be different in type but should be same in number

Example

int display(int a); int display(float a); // both the functions can be overloaded
int display(int a); float display(float b); //both the functions can’t be overloaded as the return type of
one function is different from another

let’s discuss the functions that can’t overloaded in C++

  • functions with different name and different number of parameters

Example

#include<iostream>
using namespace std;
int max_two(int a, int b) //contains two parameters{
   if(a>b){
      return a;
   }
   else{
      return b;
   }
}
int max_three(int a, int b ,int c) //contains three parameters{
   if (a>b && a>c){
      return a;
   }
   else if(b>c){
      return b;
   }
   else{
      return c;
   }
}
int main(){
   max_two(a,b);
   return 0;
}
  • Functions with the same name but different return type

Example

#include<iostream>
using namespace std;
int max_two(int a, int b){
   if(a>b){
      return a;
   }
   else{
      return b;
   }
}
float max_two(int a, int b){
   if(a>b){
      return a;
   }
   else{
      return b;
   }
}
int main(){
   max_two(a, b);
   return 0;
}
  • A member function that satisfies all the condition of function overloading but if it is a static member function than it can’t be overloaded.

Example

#include<iostream>
class check{
   static void test(int i)
   { }
   void test(int i)
   { }
};
int main(){
   check ch;
   return 0;
}
  • If two functions are exactly same but differed only in default arguments i.e. one of the functions contains default arguments, then they are considered as same which means they can’t be overloaded and therefore compiler will throw an error of redeclaration of the same function.

Example

#include<iostream>
#include<stdio.h>
using namespace std;
int func_1 ( int a, int b){
   return a*b;
}
int func_1 ( int a, int b = 40){
   return a+b;
}
Int main(){
   func_1(10,20);
   return 0;
}
raja
Published on 13-Aug-2020 06:08:07
Advertisements