Operator overloading. Conversions. friend. inline

Similar documents
Intro to OOP Visibility/protection levels and constructors Friend, convert constructor, destructor Operator overloading a<=b a.

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

Short Notes of CS201

Instantiation of Template class

See the CS 2704 notes on C++ Class Basics for more details and examples. Data Structures & OO Development I

CS201 - Introduction to Programming Glossary By

Constructors for classes

Appendix. Grammar. A.1 Introduction. A.2 Keywords. There is no worse danger for a teacher than to teach words instead of things.

2 ADT Programming User-defined abstract data types

Protection Levels and Constructors The 'const' Keyword

KLiC C++ Programming. (KLiC Certificate in C++ Programming)

14.1. Chapter 14: static member variable. Instance and Static Members 8/23/2014. Instance and Static Members

Abstraction and Encapsulation. Benefits of Abstraction & Encapsulation. Concrete Types. Using Typedefs to streamline classes.

C++ 8. Constructors and Destructors

Outline. User-dened types Categories. Constructors. Constructors. 4. Classes. Concrete classes. Default constructor. Default constructor

Object-Oriented Principles and Practice / C++

Software Engineering Concepts: Invariants Silently Written & Called Functions Simple Class Example

XII- COMPUTER SCIENCE VOL-II MODEL TEST I

From Java to C++ From Java to C++ CSE250 Lecture Notes Weeks 1 2, part of 3. Kenneth W. Regan University at Buffalo (SUNY) September 10, 2009

Chapter 13: Copy Control. Overview. Overview. Overview

CS304 Object Oriented Programming Final Term

Classes in C++98 and C++11

Ch02. True/False Indicate whether the statement is true or false.

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

Paytm Programming Sample paper: 1) A copy constructor is called. a. when an object is returned by value

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

Preface to the Second Edition Preface to the First Edition Brief Contents Introduction to C++ p. 1 A Review of Structures p.

Object-Oriented Principles and Practice / C++

THE BIG FOUR FRIEND FUNCTIONS

Classes and Objects. Class scope: - private members are only accessible by the class methods.

Introduction to Classes

CGS 2405 Advanced Programming with C++ Course Justification

Advanced C++ Topics. Alexander Warg, 2017

SRM ARTS AND SCIENCE COLLEGE SRM NAGAR, KATTANKULATHUR

Fast Introduction to Object Oriented Programming and C++

Operating Systems CMPSCI 377, Lec 2 Intro to C/C++ Prashant Shenoy University of Massachusetts Amherst

Copy Control 2008/04/08. Programming Research Laboratory Seoul National University

Overloaded Operators, Functions, and Students

Outline. 1 Function calls and parameter passing. 2 Pointers, arrays, and references. 5 Declarations, scope, and lifetimes 6 I/O

Interview Questions of C++

Overloading & Polymorphism

Object-Oriented Programming

OBJ. ORI.& MULT. PROG., M.C.Q. BANK, FOR UNIT -2, SECOND YEAR COMP. ENGG. SEM-4, 2012 PATTERN, U.O.P. UNIT-2

C++ for System Developers with Design Pattern

Inheritance. OOP components. Another Example. Is a Vs Has a. Virtual Destructor rule. Virtual Functions 4/13/2017

cs3157: c++ lecture #2 (mon-11-apr-2005) chronology of some programming languages... C++ vs Java identifiers.

C++ Important Questions with Answers

Object-Oriented Principles and Practice / C++

CSC 330 Object Oriented Programming. Operator Overloading Friend Functions & Forms

C++ Constructor Insanity

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

(5 2) Introduction to Classes in C++ Instructor - Andrew S. O Fallon CptS 122 (February 7, 2018) Washington State University

Syllabus of C++ Software for Hands-on Learning: This course offers the following modules: Module 1: Getting Started with C++ Programming

Where do we go from here?

What will happen if we try to compile, link and run this program? Do you have any comments to the code?

Preface... (vii) CHAPTER 1 INTRODUCTION TO COMPUTERS

Object-Oriented Principles and Practice / C++

Dynamic memory in class Ch 9, 11.4, 13.1 & Appendix F

