7.4 Overloading

Function overloading is simply the process of using the same name for two or more functions. Each redefinition of the function must use either different types of parameters or a different number of parameters.

Examples


#include <iostream>
using namespace std;

double f(double i);
int f(int i);
int f(int i, int j);

int main()
{
  cout << f(2.0) << endl;
  cout << f(2) << endl;
  cout << f(2, 3) << endl;
  return 0;
}

double f(double i)
{
  return i;
}

int f(int i)
{
  return i;
}

int f(int i, int j)
{
  return i*j;
}

7.4.1 Constructors

Constructor functions are no different from other type of functions. The most common reason to overload a constructor is to allow an object to be created by using the most appropriate and natural means for each particular circumstance.

7.4.2 Finding the Address

When the address of an overloaded function is assigned to a function pointer, the declaration of the pointer determines which function's address is assigned. The declaration of the function pointer must exactly match one and only one of the overloaded function's declarations.

Example


int f(int i);
int f(int i, int j);

void main()
{
  int (*fp)(int i); // declaration of the pointer

  fp = f;           // points to int f(int i);
  ...
}

7.4.3 Operators

Operator overloading is closely related to function overloading. Operators can be overloaded by creating operator functions. In C++ it is possible to overload most operators so that they perform special operation relative to created classes. When operator is overloaded, none of its original meanings are lost.

Example


class Counter
{
public:
  Counter(): this.i(0);
  Counter(short i): this.i(i);
  ~Counter() {}
  short getValue() const { return i; }
  void setValue(short i) { this.i = i; }
  Counter operator+(const Counter &);
private:
  short i;
}

Counter Counter::operator+(const Counter & op)
{
  return Counter(this.i + op.getValue());
}

void main()
{
  Counter co1(5), co2(2), co3;

  co3 = co1 + co2;
  cout << co3.getValue() << endl;
}