[ fromfile: functions.xml id: overloading ]
The signature of a function consists of its name and its parameter list. In C++, the return type is not part of the signature.
C++ permits overloading of function names. A function name is overloaded if it has more than one meaning within a given scope. Overloading occurs when two or more functions within a given scope have the same name but different signatures. It is an error to have two functions in the same scope with the same signature but different return types.
When a function call is made to an overloaded function within a given scope, the C++ compiler determines from the arguments which version of the function to invoke. To do this, a match must be found between the number and type of the arguments and the signature of exactly one of the overloaded functions. This is the sequence of steps that the compiler takes to determine which overloaded function to call.
Example 5.1 shows a class with six member functions, each with a distinct signature.
Keep in mind that
each member function has an additional, implicit, parameter: this.
The keyword const, following the parameter list, protects the host object from the action of the function and is part of its signature.
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
{cout << m_Val << "\tdemo(int) const" << endl;}
/* void demo(const int& n)
{cout << ++m_Val << "\tdemo(int&)" << endl;} */
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;
};
Example 5.2 contains some client code which tests the overloaded functions from SignatureDemo.
Example 5.2. src/functions/function-call.cpp
The output should look something like this:
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
| Generated: $Date: 2009-09-08 12:15:32 -0400 (Tue, 08 Sep 2009) $ | © 2009 Alan Ezust and Paul Ezust. |