lect10_2

lect10_2 - The Assignment Operator 1 Operator Overloading...

Info iconThis preview shows pages 1–3. Sign up to view the full content.

View Full Document Right Arrow Icon

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: The Assignment Operator 1 Operator Overloading The Assignment Operator In the previous part of our study of C++ classes, we discussed friend functions and how we can define operator functions as non-member functions. In this part we continue our study of classes and see how to overload operators as member functions. Indeed, some operators such as = and ++ can be overloaded only as member functions of a class. We begin with the assignment between objects. The assignment operator = Consider the RationalNum class discussed earlier. class RationalNum { private: int numer; int denom; public: // rest of class as before }; end class RationalNum We know that the class has two data members numer and denom . Consider the following code segment. RationalNum a(5,9), b; b = a; // assignment cout << b; // outputs 5/9 The assignment statement b = a; assigns the data member values of object a to their counterparts in b . Indeed, the compiler replaces the expression b = a; with the following. b.operator=(a); // <-- compiler replaces b = a; Thus, each time a class object is assigned to another object of the same class, the compiler looks for a member function in the class named operator= . If the class does not provide such a function, the compiler adds a default assignment operator function . The Assignment Operator 2 In our RationalNum class, we did not define any operator= member function. So the default version, provided by the compiler comes into action and assigns the data values of object a to the corresponding data members of...
View Full Document

Page1 / 5

lect10_2 - The Assignment Operator 1 Operator Overloading...

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online