Operator and function overloading in c++


Operator overloading

  • An operator is always overloaded in conjunction with a class. The definition scope of an operator is simply extended—the characteristics of the operator remain unchanged.
  • An operator is said to be overloaded if it is defined for multiple types. In other words, overloading an operator means making the operator significant for a new type.
  • Most operators are already overloaded for fundamental types.
  • In addition to defining methods, C++ offers the interesting possibility of defining the functionality of a class by means of operators.
  • Thus, you can overload the + operator instead of, or in addition to, using the add() method.
  • Operator overloading is used to define a set of functions to add, subtract, multiply and divide complex numbers using the normal operators +, -, *, and /.

Function overloading

  • In C++, a program can have multiple functions with the same name. When two or more functions within a program have the same name, the function is said to be overloaded.
  • The functions must be different somehow, or else the compiler would not know how to associate a call with a particular function definition
  • The compiler identifies a function by more than its name; a function is uniquely identified by its signature
  • A function signature consists of the function’s name and its parameter list. In the parameter list, only the types of the formal parameters are important, not their names.
  • s. If the parameter types do not match exactly, both in number and position, then the function signatures are different.
  • Let's define a simple function to return the square of an integer:

  • int square(int value)
    {
     return (value * value);
    } 
  • We also want to square floating point numbers:

  • float square(float value) {
     return (value * value);
     }
    
  • Now we have two functions with the same name. Isn't that illegal? In older languages such as C and PASCAL that would be true.
  • In C++ it's not. C++ allows function overloading, which means you can define multiple functions with the same names.
  • Thus you can define a square function for all types of things: int, float, short int, double, and even char if we could figure out what it means to square a character.