This blog is about providing theory as well as simple executable codes of different programming languages such as java, C, C++, and web programming, etc. This blog will be helpful to the IT students to learn about programming.

Friday, September 3, 2021

Operator overloading In C++

Operator overloading In C++

Overloading means assigning different meanings to an operation, depending on the context. C++ allows overloading of operators, thus allowing us to assign multiple meanings to operators.

The input/output operators << and >> are good examples of operator overloading. Although the built-in definition of the << operator is for shifting of bits, it is also used for displaying the values of various data types. This has been made possible by the header file iostream where a number of overloading definitions for << are included.

To define a task to an operator, we must specify what it means in relation to the class to which the operator is applied. This is done with the help of a special function, called operator function, which describes the task. The general form of an operator function is:

return type className :: operator op(arglist){

    function body //task definded

}

where return type is the type of value returned by the specified operation and op is the operator being overloaded. operator op is the function name, Where operator is a keyword.

The process of overloading is done through following steps:

  1. Create class that defines the data type that is to be used in the overloading operation.
  2. Declare the operator function operator op() in the public part of the class. It may be either a member function or a friend function.
  3. Define the operator function to implement the required operation


No comments:

Post a Comment

If you have any doubts, please let me know

Slider Widget