the gamedesigninitiative at cornell university Lecture 7 C++ Overview

Object Oriented Programming COP3330 / CGS5409

Plan of the day. Today design of two types of container classes templates friend nested classes. BABAR C++ Course 103 Paul F. Kunz

Review: C++ Basic Concepts. Dr. Yingwu Zhu

The paramaterless ctor (aka default ctor)

GEA 2017, Week 4. February 21, 2017

Chapter 13: Introduction to Classes Procedural and Object-Oriented Programming

Object Oriented Programming COP3330 / CGS5409

Classes: Member functions // classes example #include <iostream> using namespace std; Objects : Reminder. Member functions: Methods.

ADTs & Classes. An introduction

Operator Dot Wording

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

A <Basic> C++ Course

CSC1322 Object-Oriented Programming Concepts

! Data is stored in variables. - Perhaps using arrays and structs. ! Program is a collection of functions that perform

A <Basic> C++ Course

COP4530 Data Structures, Algorithms and Generic Programming Recitation 4 Date: September 14/18-, 2008

More Advanced Class Concepts

SFU CMPT Topic: Class Templates

CSE 333. Lecture 11 - constructor insanity. Hal Perkins Paul G. Allen School of Computer Science & Engineering University of Washington

Wentworth Institute of Technology COMP201 Computer Science II Spring 2015 Derbinsky. C++ Kitchen Sink. Lecture 14.

IS0020 Program Design and Software Tools Midterm, Fall, 2004

Lecture 8: Object-Oriented Programming (OOP) EE3490E: Programming S1 2017/2018 Dr. Đào Trung Kiên Hanoi Univ. of Science and Technology

Arizona s First University. ECE 373. Operation Overloading. The Revolution Operation Will Be Televised (and, these slides will be online later today)

CS

Abstraction in Software Development

Chapter 18 - C++ Operator Overloading

Chapter 11: More About Classes and Object-Oriented Programming

CS3157: Advanced Programming. Outline

Next week s homework. Classes: Member functions. Member functions: Methods. Objects : Reminder. Objects : Reminder 3/6/2017

Object Oriented Programming. Assistant Lecture Omar Al Khayat 2 nd Year

Intermediate Programming & Design (C++) Classes in C++

Introduction to Programming Using Java (98-388)

Recharge (int, int, int); //constructor declared void disply();

Cpt S 122 Data Structures. Course Review Midterm Exam # 2

Evolution of Programming Languages

Motivation for Templates

CS24 Week 3 Lecture 1

Learning Objectives. C++ For Artists 2003 Rick Miller All Rights Reserved xli

III. Classes (Chap. 3)

7.1 Optional Parameters

RAJIV GANDHI COLLEGE OF ENGINEERING AND TECHNOLOGY DEPARTMENT OF INFORMATION TECHNOLOGY OBJECT ORIENTED PROGRAMMING QUESTION BANK UNIT I 2 MARKS

Transcription:

Operator overloading Conversions friend inline.

Operator Overloading Operators like +, -, *, are actually methods, and can be overloaded. Syntactic sugar.

What is it good for - 1 Natural usage. compare: a.set( add(b,c) ) to a= b+c compare: v.elementat(i)= 3 to v[i]= 3

What is it good for - 2 Semantic integrity. A rule of thumb: When you need to make a deep copy of an object, you need to define all of these: 1. Copy constructor 2. Destructor 3. Operator = Or in other words: when you need one, you need all.

What is it good for - 3 Uniformity with base types (important for templates) template<typename T> const T& min(const T& a, const T& b) { return a<b? a : b; } a and b can be primitives or user defined objects that have operator <

Rules 1. Don't overload operators with non-standard behavior! (<< for adding,...) 2. Check how operators work on primitives or in the standard library and give the same behavior in your class.

Example of usage in primitives/standard library >> << are used as bit operations for primitives numbers and for I/O in the standard library iostreams classes. [] is used as subscripting primitives arrays and vector class in the standard library. () is used for function calls and for functor objects in the standard library.

Prototype X& operator=(const X& rval) return type method name parameter for object on right side of operator

