Ch. 12: Operator Overloading

Similar documents
Ch. 11: References & the Copy-Constructor. - continued -

Fast Introduction to Object Oriented Programming and C++

QUIZ on Ch.5. Why is it sometimes not a good idea to place the private part of the interface in a header file?

More Advanced Class Concepts

KOM3191 Object Oriented Programming Dr Muharrem Mercimek OPERATOR OVERLOADING. KOM3191 Object-Oriented Programming

C++ (Non for C Programmer) (BT307) 40 Hours

QUIZ Friends class Y;

Short Notes of CS201

2 ADT Programming User-defined abstract data types

CS201 - Introduction to Programming Glossary By

CS201 Some Important Definitions

QUIZ. What is wrong with this code that uses default arguments?

Vectors of Pointers to Objects. Vectors of Objects. Vectors of unique ptrs C++11. Arrays of Objects

QUIZ How do we implement run-time constants and. compile-time constants inside classes?

Midterm 2. 7] Explain in your own words the concept of a handle class and how it s implemented in C++: What s wrong with this answer?

Introduction to Programming Using Java (98-388)

Introduction to Programming using C++

Instantiation of Template class

Absolute C++ Walter Savitch

More class design with C++ Starting Savitch Chap. 11

PIC 10A Objects/Classes

CS304 Object Oriented Programming Final Term

1. Describe History of C++? 2. What is Dev. C++? 3. Why Use Dev. C++ instead of C++ DOS IDE?

IS0020 Program Design and Software Tools Midterm, Fall, 2004

Chapter 8. Operator Overloading, Friends, and References. Copyright 2010 Pearson Addison-Wesley. All rights reserved

Overloaded Operators, Functions, and Students

Ch. 10: Name Control

QUIZ: What value is stored in a after this

ADTs & Classes. An introduction

11.2. Overloading Operators

Object-Oriented Principles and Practice / C++

Introduction to Computers and C++ Programming p. 1 Computer Systems p. 2 Hardware p. 2 Software p. 7 High-Level Languages p. 8 Compilers p.


Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 8/19/ Review. Here s a simple C++ program:

QUIZ. What are 3 differences between C and C++ const variables?

C++ Programming: From Problem Analysis to Program Design, Third Edition

OBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe

Program construction in C++ for Scientific Computing

Operator Overloading in C++ Systems Programming

Lecture Topics. Administrivia

Overloading Operators in C++

QUIZ. 1. Explain the meaning of the angle brackets in the declaration of v below:

Interview Questions of C++

QUIZ. How could we disable the automatic creation of copyconstructors

I BSc(IT) [ Batch] Semester II Core: Object Oriented Programming With C plus plus - 212A Multiple Choice Questions.

These are notes for the third lecture; if statements and loops.

C++ for Java Programmers

UNIT- 3 Introduction to C++

G52CPP C++ Programming Lecture 17

QUIZ. How could we disable the automatic creation of copyconstructors

C++ Basic Elements of COMPUTER PROGRAMMING. Special symbols include: Word symbols. Objectives. Programming. Symbols. Symbols.

Writing an ANSI C Program Getting Ready to Program A First Program Variables, Expressions, and Assignments Initialization The Use of #define and

EINDHOVEN UNIVERSITY OF TECHNOLOGY Department of Mathematics and Computer Science

CHAPTER 1 Introduction to Computers and Programming CHAPTER 2 Introduction to C++ ( Hexadecimal 0xF4 and Octal literals 031) cout Object

Chapter 13: Copy Control. Overview. Overview. Overview

Chapter 18 - C++ Operator Overloading

Object-Oriented Design (OOD) and C++

CISC 2200 Data Structure Fall, C++ Review:3/3. 1 From last lecture:

C++ Addendum: Inheritance of Special Member Functions. Constructors Destructor Construction and Destruction Order Assignment Operator

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor.

QUIZ How do we implement run-time constants and. compile-time constants inside classes?

QUIZ. Can you find 5 errors in this code?

Problem Solving with C++

