Download presentation
Presentation is loading. Please wait.
1
Operator overloading Dr. Bhargavi Goswami
Department of Computer Science CHRIST Bangalore.
2
Operator overloading Has enhanced the power of extensibility of C++.
Allows user defined datatype behave same as built-in datatypes. Eg. A = B + C Operator overloading provides operators an additional specific meaning for data types. What does operator overloading do? It provides flexible option for creation of new definition for C++ operators. Why word overload? Because it provides additional meaning.
3
Operators that cannot be overloaded
Class member access operators . .* Scope Resolution operator :: Size of operator (sizeof) Conditional operator ?:
4
Operators that can be overloaded
+ - * / % & | ~ ! , < > <= >= ++ << >> == != && += -= /= %= ^= |= *= <<= >>= [] ->* new new[] delete delete[]
5
Operator overloading syntax
Semantics of the operator gets extended, but we cannot change its syntax, precedence, grammatical rules, its basic behavior. So, when operator is overloaded, its originality is not lost. Eg. + operator which used to add two integers, can be extended to add two vectors. How to achieve operator overloading? Using special function called operator function. Below syntax, op is the operator overloaded, operator is a keyword. Syntax:
6
Operator overloading functions and types
Operator function must be eitheir member functions (nonstatic) or friend function. What is the difference? Friend function takes one argument for unary operators, two for binary. But, member function has zero argument for unary operators and one for binary. Why so? Object that invokes member function is passed implicitly to member function. But, for friend function, both the arguments has to be passed explicitly. Note: Arguments may be passed either by value or by reference.
7
Some prototypes:
8
Process of overloading
Create a class Define data type and return type of operator function Declare operator function <op()> in public section as member function or friend function. Define the body of operator function. How to invoke? Eg. X++ --X X+Y We will see the things in detail in programs.
9
Unary operator overloading
Takes one operand. Eg. –x. changes sign of x. Lets do the same thing to object to convert all data items to negative. Eg. 7-1-UnaryMinus.cpp Remember, nothing it returns so statements like following will not work. S2 = -S1; Y we passed argument by reference in friend function? As operator overloading function returns nothing, it will not reflect the change back to object for printing values. So, pass by reference is necessary.
10
Binary operator overloading
Can we replace ‘c = sum(a,b);’ with ‘c=a+b;’ ? Yes. Using binary operator overloading. See next fig. Eg. 7-2-binaryMultiply.cpp Eg. 7-2-BinaryPlusOverloading.cpp It does following: 1. receives one argument of type complex 2. returns type complex 3. itself is member function of complex What invokes function in c3=c1+c2? C1+ Then what is c2? Argument passed to function. Then what is c3? It catches returned value of operator overloading function. Alternative? Usual call statement such as: C3 = c1.operator+(c2) Thus, left hand operand invokes operator function and right hand operand is passed as an argument to operator function.
12
Can we avoid declaration of temp object?
Yes. How? By using constructor. if we want to avoid using temp object, use constructor: return complex ((x+c.x),(y+c.y)); It initializes an object with no name. Returns the content by copying back to obj Such obj are temporary objects which gets destroyed no sooner values are provided to other object. Exercise: try out replacing temp object creation using constructor.
13
Overloading operators using friends
Only requirement is that friend function needs all operands passed as arguments. What is the need? When one operand is object and one operand is basic data type, it may not work. Eg. A = 2 + B; or A = a * B; // a is int variable Y? Because left hand operator is not object but a normal int or normal built in int variable. Limitation of member function?. Yes. Then solution? Friend function can handle all the three situation. i.e. A = 2 + B; A = a + B; A = A + B; How? By passing first argument as built in data type and second data type as user defined data type. Eg. 7-3-InputOutputOperatorOverloadingFriend.cpp
14
Manipulation of strings using operators
How C implement strings? Ans: By character array. Drawback? Programmer has to determine length of string before using it and allocate memory likewise. C++ removes this limitation? (Yes/No) Ans: Not completely. But, to great extend. How? Ans: By string class. Discussed in detail in Ch.15. Self Study: Example Program 7.4.
15
Other operator overloading
Subscript operator [] Pointer to Member opeartor -> Lets check both the examples. Eg. 7-5-overloadingSubscriptOperator.cpp and 7-6-overloadingPointer2MemberOperator.cpp
16
Rules for overloading operators
Only existing operators can be overloaded. New operators cannot be overloaded. The overloaded operator must have at least one operand that is of user defined type. Overloaded operator follow the syntax rules of original operator. Operators can be overloaded but cannot be overridden. All operators are not overloaded, few exemptions exist. (See next fig) We cannot use friend function for few operators. (See next fig)
17
Operators cannot be overloaded with friend
18
Rules for overloading operators
Unary operator: Takes no explicit argument until it is a friend function. Binary operator: Takes one explicit argument and if it is a friend, takes two. For binary operator, left hand operator must be always object and never a value. For binary operator as a friend, left hand operator can be a value. Binary arithmetic operators such as +,-,*,/ must explicitly return a value. Binary arithmetic operators must not make attempt to change own arguments.
19
Type Conversions C applies automatic type conversion.
Assignment operator “ = ” automatic type conversion. Eg. int m; float x = 3.145; m = x; This converts x to int automatically. Everything is fine till datatype is built in. What happens when datatype is user defined? Eg. V3 = V1 + V2 //all are class objects.
20
Type Conversions Situations which may need type conversion:
Basic to Class Class to Basic Class to Class First is achieved by constructors and functions. Second is achieved with cascading operator. Conditions: It must be a class member. It must not specify a return type. It must not have any arguments. Third one is achieved by either constructor or conversion function.
21
Basic to class We are already doing it using constructors and functions. Eg. Constructor body: A(int x){ a = b = x;}
22
Class to basic Using casting operators. What?
const_cast<type> (expr) performs explicitly override const of same type. dynamic_cast<type> (expr) performs runtime cast that verifies the validity of the cast. reinterpret_cast<type> (expr) performs casting of pointer to any other type of pointer. static_cast<type> (expr) performs cast a base class pointer into a derived class pointer. Eg. Vector operator double() { double sum=0; for (int i=0;i<size;i++) sum = sum + v[i] * v[i]; return sum; } double length = double (V1) OR double length = V1; HERE, V1 is object of Vector class.
23
Class to class Happens with constructors or functions.
X objx; //X is a class Y objy; //Y is a class Eg: objx = objy; So class Y is source data type and class X is destination data type. See next figure.
24
Object conversion
25
remember:
26
Type Conversions Compiler does not support automatic type conversations for user defined data types. We can use casting operator functions to achieve this. The casting operator function should satisfy following conditions: It must be a class member. It must not specify return type. It must not have any argument. Lets check the example. Eg. 7-7-dataConversionOperatorOverloading.cpp
27
Thank you. See u soon. Explore more about the topic.
Chapter 7 is over. Thank you. See u soon.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.