Invoking an Overloaded Operator Operator can be invoked as a member function: object1.operator=(object2); It can also be used in more conventional manner: object1= object2;

A skeleton for deep copy // Copy constructor A (const A& other) { // init // copy other } // Destructor ~A() { // clear } // Operator = A& operator=(const A& other) { if (this!=&other) { // preventing problems in a=a // clear // copy other } return *this; } // allows a= b= c=

C++-11 Move ctor and assignment (not learned in this class) // Move constructor A (const A&& other) { }? // Move operator = A& operator=(const A&& other) { }? http://www.cprogramming.com/c++11/rvaluereferences-and-move-semantics-in-c++11.html

List & Complex examples

Operators ++ -- postfix prefix // Prefix: ++n HNum& operator++() { code that adds one to this HNum return *this; // return ref to curr } A flag that makes it postfix // Postfix : n++ const HNum operator++(int) { Hnum cpy(*this); // calling copy ctor code that adds one to this HNum return cpy; } 13

Operators ++ -- postfix prefix // Prefix: ++n HNum& operator++() { code that adds one to this HNum return *this; // return ref to curr } A flag that makes it postfix // Postfix : n++ const HNum operator++(int) { Hnum cpy(*this); // calling copy ctor code that adds one to this HNum return cpy; } // For HNum, it might be a good idea not to 14

Conversions of types is done in two cases: 1. Explicit casting (we'll learn more about it in next lessons) 15

Conversions of types is done in two cases: 1. Explicit casting (we'll learn more about it in next lessons) 2. When a function gets X type while it was expecting to get Y type, and there is a casting from X to Y: void foo(y y)... X x; foo(x); // a conversion from X to Y is done 16

Conversion example (conv.cpp) 17

Conversions danger: unexpected behavior Buffer(size_t length) // ctor void foo(const Buffer& v) // function... foo(3); // Equivalent to: foo(buffer(3)) // Did the user really wanted this? The Buffer and the size_t objects are not logically the same objects! 18

Conversion example (conv_explicit.cpp) 19

User defined conversion class Fraction {... // double --> Fraction conversion Fraction (const double& d) {... }... // Fraction --> double conversion operator double() const {... } 20

friend 21

friend functions Friend function in a class: Not a method of the class Have access to the class s private and protected data members Defined inside the class scope Used properly does not break encapsulation 22

friend functions example: Complex revisited 23

friend classes A class can allow other classes to access its private data members The friendship is one sided 24

class IntTree { friend class IntTreeIterator; }; friend classes - example // TreeIterator can access Tree's data members IntTreeIterator& IntTreeIterator::operator++() {... return *this; } 25

Inline functions / methods 26

Inline functions / methods A hint to a compiler to put function s code inline, rather than perform a regular function call. Objective: improve performance of small, frequently used functions. An inline function defined in.cpp file is not recognized in other source files. 27

compare: C vs C++ : macro vs inlining define SQRT(x) ((x)*(x)) SQRT(i++) // unexpected behavior to inline int sqrt(int x) { return x*x; } sqrt(i++) // good behavior 28

Inline methods You can hint to the compiler that a method is inline in class declaration (inside the { }; block of a class): class Tree {... size_t size() const{ // automatically hints on inline return _size; } }; 29

Inline methods You can hint to the compiler that a method is inline after class declaration: class Tree {... size_t size() const;... }; inline size_t Tree::size() const { // still in the h file return _size; } 30

Tradeoffs: Inline vs. Regular Functions / Methods Regular functions when called, compiler stores return address of call, allocates memory for local variables, etc. 31

Tradeoffs: Inline vs. Regular Functions / Methods Regular functions when called, compiler stores return address of call, allocates memory for local variables, etc. Code for an inline function is copied into program in place of call can enlarge executable program, but no function call overhead, hence usually faster execution. 32

Tradeoffs: Inline vs. Regular Functions / Methods Regular functions when called, compiler stores return address of call, allocates memory for local variables, etc. Code for an inline function is copied into program in place of call can enlarge executable program, but no function call overhead, hence usually faster execution. Can enlarge compile time. You compile the inline function again and again in every place it's used. 33