Rules for Overloading Operators Dr Piyush Kumar Singh

  • Slides: 8
Download presentation
Rules for Overloading Operators Dr. Piyush Kumar Singh

Rules for Overloading Operators Dr. Piyush Kumar Singh

Rules for Overloading Operators: ØOnly Existing operators can be overloaded. ØThe overloaded operator must

Rules for Overloading Operators: ØOnly Existing operators can be overloaded. ØThe overloaded operator must have at least one operand is of user defined type. ØWe cannot change the basic meaning of an operator. That is to say, we cannot redefine the plus (+) operator to subtract one value from the other. ØOverloaded operators follow the syntax rules of the original operators. They cannot be overridden.

Rules for Overloading Operators: ØThere are some operatos that cannot be overloaded. These are

Rules for Overloading Operators: ØThere are some operatos that cannot be overloaded. These are given below: q Class member access operators q. Scope resolution operator q. Size Operator q. Conditional Operator . . * : : sizeof ? :

Rules for Overloading Operators: ØWe cannot use friend functions to overload certain operators. The

Rules for Overloading Operators: ØWe cannot use friend functions to overload certain operators. The list is given below: q. Assignment Operator = q. Function call Operator () q. Subscription Operator [] q. Class member access operator -> ØHowever member function can be used to overload the above operators.

Rules for Overloading Operators: ØUnary operators, overloaded by means of a member function, take

Rules for Overloading Operators: ØUnary operators, overloaded by means of a member function, take no explicit arguments and return no explicit values, but, those overloaded by means of a friend function, take one reference argument (the object of the relevant class). ØBinary operator overloaded through a member function take one explicit argument and those which are overloaded through a friend function take two explicit argument. ØWhen using binary operators overloaded through a member function, the left hand operand must be an object of relevant class.

Rules for Overloading Operators: ØBinary arithmetic operators such as +, -, * and /

Rules for Overloading Operators: ØBinary arithmetic operators such as +, -, * and / must explicitly return a value. They must not attempt to change their own arguments.

References: 1. Object Oriented Programming with C++, 3/e by E. Balagurusamy, Tata Mc. Graw

References: 1. Object Oriented Programming with C++, 3/e by E. Balagurusamy, Tata Mc. Graw Hill. 2. Mastering C++, 1/e by Venugopal, Tata Mc. Graw Hill.

Thank You

Thank You