C++ Programming Chapter 7 Pointers

LESSON 1. A C program is constructed as a sequence of characters. Among the characters that can be used in a program are:

CSC 210, Exam Two Section February 1999

CSCI-1200 Data Structures Fall 2017 Lecture 5 Pointers, Arrays, & Pointer Arithmetic

Page. No. 1/15 CS201 Introduction to Programmming Solved Subjective Questions From spring 2010 Final Term Papers By vuzs Team

Slide Set 14. for ENCM 339 Fall Steve Norman, PhD, PEng. Electrical & Computer Engineering Schulich School of Engineering University of Calgary

CSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010

COP 3275: Chapter 04. Jonathan C.L. Liu, Ph.D. CISE Department University of Florida, USA

Week 3 More Formatted Input/Output; Arithmetic and Assignment Operators

CSCI-1200 Data Structures Spring 2018 Lecture 10 Vector Iterators & Linked Lists

OBJECT ORIENTED PROGRAMMING USING C++

Control Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003

JAVASCRIPT AND JQUERY: AN INTRODUCTION (WEB PROGRAMMING, X452.1)

Review of the C Programming Language

Java Primer 1: Types, Classes and Operators

Object-Oriented Programming

Roxana Dumitrescu. C++ in Financial Mathematics

Understanding main() function Input/Output Streams

Chapter 10. Pointers and Dynamic Arrays. Copyright 2016 Pearson, Inc. All rights reserved.

C Language Part 1 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee

Reference Parameters A reference parameter is an alias for its corresponding argument in the function call. Use the ampersand (&) to indicate that

The issues. Programming in C++ Common storage modes. Static storage in C++ Session 8 Memory Management

Ch 8. Operator Overloading, Friends, and References

Fundamentals. Fundamentals. Fundamentals. We build up instructions from three types of materials

G52CPP C++ Programming Lecture 20

And Even More and More C++ Fundamentals of Computer Science

Object Oriented Design

Review of the C Programming Language for Principles of Operating Systems

CSE 303: Concepts and Tools for Software Development

Chapter 3. Numeric Types, Expressions, and Output

A student was asked to point out interface elements in this code: Answer: cout. What is wrong?

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

CSCI-1200 Data Structures Fall 2017 Lecture 10 Vector Iterators & Linked Lists

This wouldn t work without the previous declaration of X. This wouldn t work without the previous declaration of y

A <Basic> C++ Course

A <Basic> C++ Course

Chapter 2: Basic Elements of C++

Transcription:

Ch. 12: Operator Overloading

Operator overloading is just syntactic sugar, i.e. another way to make a function call: shift_left(42, 3); 42 << 3; The difference is that the arguments for this function don t appear inside parentheses, but instead they surround or are next to the operator s character(s). example

Just a wrapper for the int type! Let s first understand what we re trying to do!

We would like to operate with Integer objects the same way we operate with int!

Wait a second! Isn t + a binary operator?

Yes, but, when defined as member function, the LEFT operand is always the object, so only the RIGHT operand needs to be passed.

Why is the return value const?

In order to prevent crazy uses like (x + y) = z;

Write the member function to overload the division / operator. QUIZ

If we want to use this function, we must #include <cassert> Note: The author of the text has his own, customized version of assert, called require:..

Now let s overload the compound assignment operator +=

... Why non-const and why reference?

... Non-const to allow uses accepted in C: (x += y) += z; Reference to prevent the creation of a copy.

... If this is a pointer to the current object, *this is

Unary operators Since only one operator is needed, if we want it passed explicitly, we have to use global functions: declarations... definitions

... definitions

If we want to use member functions, then no argument is passed!...

Pre- and postincrement When the compiler sees ++a (a pre-increment), it generates a call to operator++(a); but when it sees a++, it generates a call to operator++(a, int). That is, it differentiates between the two forms by making calls to different overloaded functions.

QUIZ Write the member function to overload the subtraction operator. Clearly explain the choices you make for: Return value Argument(s)

