Coupon Accepted Successfully!


The Keyword Operator

The keyword operator defines a new action or operation to the operator.

The keyword “operator”, followed by an operator symbol, defines a new (overloaded) action of the given operator.

Overloaded operators are redefined within a C++ class using the keyword operator followed by an operator symbol. When an operator is overloaded, the produced symbol is called the operator function name. The above declarations provide an extra meaning to the operator. Operator functions should be either member functions or friend functions. A friend function requires one argument for unary operators and two for binary operators, while a member function requires one argument for binary operators and no argument for unary operator. When the member function is called, the calling object is passed implicitly to the function and hence available for member function. While using friend functions, it is essential to pass the objects by value or reference. The prototype of operator functions in classes can be written as follows.


(a) void operator ++();

(b) void operator −−();

(c) void operator −();

(d) num operator+(num);

(e) friend num operator * (int ,num);

(f) void operator = (num);

Operator overloading can be carried out in the following steps.

  1. Define a class which is to be used with overloading operations.
  2. The public declaration section of the class should contain the prototype of the function operator().
  3. Define the definition of the operator() function with proper operations for which it is declared.

10.2 Write a program to perform addition of two objects using operator keyword.


Explanation: In the above program A, B, and C are objects of class number. Here, we performed the addition using statement C=A+B. Remember, in the last program we were not able to execute this statement. Instead of this, two separate statements were used to perform addition.

In this program, the statements that perform addition operation of each individual member of objects are written in function operator. The operator has return type and single argument. It also uses a local object (T) to hold addition as long as the operator function is active. Whenever the statement C=A+B is executed, the compiler searches for definition of operator +. The object A invokes the operator function and object B is passed as argument. The copy of object B is stored in the formal argument D. The member variables of A are directly available in operator function as the function is invoked by the same object. The addition of individual members are carried out and stored in member variable of object T. The return type of operator function is same as that of its class. The function returns object T and it is assigned to variable C.

Test Your Skills Now!
Take a Quiz now
Reviewer Name