5.1.  Overloading Functions

[ fromfile: functions.xml id: overloading ]

Function Call Resolution

Example 5.1. src/functions/function-call.cpp

[ . . . . ]

class SignatureDemo {
public:
    SignatureDemo(int val) : m_Val(val) {}
    void demo(int n)
        {cout << ++m_Val << "\tdemo(int)" << endl;}
    void demo(int n) const                             1  
        {cout << m_Val << "\tdemo(int) const" << endl;}
/*  void demo(const int& n)   
      {cout << ++m_Val << "\tdemo(int&)" << endl;}  */ 2
    void demo(short s)  
        {cout << ++m_Val << "\tdemo(short)" << endl;}
    void demo(float f)  
        {cout << ++m_Val << "\tdemo(float)" << endl;}
    void demo(float f) const 
        {cout << m_Val << "\tdemo(float) const" << endl;}
    void demo(double d)
        {cout << ++m_Val << "\tdemo(double)" << endl;}
private:
    int m_Val;
};

1

Overloaded on const-ness.

2

Clashes with previous function.


Example 5.2. src/functions/function-call.cpp

[ . . . . ]

int main() {
    SignatureDemo sd(5);
    const SignatureDemo csd(17);
    sd.demo(2);    
    csd.demo(2);   1
    int i = 3;
    sd.demo(i);
    short s = 5;
    sd.demo(s);
    csd.demo(s);   2
    sd.demo(2.3);  3
    float f(4.5);   
    sd.demo(f);
    csd.demo(f);    
    // csd.demo(4.5);  
    return 0;
}

1

const version is called.

2

Non-const short cannot be called, so a promotion to int is required to call the const int version.

3

This is double, not float.


   6       demo(int)
   17      demo(int) const
   7       demo(int)
   8       demo(short)
   17      demo(int) const
   9       demo(double)
   10      demo(float)
   17      demo(float) const