<<

Chapter 8

Operator Overloading, Friends, and References

Learning Objectives

ƒ Basic Operator Overloading ƒ Unary operators ƒ As member functions ƒ Friends and Automatic Type Conversion ƒ Friend functions, friend classes ƒ Constructors for automatic type conversion ƒ References and More Overloading ƒ << and >> ƒ Operators: = , ++, -- Operator Overloading Introduction ƒ Operators +, -, %, ==, etc. ƒ Really just functions! ƒ Simply ‘called’ with different syntax: x + 7 ƒ ‘+’ is binary operator with x & 7 as operands ƒ We ‘like’ this notation as humans ƒ Think of it as: +(x, 7) ƒ ‘+’ is the function name ƒ x, 7 are the arguments ƒ Function ‘+’ returns ‘sum’ of it’s arguments

Operator Overloading Perspective ƒ Built-in operators ƒ e.g.: +, -, = , %, ==, /, * ƒ Already work for ++ built-in types ƒ In standard ‘binary’ notation ƒ We can overload them! ƒ To work with OUR types! ƒ To add ‘Chair types’, or ‘Money types’ ƒ As appropriate for our needs ƒ In ‘notation’ we’re comfortable with ƒ Always overload with similar ‘actions’! Overloading Basics ƒ Overloading operators ƒ VERY similar to overloading functions ƒ Operator itself is ‘name’ of function ƒ Example Declaration: const Money operator +( const Money& amount1, const Money& amount2); ƒ Overloads + for operands of type Money ƒ Uses constant reference parameters for efficiency ƒ Returned value is type Money ƒ Allows addition of ‘Money’ objects

Overloaded ‘+’ ƒ Given previous example: ƒ Note: overloaded ‘+’ NOT member function ƒ Definition is ‘more involved’ than simple ‘add’ ƒ Requires issues of money type addition ƒ Must handle negative/positive values ƒ Operator overload definitions generally very simple ƒ Just perform ‘addition’ particular to ‘your’ type Money ‘+’ Definition ƒ Definition of ‘+’ operator for Money class: Display 8.1, page 305

Overloaded ‘==‘ ƒ Equality operator, == ƒ Enables comparison of Money objects ƒ Declaration: bool operator ==(const Money& amount1, const Money& amount2); ƒ Returns bool type for true/false equality ƒ Again, it’s a non-member function (like ‘+’ overload) Overloaded ‘==‘ for Money ƒ Definition of ‘==‘ operator for Money class:

Display 8.1, page 306

Constructors Returning Objects ƒ Constructor a ‘void’ function? ƒ We ‘think’ that way, but no ƒ A ‘special’ function ƒ With special properties ƒ CAN return a value! ƒ Recall in ‘+’ overload for Money type: ƒ return Money(finalDollars, finalCents); ƒ Returns an ‘invocation’ of Money class! ƒ So constructor actually ‘returns’ an object! ƒ Called an ‘anonymous object’ Returning by const Value ƒ Consider ‘+’ operator overload again: const Money operator +(const Money& amount1, const Money& amount2); ƒ Returns a ‘constant object’? ƒ Why? ƒ Consider impact of returning ‘non-const’ object to see…Æ

Returning by non-const Value ƒ Consider ‘no const’ in declaration: Money operator +( const Money& amount1, const Money& amount2); ƒ Consider expression that calls: m1 + m2 ƒ Where m1 & m2 are Money objects ƒ Object returned is Money object ƒ We can ‘do things’ with objects! ƒ Like call member functions… What to do with Non-const Object ƒ Can call member functions: ƒ We could invoke member functions on object returned by expression m1+m2: ƒ (m1+m2).output(); //Legal, right? ƒ Not a problem: doesn’t change anything ƒ (m1+m2).input(); //Legal! ƒ PROBLEM! //Legal, but MODIFIES! ƒ Allows modification of ‘anonymous’ object! ƒ Can’t allow that here! ƒ So we define the return object as const

Overloading Unary Operators ƒ C++ has unary operators: ƒ Defined as taking one operand ƒ e.g.: - (negation) ƒ x = -y; // Sets x equal to negative of y ƒ Other unary operators: ƒ ++, -- ƒ Unary operators can also be overloaded Overload ‘-’ for Money ƒ Overloaded ‘-’ function declaration ƒ Placed outside class definition: const Money operator –(const Money& amount); ƒ Notice: only one argument ƒ Since only 1 operand (unary) ƒ ‘-’ operator is overloaded twice! ƒ For two operands/arguments (binary) ƒ For one operand/argument (unary) ƒ Definitions must exist for both

Overloaded ‘-’ Definition ƒ Overloaded ‘-’ function definition: const Money operator –(const Money& amount) { return Money(-amount.getDollars(), -amount.getCents()); } ƒ Applies ‘-’ unary operator to built-in type ƒ Operation is ‘known’ for built-in types ƒ Returns anonymous object again Overloaded ‘-’ Usage ƒ Consider: Money amount1(10), amount2(6), amount3; amount3 = amount1 – amount2; ƒ Calls binary ‘-’ overload amount3.output(); //Displays $4.00 amount3 = -amount1; ƒ Calls unary ‘-’ overload amount3.output() //Displays -$10.00

