Full size Banner

About overloading and overriding


Overloading
With the C++ language, we can overload functions and operators. Overloading is the practice of supplying more than one definition for a given function name in the same scope. The compiler is left to pick the appropriate version of the function or operator based on the arguments with which it is called. For example, the function max is considered an overloaded function. It can be used in code such as the following:

// overview_overload.cpp
double max( double d1, double d2 )
{p
return ( d1 > d2 ) ? d1 : d2;p
}p
p
int max( int i1, int i2 )p
{p
return ( i1 > i2 ) ? i1 : i2;p
}p
int main()p
{p
int i = max( 12, 8 );p
double d = max( 32.9, 17.4 );p
}p
p
In the first function call, where the maximum value of two variables of type int is being requested, the function max( int, int ) is called. However, in the second function call, the arguments are of type double, so the function max( double, double ) is called.p
Operator Overloading
The operator keyword declares a function specifying what operator-symbol means when applied to instances of a class. This gives the operator more than one meaning, or "overloads" it. The compiler distinguishes between the different meanings of an operator by examining the types of its operands.
The name of an overloaded operator is operatorx, where x is the operator as it appears in the following table. For example, to overload the addition operator, you define a function called operator+. Similarly, to overload the addition/assignment operator, +=, define a function called operator+=.

Let's take an example with assignment operator:
The assignment operator (=) is, strictly speaking, a binary operator. Its declaration is identical to any other binary operator, with the following exceptions:

  • It must be a nonstatic member function. No operator= can be declared as a nonmember function.

  • It is not inherited by derived classes.

// assignment.cpp
class Point
{
public:
Point &operator=( Point & ); // Right side is the argument.
int _x, _y;
};

// Define assignment operator.
Point &Point::operator=( Point &ptRHS )
{
_x = ptRHS._x;
_y = ptRHS._y;

return *this; // Assignment operator returns left side.
}

int main()
{
}