Presentation is loading. Please wait.

Presentation is loading. Please wait.

Object Oriented Programming with C++/ Session 4/ 1 of 49 Operator Overloading Session 4.

Similar presentations


Presentation on theme: "Object Oriented Programming with C++/ Session 4/ 1 of 49 Operator Overloading Session 4."— Presentation transcript:

1 Object Oriented Programming with C++/ Session 4/ 1 of 49 Operator Overloading Session 4

2 Object Oriented Programming with C++/ Session 4/ 2 of 49 Session Objectives n Describe Operator Overloading Unary operators Binary operators Binary arithmetic operators Compound assignment operators Comparison operators n Describe overloading of the Assignment Operator n Describe Copy Constructors

3 Object Oriented Programming with C++/ Session 4/ 3 of 49 Session Objectives (Contd.) n Describe conversion functions which help in conversion from Basic types to User-Defined types from User-Defined types to Basic types between Objects of different Classes n Identify operators that cannot be overloaded

4 Object Oriented Programming with C++/ Session 4/ 4 of 49 Operator Overloading n It is the ability to associate an existing operator with a member function and use it with objects of its class as its operands Expressions with operators like +, -, >, +=, ==, etc. can be used only on basic data types like int and float n Operator overloading allows statements like, if (obj1>obj2){...} where obj1 and obj2 are objects of a class.

5 Object Oriented Programming with C++/ Session 4/ 5 of 49 Operator Overloading(Contd.) n Operation of comparing the objects can be defined in a member function and associated with the comparison operator. n Compiler can distinguish between overloaded operators by examining the data type of its operators. n Operator overloading is one form of polymorphism - operational polymorphism.

6 Object Oriented Programming with C++/ Session 4/ 6 of 49 Points to note n Overloading cannot alter the basic function of an operator, nor change its place in the order of precedence that is already defined in the language. ++ (increment) and -- (decrement) can be used only as unary operators. an overloaded + operator can be used to multiply two objects but this would make your code unreadable.

7 Object Oriented Programming with C++/ Session 4/ 7 of 49 Advantage n Makes programs easier to read and debug. n Easy to understand that two objects are being added and the result assigned to a third object, if you use the syntax obj3 = obj1 + obj2; instead of, obj3.addobjects(obj1,obj2);

8 Object Oriented Programming with C++/ Session 4/ 8 of 49 The Operator function n Operator function: Contains actual instructions to overload an operator. The operator that has to be overloaded follows the keyword "operator". return_type operator op(argument list); where op is the symbol for the operator that is being overloaded.

9 Object Oriented Programming with C++/ Session 4/ 9 of 49 Unary Operators n Unary operators have only one operand. increment operator ++, decrement operator --, and unary minus operator. n The increment and decrement operators can be used as either prefix or postfix operations. class Sample{ private: int counter; public: Sample() {counter =0;} void operator++() {++counter;} };