Overloading as Member Functions ƒ Previous examples: standalone functions ƒ Defined outside a class ƒ Can overload as ‘member operator’ ƒ Considered ‘member function’ like others ƒ When operator is member function: ƒ Only ONE parameter, not two! ƒ Calling object serves as 1st parameter Member Operator in Action ƒ Money cost(1, 50), tax(0, 15), total; total = cost + tax; ƒ If ‘+’ overloaded as member operator: ƒ Variable/object cost is calling object ƒ Object tax is single argument ƒ Think of as: total = cost.+(tax); ƒ Declaration of ‘+’ in class definition: ƒ const Money operator +(const Money& amount); ƒ Notice only ONE argument

const Functions ƒ When to make function const? ƒ Constant functions not allowed to alter class member ƒ Constant objects can ONLY call constant member functions ƒ Good style dictates: ƒ Any member function that will NOT modify data should be made const ƒ Use keyword const after function declaration and heading Overloading Operators: Which Method? ƒ Object-Oriented-Programming ƒ Principles suggest member operators ƒ Many agree, to maintain ‘spirit’ of OOP ƒ Member operators more efficient ƒ No need to call accessor & mutator functions

Friend Functions ƒ Nonmember functions ƒ Recall: operator overloads as nonmembers ƒ They access data through accessor and mutator functions ƒ Very inefficient (overhead of calls) ƒ Friends can directly access private class data ƒ No overhead, more efficient ƒ So: best to make nonmember operator overloads friends! Friend Functions ƒ Friend function of a class ƒ Not a member function ƒ Has direct access to private members ƒ Just as member functions do ƒ Use keyword friend in front of function declaration ƒ Specified IN class definition ƒ But they’re NOT member functions!

Friend Function Uses ƒ Operator Overloads ƒ Most common use of friends ƒ Improves efficiency ƒ Avoids need to call accessor/mutator member functions ƒ Operator must have access anyway ƒ Might as well give full access as friend ƒ Friends can be any function Friend Function Purity ƒ Friends not pure? ƒ ‘Spirit’ of OOP dictates all operators and functions be member functions ƒ Many believe friends violate basic OOP principles ƒ Advantageous? ƒ For operators: very! ƒ Allows automatic type conversion ƒ Still encapsulates: friend is in class definition ƒ Improves efficiency

Friend Classes ƒ Entire classes can be friends ƒ Similar to function being friend to class ƒ Example: class F is friend of class C ƒ All class F member functions are friends of C ƒ NOT reciprocated ƒ Friendship granted, not taken ƒ Syntax: friend class F ƒ Goes inside class definition of ‘authorizing’ class References ƒ Reference defined: ƒ Name of a storage location ƒ Similar to ‘pointer’ ƒ Example of stand alone reference: ƒ int robert; int& bob = robert; ƒ bob is reference to storage location for robert ƒ Changes made to bob will affect robert ƒ Confusing?

References Usage ƒ Seemingly dangerous ƒ Useful in several cases: ƒ Call-by-reference ƒ Often used to implement this mechanism ƒ Returning a reference ƒ Allows operator overload implementations to be written more naturally ƒ Think of as returning an ‘alias’ to a variable Returning Reference in Definition ƒ Example function definition: double& sampleFunction(double& variable) { return variable; } ƒ Trivial, useless example ƒ Shows concept only ƒ Major use: ƒ Certain overloaded operators

Overloading >> and << ƒ Enables input and output of our objects ƒ Similar to other operator overloads ƒ New subtleties ƒ Improves readability ƒ Like all operator overloads do ƒ Enables: cout << myObject; cin >> myObject; ƒ Instead of need for: myObject.output(); … Overloading >> ƒ Insertion operator, << ƒ Used with cout ƒ A binary operator ƒ Example: cout << “Hello”; ƒ Operator is << ƒ 1st operand is predefined object cout ƒ From library iostream ƒ 2nd operand is literal string “Hello”

Overloading >> ƒ Operands of >> ƒ Cout object, of class type ostream ƒ Our class type ƒ Recall Money class ƒ Used member function output() ƒ Nicer if we can use >> operator: Money amount(100); cout << “I have “ << amount << endl; instead of: cout << “I have “; amount.output() Overloaded >> Return Value ƒ Money amount(100); cout << amount; ƒ << should return some value ƒ To allow cascades: cout << “I have “ << amount; (cout << “I have “) << amount; ƒ Two are equivalent ƒ What to return? ƒ cout object! ƒ Returns it’s first argument type, ostream

Overloaded >> Example Display 8.5, page 331 Overloaded >> Example Cont’d Display 8.5, page 331

Overloaded >> Example Cont’d

Display 8.5, page 331 Assignment Operator, = ƒ Must be overloaded as member operator ƒ Automatically overloaded ƒ Default assignment operator: ƒ Member-wise copy ƒ Member variables from one object Æ corresponding member variables from other ƒ Default OK for simple classes ƒ But with pointers Æ must write our own!

Increment and Decrement ƒ Each operator has two versions ƒ Prefix notation: ++x; ƒ Postfix notation: x++; ƒ Must distinguish in overload ƒ Standard overload method Æ Prefix ƒ Add 2d parameter of type int Æ Postfix ƒ Just a marker for ! ƒ Specifies postfix is allowed Summary 1 ƒ C++ built-in operators can be overloaded ƒ To work with objects of your class ƒ Operators are really just functions ƒ Friend functions have direct private member access ƒ Operators can be overloaded as member functions ƒ 1st operand is calling object

Summary 2 ƒ Friend functions add efficiency only ƒ Not required if sufficient accessors/mutators available ƒ Reference ‘names’ a variable with an alias ƒ Can overload <<, >> ƒ Return type is a reference to type