Chapt 9. Operator Overloading

9.1. Introduction to Operator Overloading (Learn C++)

A. Constraints

1. cannot overload

a. ‘? :’ – Conditional operator

b. ‘sizeof’ – sizeof operator

c. ‘::’ – scope resolution

d. ‘.’ – member selector

e. ‘.*’ – member pointer selector

2. cannot create new operator

3. cannot rename existing operator

4. at least one of operand should be user-defined type

5. cannot change number of operands

6. cannot change default ‘precedence’ and ‘associativity’

9.2. Overloading the arithmetic operators (+, -, *, /) (Learn C++)

By using keyword ‘friend’, you can overload arithmetic operator

Source Code

9.3. Overloading the I/O operators (>>, <<) (Learn C++)

Input Operator(‘<<‘)   : std::cin is type of ‘isream’

Output Operator(‘>>’): std::cout is type of ‘ostream’

Source Code

9.4. Overloading using member functions (Learn C++)

KEY: left operand is fixed – becomes implicit ‘*this’ object

Not every operator can be overloaded as member functions

i.e. ‘>>’, ‘<<‘

Not every operators can be overloaded as friend functions

i.e. ‘[]’, ‘=’, ‘->’

Source Code

9.5. Overloading unary operator (+, -, !) (Learn C++)

implement as member function, because it operator on itself

9.6. Overloading the comparison operator (<,>,==) (Learn C++)

Source Code

9.8. Overloading the subscript operator ‘[]’ (Learn C++)

A. operator[] returns a ‘l-value’ (reference)

int& operator[] (const int index) { return array[index]; }

9.10. Overloading Typecasts (Learn C++)

• No return type syntax included

Source Code

9.11. & 14. Copy constructor and Overloading assignment operator

both do same function, but called in difference cases

A. Copy Constructor (Learn C++)

parameter must passed by reference, not by value

When called

1. instantiating and initializing a new object from already existing object

2. passing an object by value

3. object is returned from a function by value

B. Assignment Operator (Learn C++)

default memberwise assignment operator provided by C++ compiler

should be member function to ease accessing private field

should check to avoid self-assignment

return ‘*this‘ so can chain the assignment operator

9.12 Shallow vs Deep copying (Learn C++)

A. Shallow Copy(=Memberwise Copying)

C++ provide default shallow copy constructor and assignment operator

B. Deep Copy

Must implement your won copy constructor and assignment overloading in case class has dynamically allocated variables

C. Prevent Copy

Place into private field, if you don’t want your class object to be copied