QUIZ The choices for: Return value: Value, b/c we re creating a new variable, and we don t want a leaked reference const, b/c we want to forbid (a b) = 42; Argument(s): Only rv if we make it a member function const for safety, since the function should not modify the argument Reference to avoid making a copy (in case of large object).

QUIZ What is this type of argument called? Based on their signatures (i.e. function headers), explain what the compiler does when it encounters each operator.

QUIZ When the compiler sees ++a (a pre-increment), it generates a call to operator++(a); but when it sees a++, it generates a call to operator++(a, int). That is, it differentiates between the two forms by making calls to different overloaded functions.

QUIZ Why does Integer have to befriend all these functions?....

Solution B/c they re global functions that need to access a private member.....

Read and take notes: Binary operators

Arguments & return values - GUIDELINES - 1.If you only need to read from the argument and not change it, default to passing it as a const reference. Ordinary arithmetic operations (like + and, etc.) and Booleans will not change their arguments, so pass by const reference is predominantly what you ll use. When the function is a class member, this translates to making it a const member function.

Arguments & return values - GUIDELINES - 1.If you only need to read from the argument and not change it, default to passing it as a const reference. Only with the operator-assignments (like +=) and the operator=, which change the left-hand argument, is the left argument not a constant, but it s still passed in as an address because it will be changed.

Arguments & return values - GUIDELINES - 2. The type of return value you should select depends on the expected meaning of the operator. If the effect of the operator is to produce a new value, you will need to generate a new object as the return value. For example, Integer::operator+ must produce an Integer object that is the sum of the operands. This object is returned by value as a const, so the result cannot be modified as an lvalue.

Arguments & return values - GUIDELINES - 3. All the assignment operators modify the lvalue. To allow the result of the assignment to be used in chained expressions, like a=b=c, it s expected that you will return a reference to that same lvalue that was just modified. But should this reference be a const or nonconst? Although you read a=b=c from left to right, the compiler parses it from right to left, so you re not forced to return a nonconst to support assignment chaining. Assignment is right-associative

QUIZ What is the output? a = b = c = d ;

QUIZ It s the same as if parenthesized thus: a = b = c = d ;

Arguments & return values - GUIDELINES - 3. All the assignment operators modify the lvalue. To allow the result of the assignment to be used in chained expressions, like a=b=c, it s expected that you will return a reference to that same lvalue that was just modified. However, people do sometimes expect to be able to perform an operation on the object that was just assigned to, such as (a=b).func( ); to call func( ) on a after assigning b to it. Thus, the return value for all of the assignment operators should be a nonconst reference to the lvalue.

Returning a temporary a.k.a. the return value optimization This is how what we explained in ch.11. Constructor, copy-constructor, and destructor are called. vs. If we do the return this way, the compiler builds the object directly into the location of the outside return value. Only the constructor is called. No copy-constructor is called! No destructor is called (no object in this function s scope leave it to the caller s scope!)

Individual work for next time: End-of-chapter exercises 1, 2, 3 EOL 1

SKIP: operator[] new delete comma operator, operator ->*

Operator -> Remember how we have used it so far: the LHS must be a pointer (to a struct, union or class). When we overload it, it is because we want to make an object appear to be a pointer. Since such an object has more smarts built into it than a typical pointer, it is called a smart pointer.

Operator -> Especially useful if you want to: wrap a class around a pointer to make it safe create an iterator (object that moves through a collection /container of other objects and selects them one at a time, without providing direct access to the implementation of the container)

Operator -> A pointer dereference operator must: be a member function return an object (or reference to an object) that also has a pointer dereference operator, or return a pointer that can be used to select what the pointer dereference operator arrow is pointing at. example

These objects are used in the text program C12: SmartPointer.cpp

..... Member function of the vector class nullptr

Let s understand this! sp is an object of class SmartPointer (next slide) Abort at the end of container

Shouldn t it be sp -> -> f() instead?

Shouldn t it be sp -> -> f() instead? A: No, because oc is a reference, which automatically dereferences itself!!