10 Object Oriented Programming with C++/ Session 4/ 10 of 49 Unary Operators (Contd.) void main() { Sample obj1; obj1++;//increments counter to 1 ++obj1;//increments counter to 2 } If an operator function is found in the class specifier, the statement to increment the object obj1++; gets converted, by the compiler to the following: obj1.operator++();

11 Object Oriented Programming with C++/ Session 4/ 11 of 49 Unary Operators (Contd.) n A similar function to decrement the object can also be included in the class as: void operator --() {--counter;} Can be invoked with the statement --obj1; or obj--; n With the overloaded increment and decrement operators, the operator function is executed first, regardless of whether the operator is postfix or prefix.

12 Object Oriented Programming with C++/ Session 4/ 12 of 49 Unary Operators (Contd.) Does not matter in obj1++ or ++obj1 but there is a problem when obj1 = obj2++; is used. n Revise the function so that it is able to return an incremented object. Sample Sample::void operator++() { Sample temp;//create a temporary object temp.counter = ++counter; //assign incremented value return temp;//return incremented object }

13 Object Oriented Programming with C++/ Session 4/ 13 of 49 Using nameless temporary object n Another way is to create a nameless temporary object and return it. class Sample{ private: int counter; public: Sample()//constructor with no argument {counter = 0;} Sample(int c) //constructor with one argument {counter = c;} Sample operator++(); };

14 Object Oriented Programming with C++/ Session 4/ 14 of 49 Using nameless temporary object (Contd.) Sample Sample::void operator++() { ++counter; return Sample(counter); //or only return Sample(++counter); } In the return statement, an unnamed temporary object of class Sample is created by the constructor that takes one argument. The object is initialised with the value in counter and the function returns the object.

15 Object Oriented Programming with C++/ Session 4/ 15 of 49 Using the this pointer Yet another way of returning an object from the member function is by using the this pointer. Sample Sample::void operator++() { ++counter; return(*this); } The one argument constructor is not needed in this approach.

16 Object Oriented Programming with C++/ Session 4/ 16 of 49 Problems with post and prefix When ++ and -- are overloaded, there is no distinction between the prefix and postfix operation. The expressions, obj2 = obj1++; and obj2 = ++obj1; produce the same effect. Define the function with a single argument to overload the ++ operator for a postfix operation Sample Sample::void operator++(int) { dummy argument return Sample(counter++); }

17 Object Oriented Programming with C++/ Session 4/ 17 of 49 Binary Operators n Binary operators can be overloaded in two ways: as member functions, they take one formal argument, which is the value to the right of the operator. –For example, when the addition obj1+obj2 has to be done the overloaded operator function for + is declared as, operator+(Sample obj2) as friend functions they take two arguments. –For example, operator+(Sample obj1,Sample obj2)

18 Object Oriented Programming with C++/ Session 4/ 18 of 49 Binary Arithmetic Operators n Need two operands to perform the operation. Sample Sample::operator+(Sample a) { Sample temp;//temporary object temp.counter = counter + a.counter; return temp;//return temp object } n Now we are able to perform addition of objects with a statement, obj3 = obj1 + obj2;//objects of class Sample

19 Object Oriented Programming with C++/ Session 4/ 19 of 49 Binary Arithmetic Operators (Contd.) The operator + can access two objects object on the left side of the operator, obj1, is the one that will invoke the function object on the right hand side, obj2, is taken as the argument to the function call. Left operand (object obj1 ) is accessed directly since this is the object invoking the function. Right hand operand is accessed as the function's argument as a.counter. n Also possible to do obj4 = obj3 + obj2 + obj1; Possible because return type of the + operator function is an object of type Sample.

20 Object Oriented Programming with C++/ Session 4/ 20 of 49 Overloaded + Operator for strings String String::operator+(String ss) { String temp;//make a temporary string strcpy(temp.str,str); //copy this string to temp strcat(temp.str,ss.str); //add the argument string return temp;//return temp string } Use as shown below: String s1 = "Welcome"; String s2 = "to C++"; String s3; s3 = s1 + s2;

21 Object Oriented Programming with C++/ Session 4/ 21 of 49 Compound Assignment Operators void Sample::operator+=(Sample a) { counter += a.counter;//addition } No need for a temporary object. The object, whose data member counter is changed, is the object that invokes the function. The function also needs no return value because the result of the assignment operator is not assigned to anything.

22 Object Oriented Programming with C++/ Session 4/ 22 of 49 Compound Assignment Operators (Contd.) n The operator is used in expressions like obj1 += obj2; n Function would need to have a return value to be used in more complex expressions such as obj3 = obj1 += obj2; n Member function declaration would be: Sample Sample::operator+=(Sample a); n The return statement can be written as: return Sample(counter); where a nameless object is initialised to the same values as this object.

23 Object Oriented Programming with C++/ Session 4/ 23 of 49 Comparison Operators Comparison and logical operators are binary operators that need two objects to be compared. The comparison operators that can be overloaded include, >=, ==, and != int String::operator>(String ss) { return(strcmp(str,ss.str) > 0)); }

24 Object Oriented Programming with C++/ Session 4/ 24 of 49 Assignment Operator Overloading n Default assignment operator simply copies the source object to the destination object byte by byte. If data members contain pointers and have been allocated memory using the new operator. class String{ private: char *str; public: String(char *s = ""){ int length = strlen(s); str = new char[length+1]; strcpy(str,s); }

25 Object Oriented Programming with C++/ Session 4/ 25 of 49 Assignment Operator (Contd.) ~String(){delete[] str;}//destructor void display(){cout<<str;} }; void main() { String s1("Welcome to my world \n"); String s2; s2 = s1; s1.display(); s2.display(); } Two objects s1 and s2 are created. The constructor function allocates memory for a string and copies the contents of its formal argument in it.

26 Object Oriented Programming with C++/ Session 4/ 26 of 49 Assignment Operator (Contd.) n Output: Welcome to my world Null pointer assignment After the assignment the data member str of both the objects points to the same location of memory. There are two pointers to the same memory location.

27 Object Oriented Programming with C++/ Session 4/ 27 of 49 Strings in memory str s1 s2 "Welcome to my world" Assignment copies only the pointer and not the string String in memory str s1 After s2 is deleted memory is released but str of s1 object still points to it

28 Object Oriented Programming with C++/ Session 4/ 28 of 49 Assignment Operator (Contd.) Solution: String& String::operator=(String& s) { delete str; int length = strlen(s.str); str = new char[length+1]; strcpy(str,s.str); return(*this); } By including this function in the program the error message will not appear.

29 Object Oriented Programming with C++/ Session 4/ 29 of 49 Assignment Operator (Contd.) n When you overload the assignment operator you must make sure that all the data members are copied from one object to the other in the operator function. n Where more data members are involved each has to be copied to the target object. n It is possible to use a chain of = operators, such as: obj3 = obj2 = obj1;

30 Object Oriented Programming with C++/ Session 4/ 30 of 49 Why we need Copy Constructors String s1("This is a string."); String s2(s1); The first statement declares an object s1 and passes a string as an argument to its constructor. The second statement declared another object s2 and contains an object as its argument. If constructor with an object as its formal argument is not defined, the compiler itself initialises the data members of s2 with s1. Since the data member of class String is a pointer, the null pointer assignment problem arises just as in the assignment operator.

31 Object Oriented Programming with C++/ Session 4/ 31 of 49 Copy Constructor n Define a constructor function that takes an object as its argument. This constructor is called the copy constructor. X::X(X &ptr), where X is the user defined class name and ptr is an object of class X that is passed by reference. n Another format X::X(const X &ptr) By using the const keyword we make sure that the copy process does not inadvertently make any changes to the object that is being copied.

32 Object Oriented Programming with C++/ Session 4/ 32 of 49 Copy Constructor (Contd.) n Copy constructor is called in three contexts: when an object of a class is initialised to another of the same class when an object is passed as an argument to a function when a function returns an object

33 Object Oriented Programming with C++/ Session 4/ 33 of 49 Copy Constructor (Contd.) n The copy constructor is generated automatically for you by the compiler if you do not define one yourself. It is used to copy the contents of an object to a new object during construction of that new object. n Alright for simple classes with no pointers but with a pointer as a data member, a byte by byte copy would copy the pointer from one to the other and they would both be pointing to the same allocated member. n Assignment and initialisation are different operations.

34 Object Oriented Programming with C++/ Session 4/ 34 of 49 Copy Constructor for String class String::String(String& ss) { int size = strlen(ss.str); str = new char[size+1]; strcpy(str, ss.str); }

35 Object Oriented Programming with C++/ Session 4/ 35 of 49 A typical class n When a class X has a data member of pointer type, the class should have a constructor, assignment operator function, copy constructor and destructor. class X{ X(some_value);//constructor X(const X&);//copy constructor X& operator=(const X&); //assignment ~X();//destructor };

36 Object Oriented Programming with C++/ Session 4/ 36 of 49 Conversion Functions n Member functions used to convert objects to or from basic data types and for conversions between objects of different classes. n Compiler knows nothing about converting user-defined types such as objects.

37 Object Oriented Programming with C++/ Session 4/ 37 of 49 Example class Converter{ private: int feet; float inches; public: Converter()//default constructor {feet = 0; inches =0.0;} Converter(float metres) {//constructor with one arg float f; f= 3.28 * metres; feet = int(f); inches = 12 *(f-feet); } };

38 Object Oriented Programming with C++/ Session 4/ 38 of 49 Example (Contd.) void main() { Converter d1 = 1.55;//uses second constructor Converter d2;//uses first constructor d2 = 2.0;//uses second constructor }

39 Object Oriented Programming with C++/ Session 4/ 39 of 49 Basic types to User-Defined types Declaration of the object d1 uses the second constructor and assigns the value 1.55. It shows the conversion of a float constant to an object of class Converter. d2 = 2.0; also uses the constructor function for assignment of a float to object d2. n The compiler first checks for an operator function for the assignment operator. n If the assignment operator is not overloaded, then it uses the constructor to do the conversion. If the constructor also had not been defined the compiler would have given an error.

40 Object Oriented Programming with C++/ Session 4/ 40 of 49 User-Defined types to Basic types n Compiler has to be explicitly instructed if an object has to be converted to a basic data type. n These instructions are coded in a conversion function and defined as a member of that class. operator float() { float f; f = inches/12; f += float(feet); return (f/3.28); }

41 Object Oriented Programming with C++/ Session 4/ 41 of 49 User-Defined types to Basic types (Contd.) Can be used as, m = d2; or explicitly using statement, m = float(d1); n Conversion function is nothing but overloading of the type cast operator. n The conversion function contains the operator keyword and instead of an operator symbol it contains the data type. n The conversion function must not define a return type nor should it have any arguments.

42 Object Oriented Programming with C++/ Session 4/ 42 of 49 Conversion between Objects n Conversion functions have to be specified since compiler knows nothing about user- defined types. n Can be a member function of the source class (i.e. the right hand side of the assignment operator) n Or it can be a member function of the destination class (i.e., the left-hand side of the assignment operator).

43 Object Oriented Programming with C++/ Session 4/ 43 of 49 Conversion between Objects (Contd.) objectA = objectB; objectA: object of destination class objectB: object of source class. n Conversion of objects of two different classes can be achieved with: One-argument constructor defined in the destination class. Or a conversion function defined in the source class.

44 Object Oriented Programming with C++/ Session 4/ 44 of 49 Example class LFeet{ private: int feet; float inches; public: LFeet(){feet = 0; inches =0.0;}//Constructor 1 LFeet(int ft,float in) //Constructor 2 { feet = ft; inches = in; } };

45 Object Oriented Programming with C++/ Session 4/ 45 of 49 Example (Contd.) class LMetres{ private: float metres; public: LMetres(){metres = 0.0;}//Constructor 1 LMetres(float m)//Constructor 2 {metres = m;} }; void main() { LMetres dm1 = 1.0; LFeet df1; df1 = dm1; }

46 Object Oriented Programming with C++/ Session 4/ 46 of 49 Conversion Function in Source Class The conversion function in the source class to convert the length from the source class LMetres to the destination class LFeet would be as follows: operator LFeet()//conversion function { float ffeet, inc; int ifeet; ffeet = 3.28*metres; ifeet = int(ffeet); inc = 12*(ffeet - ifeet); return LFeet(ifeet,inc); } df1 = dm1; calls the conversion function implicitly.

47 Object Oriented Programming with C++/ Session 4/ 47 of 49 Constructor Function in Destination Class LFeet::LFeet(LMetres dm)//constructor function { float ffeet; ffeet = 3.28*dm.GetMetres(); feet = int(ffeet); inches = 12*(ffeet - feet); } Also need to define a member function called GetMetres() in the source class Lmetres: float LMetres::GetMetres() { return metres; }

48 Object Oriented Programming with C++/ Session 4/ 48 of 49 Table for Type Conversions

49 Object Oriented Programming with C++/ Session 4/ 49 of 49 Operators that cannot be overloaded n The sizeof() operator n The dot operator (.) n The scope resolution operator (::) n The conditional operator (?:) n The pointer-to-member operator (.*)


Download ppt "Object Oriented Programming with C++/ Session 4/ 1 of 49 Operator Overloading Session 4."

Similar presentations


Ads by Google