Special Member Functions

Similar documents
Special Member Functions. Compiler-Generated Destructor. Compiler-Generated Default Constructor. Special Member Functions

Copy Constructor, Assignment, Equality

Entity vs. Value, Modules, Hidden Implementation, Interface Specification

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

COMP6771 Advanced C++ Programming

THE NAME OF THE CONSTRUCTOR AND DESTRUCTOR(HAVING (~) BEFORE ITS NAME) FUNCTION MUST BE SAME AS THE NAME OF THE CLASS IN WHICH THEY ARE DECLARED.

Modern C++ for Computer Vision and Image Processing. Igor Bogoslavskyi

Value vs. Entity Objects, Information Hiding

04-19 Discussion Notes

C++ 8. Constructors and Destructors

static CS106L Spring 2009 Handout #21 May 12, 2009 Introduction

Object-Oriented Principles and Practice / C++

Object-Oriented Principles and Practice / C++

Written by John Bell for CS 342, Spring 2018

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

Determine a word is a palindrome? bool ispalindrome(string word, int front, int back) { Search if a number is in an array

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

More About Classes. Gaddis Ch. 14, CS 2308 :: Fall 2015 Molly O'Neil

Abstract Data Types (ADTs) 1. Legal Values. Client Code for Rational ADT. ADT Design. CS 247: Software Engineering Principles

CS 247: Software Engineering Principles. ADT Design

Overview of C Feabhas Ltd 2012

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

G52CPP C++ Programming Lecture 13

Constants, References

Assertions and Exceptions

Chapter 10 Pointers and Dynamic Arrays. GEDB030 Computer Programming for Engineers Fall 2017 Euiseong Seo

Copying Data. Contents. Steven J. Zeil. November 13, Destructors 2

6.096 Introduction to C++ January (IAP) 2009

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

CS32 - Week 1. Umut Oztok. June 24, Umut Oztok CS32 - Week 1

Launchpad Lecture -10

Copy Constructors and Assignment Operators

Make Classes Useful Again

A506 / C201 Computer Programming II Placement Exam Sample Questions. For each of the following, choose the most appropriate answer (2pts each).

Object-Oriented Programming

2 ADT Programming User-defined abstract data types

Everything You Ever Wanted To Know About Move Semantics

Vector and Free Store (Vectors and Arrays)

COMP6771 Advanced C++ Programming

Assignment operator string class c++ Assignment operator string class c++.zip

Constructors for classes

Programmazione. Prof. Marco Bertini

Introduction to Classes

CS 247: Software Engineering Principles. C++ Templates. Reading: Eckel, Vol. 2 Ch. 5 Templates in Depth. U Waterloo CS247 (Spring 2017) p.

Assignment of Structs

Programming, numerics and optimization

CPSC 427: Object-Oriented Programming

Rvalue References & Move Semantics

Rvalue References, Move Semantics, Universal References

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

Object Oriented Programming COP3330 / CGS5409

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

CS 247: Software Engineering Principles. Modules

Object-Oriented Programming, Iouliia Skliarova

Object-Oriented Principles and Practice / C++

Object-Oriented Languages and Object-Oriented Design. Ghezzi&Jazayeri: OO Languages 1

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

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

CMSC 132: Object-Oriented Programming II

Assignment of Objects

Class Vector: Interface CSE 143. Dynamic Memory In Classes [Chapter 4, p ] Vector Implementation. Many Ways to Implement. Draw the picture!

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

Exception Safety. CS 311 Data Structures and Algorithms Lecture Slides Wednesday, October 28, Glenn G. Chappell. continued

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

Advanced C++ Topics. Alexander Warg, 2017

Ch. 12: Operator Overloading

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

Midterm Review. PIC 10B Spring 2018

Data types. Definitions Aggregate constructors User-defined type definitions Types and storage Types and subtypes Type systems and type checking

CS11 Advanced C++ Spring 2018 Lecture 2

CS304 Object Oriented Programming Final Term

CS260 Intro to Java & Android 03.Java Language Basics

THE BIG FOUR FRIEND FUNCTIONS

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

The paramaterless ctor (aka default ctor)

Advanced Systems Programming

CS 247 Software Engineering Principles Midterm Examination **Solutions** Spring 2017

C++ Programming: From Problem Analysis to Program Design, Fifth Edition. Chapter 12: Classes and Data Abstraction

LECTURE 03 LINKED LIST

An Introduction to C++

PIC 10B Lecture 1 Winter 2014 Homework Assignment #3

Agenda. The main body and cout. Fundamental data types. Declarations and definitions. Control structures

Intermediate Programming, Spring 2017*

Overloading Operators in C++

CSE 143. Linked Lists. Linked Lists. Manipulating Nodes (1) Creating Nodes. Manipulating Nodes (3) Manipulating Nodes (2) CSE 143 1

CS250 Final Review Questions

CIS 265/506 Exam1 Spring 2012 Prof. V. Matos Exam Last Name First Name:

Refresher: Interface Specifications. ADT Documentation. Set Represented as an Array. Representation Invariant, Abstraction Function

Multiple choice questions. Answer on Scantron Form. 4 points each (100 points) Which is NOT a reasonable conclusion to this sentence:

Chapter 13: Copy Control. Overview. Overview. Overview

Structs. Contiguously-allocated region of memory Refer to members within structure by names Members may be of different types Example: Memory Layout

Representation Invariant, Abstraction Function

Short Notes of CS201

C++11: 10 Features You Should be Using. Gordon R&D Runtime Engineer Codeplay Software Ltd.

CS250 Final Review Questions

CS201 - Introduction to Programming Glossary By

IS0020 Program Design and Software Tools Midterm, Fall, 2004

Allocation & Efficiency Generic Containers Notes on Assignment 5

Operator Overloading in C++ Systems Programming

Object-Oriented Programming. Lecture 4 Dr Piotr Cybula

Transcription:

CS 247: Software Engineering Principles Special Member Functions Readings: Eckel, Vol. 1 Ch. 11 References and the Copy Constructor Ch. 12 Operator Overloading ( operator= ) U Waterloo CS247 (Spring 2017) p.1/20

C++ member functions that are so important that the compiler will provide default versions if we don't provide them: default (0 parameters; generated iff we define no ) destructor Special Member Functions assignment ( operator= ) move move assignment U Waterloo CS247 (Spring 2017) p.2/20

Compiler-Generated Default Constructor If we do declare any for our class, the compiler will generate a default for us: based on memberwise initialization. simple data members (built-in types): uninitialized pointer members: uninitialized member objects: initialized using members' default s inherited members: initialized using base class default U Waterloo CS247 (Spring 2017) p.3/20

Compiler-Generated Destructor If we do declare a destructor for our class, the compiler will generate a destructor for us: based on memberwise destruction simple data members: deallocated pointer members: pointer deallocated ( deleted) member objects: cleaned up using members' destructors inherited members: cleaned up using base class's destructor U Waterloo CS247 (Spring 2017) p.4/20

Copy Constructor A constructs a new object whose value is equal to an existing object. - Used by the compiler to objects of the ADT. class Money; Money operator+ (Money m, Money n); int main() { Money m; Money n{m}; Money p = m; p = p + n; } U Waterloo CS247 (Spring 2017) p.5/20

Copying Objects with Pointers Shallow copies the object and its pointers' addresses, so that the original and copied pointers refer to the same object. Deep copies the object and what its pointers point to, so that the pointer data members refer to distinct objects. U Waterloo CS247 (Spring 2017) p.6/20

Compiler-Generated Copy Constructor If we do provide a default or /move or /move assignment, the compiler will generate a for us: based on memberwise simple data members: bitwise pointer members: bitwise member objects: copied using members' s inherited members: copied using base class's U Waterloo CS247 (Spring 2017) p.7/20

Copy Assignment Operator Copy assignment is similar to the, except that the destination of the already exists. X = Y; // deep X Y U Waterloo CS247 (Spring 2017) p.8/20

Compiler-Generated Assignment Operator If we do provide a /move or /move assignment, the compiler will create a operator= member function for us: based on memberwise assignment: simple data members: bitwise pointer members: bitwise member objects: uses members' assignment operators inherited members: uses base class's assignment operator X Y X = Y; // shallow U Waterloo CS247 (Spring 2017) p.9/20

Copy-Swap Idiom Assignment operators may deal with pointer members by: creating a new object of the same type with the swapping the old values of the pointer members with the values in the newly created object letting the destructor take care of deleting the old members but at the cost of efficiency!! // friend that swaps contents of m1 and m2 // using std::swap from <algorithm> void swap( MyClass & m1, MyClass &m2 ) { Base &b_m1 = static_cast<base&>(m1); Base &b_m2 = static_cast<base&>(m2); swap( b_m1, b_m2 ); std::swap( m1., m2. ); std::swap( m1., m2. ); std::swap( m1., m2. ); } MyClass& MyClass::operator= (const MyClass& m) { MyClass temp{m}; swap( *this, temp ); return *this; } U Waterloo CS247 (Spring 2017) p.10/20

Move Constructor A move constructs a new object whose value is equal to an existing object, but does preserve the value of the existing object. MyClass::MyClass (MyClass&& m) : Base{ std::move(m) }, { std::move(m.) }, { m.simple }, { m. } { } m. = nullptr; To invoke members move, need to pass an rvalue reference created by std::move() Only requirement of moved-from object is that it be easy to delete and () reassign. U Waterloo CS247 (Spring 2017) p.11/20

Compiler-Generated Move Constructor If we do provide a default or /move or /move assignment, then the compiler will generate a move for us: based on memberwise move simple data members: bitwise pointer members: bitwise member objects: uses members' move/ s inherited members: uses base class's move/?? U Waterloo CS247 (Spring 2017) p.12/20

Move Assignment Move assignment is similar to the move, except that the destination of the move already exists. Only requirement of moved-from object is that it be easy to delete and () reassign. MyClass& MyClass::operator= (MyClass&& m) { MyClass temp(0); swap( temp, m ); // temp steals m s contents swap( *this, temp ); // put what used to be in // m into this } return *this; U Waterloo CS247 (Spring 2017) p.13/20

Improved Assignment We can improve the code by passing the argument by value and unifying the assignment and move assignment operators into a single member method. Compiler will call this assignment operator even with an rvalue. MyClass::MyClass( const MyClass & other) : MyClass(0) { ( *this, other ); } MyClass::MyClass( MyClass && other ) : MyClass(0) { swap( *this, other ); } MyClass& MyClass::operator= (MyClass m) { swap( *this, m ); return *this; } U Waterloo CS247 (Spring 2017) p.14/20

Compiler-Generated Move Assignment If we do provide a /move or /move assignment, the compiler will create a move operator= member function for us: based on memberwise move assignment: simple data members: bitwise pointer members: bitwise member objects: uses members' move/ assignment inherited members: uses base class's move/ assignment X Y?? X = Y; // shallow U Waterloo CS247 (Spring 2017) p.15/20

http://accu.org/content/conf2014/howard_hinnant_accu_2014.pdf Special Members compiler implicitly declares default destructor assignment move move assignment Nothing defaulted defaulted defaulted defaulted defaulted defaulted declares Any default destructor assignment move move assignment defaulted defaulted defaulted defaulted defaulted defaulted defaulted defaulted defaulted defaulted defaulted defaulted defaulted defaulted defaulted defaulted defaulted defaulted defaulted deleted deleted defaulted defaulted deleted deleted

http://accu.org/content/conf2014/howard_hinnant_accu_2014.pdf Special Members compiler implicitly declares default destructor assignment move move assignment Nothing defaulted defaulted defaulted defaulted defaulted defaulted declares Any default destructor assignment move move assignment defaulted defaulted defaulted defaulted defaulted defaulted defaulted defaulted defaulted defaulted defaulted defaulted defaulted defaulted defaulted defaulted defaulted defaulted defaulted deleted deleted defaulted defaulted deleted deleted

Equality A copied/assigned object should be equal ( operator== ) to the original. Deep equality X compares Y Shallow equality X compares Y The compiler does NOT generate a default version of the equality operator we are on our own. U Waterloo CS247 (Spring 2017) p.18/20

Equality bool operator== ( const MyClass &m, const MyClass &m2 ) { if (!( Base::operator==(m, m2) ) ) return false; if ( m.!= m2. ) return false; if (! (m. == m2.) ) return false; if (! m.p_ &&! m2.p_ ) return true; if (! m.p_! m2.p_ ) return false; } return *m.p_ == *m2.p_ ; U Waterloo CS247 (Spring 2017) p.19/20

Take Aways Recognition C++ special member functions (6 of them): if one needs to be hand-crafted, likely all of them do Comprehension Best practices for ADT design Entity vs. Value-based ADTs Rules for compiler-default special member functions (default, destructor,, assignment) Application Operator overloading Const function arguments and member functions ADT design (entity vs. value-based design, immutable ADTs, hidden implementation) User-defined s, destructor,, assignment U Waterloo CS247 (Spring 2017) p.20/20