Function Overloading in C++

Function overloading is different function can have same name but argument list will be different.  For example, constructors. 

Function name is said to be overloaded because two or more functions will have the same name, and this applies to both member and non-member function. 

Overloaded function is resolved by matching actual arguments against formal arguments. Compiler is brilliant to enough match the function with the supplied arguments.

Example 1 :

#include <iostream>
using namespace std;

class Army  
{
private:
    int armyCode;
    string name;
public:    
    Army(int armyCode) {};
    Army(int armyCode, string name) {};
    int getArmyCode() {
       return armyCode;
    }
};

class ArmyHospital : public Army
{
private:
    int code_;
public:
    ArmyHospital(int cod) : Army(cod) {
       code_ = cod;
    }
};

int function(int num) {
   cout << __func__ << "(int)" << endl;
   return 1;
}

int function(double num) {
   cout << __func__ << "(double)" << endl;
   return 1;
}

int main ()
{
    ArmyHospital arm1(581);
    int res = function(arm1.getArmyCode());
    return 1;
}

Output:

1
function(int)

Example 2 :

#include <iostream>
using namespace std;

class Army  
{
private:
    int armyCode;
    string name;
public:    
    Army(int armyCode) {};
    Army(int armyCode, string name) {};
    int getArmyCode() {
       return armyCode;
    }
};

class ArmyHospital : public Army
{
private:
    int code_;
public:
    ArmyHospital(int cod) : Army(cod) {
       code_ = cod;
    }
};

int function(int num) {
   cout << __func__ << "(int)" << endl;
   return 1;
}

int function(char []) {
   cout << __func__ << "(char [])" << endl;
   return 1;
}

int main ()
{
    ArmyHospital arm1(581);
    int res = function(arm1.getArmyCode());
    return 1;
}

Output:

1
function(int)

As integer can't be converted into char [], it will choose the integer as an argument. 

Example 3 : 

Now, I tweaked a little bit to have the function with argument as double and char.

#include <iostream>
using namespace std;

class Army  
{
private:
    int armyCode;
    string name;
public:    
    Army(int armyCode) {};
    Army(int armyCode, string name) {};
    int getArmyCode() {
       return armyCode;
    }
};

class ArmyHospital : public Army
{
private:
    int code_;
public:
    ArmyHospital(int cod) : Army(cod) {
       code_ = cod;
    }
};

int function(double num) {
   cout << __func__ << "(double)" << endl;
   return 1;
}

int function(char) {
   cout << __func__ << "(char [])" << endl;
   return 1;
}

int main ()
{
    ArmyHospital arm1(5);
    int res = function(arm1.getArmyCode());
    return 1;
}

Output:

1
2
3
In function 'int main()':
Line 40: error: call of overloaded 'function(int)' is ambiguous
compilation terminated due to -Wfatal-errors.



Comments