It s more common to see a smart pointer or iterator class nested within the class that it services see the following example C12:NestedSmartPointer.cpp We shall examine the nested smart pointer example in the lab.

Operators you can t overload The member selection operator. The pointer to member dereference operator.* There s no exponentiation operator. The most popular choice for this was operator** from Fortran, but it raised difficult parsing questions for compilers. Also, C has no exponentiation operator, so C++ didn t seem to need one either because you can always perform a function call.

Operators you can t overload There are no user-defined operators. For existing operators, we can t change: precedence rules nr. of arguments.

To do for next time: Solve end-of-chapter exercises 4, 5 EOL 2

Non-member operators If it doesn t make any difference whether we overload the operators with member or global functions, it is recommended to choose member functions; this emphasizes the association between the operator and its class.

Non-member operators However, sometimes you want the left-hand operand to be an object of some other class. Application: when the operators << and >> are overloaded for iostreams; we want to be able to write: MyClass myobject; cout <<myobject; cin >>myobject; Since iostreams is a fundamental C++ library, you ll probably want to overload these operators for most of your classes, so the process is worth memorizing

C12:IostreamOperatorOverloading.cpp The operator [] is overloaded through a member function Making friends with two global functions that overload the operators << and >>

Global function definitions These are the original versions of the operators, from <iostream>

Global function definitions Why by reference? B/c we want the external objects to change after applying the overloaded operators.

Global function definitions Why return anything? It would be simpler to make the functions void! A: We want to be able to use the returned ostream and istream in a more complex expression (see next slides for example).

This is how the operators are employed in user code stringstream is a stream class that allows easy operation on strings. Objects of this class use a string buffer that contains a sequence of characters. Characters can be inserted and/or extracted from the stream using any operation allowed on both input and output streams.

Is it legal to do this? IntArray I1, I2;.... input >> I1 >>I2; A: Yes, but only because the overloading function returns the stream!

Overloading assignment = Doesn t the copy constructor take care of assignment? Remember the rule: the copy-constructor is called (only) when a new object is created from an existing object! Default constructor Copy constructor Overloaded operator =

The right-hand side does not even need to be a user-defined object: Assignment syntax, equivalent to Fee fee(1); This constructor is called

Conclusion: Any time we re initializing an object using an = instead of the ordinary function-call form of the constructor, the compiler will look for a constructor that accepts whatever is on the right-hand side.

One simple rule: copy all of the necessary information from the right-hand object into the current object (that is, the object that operator= is being called for)

and one common mistake: not checking first for self-assignment! In some cases, such as this one, it s harmless if you perform the assignment operations anyway, but if changes are made to the implementation of the class, it can make a difference, and if you don t do it as a matter of habit, you may forget and cause hardto-find bugs. example

Important case in which self-assignment is dangerous: Pointers in classes Problem: Simply copying a pointer means that you ll end up with two objects pointing to the same storage location. Solution: You need to do bookkeeping of your own. example

Simply copy whatever the pointer refers to. (Also works for copyconstruction.)

Draw a memory map!

Problem with the copy technique If the object requires a lot of memory or time for initialization, copying is not efficient. Solution: next slide

Reference counting You give intelligence to the object that s being pointed to so it knows how many objects are pointing to it. Both copy-construction and assignment mean: attaching another pointer to an existing object and incrementing the reference count. Destruction means: decrementing the reference count. If the reference count goes to zero, destroy the object!

Read and understand C12:ReferenceCounting.cpp

Automatic operator= creation Because assigning an object to another object of the same type is an activity most people expect to be possible, the compiler will automatically create a type::operator=(type) if you don t make one. The behavior of this operator mimics that of the automatically created copy-constructor; if the class contains objects (or is inherited from another class), the operator= for those objects is called recursively, a.k.a. memberwise assignment.

We can disable the use of assignment for a class Remember from ch.11: Deleted functions were introduced in C++11

We stop before the section Automatic type conversion SKIP the remainder of ch.12 EOL 3