Constructors, Destructors, and Assignment Operators. Literature: Effective C++, Third Edition Chapter 2

Similar documents
G52CPP C++ Programming Lecture 13

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

Lecture 5: Inheritance

C++ Alexander Baltatzis

Object-Oriented Principles and Practice / C++

C++ Inheritance and Encapsulation

2 ADT Programming User-defined abstract data types

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

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

VIRTUAL FUNCTIONS Chapter 10

Object-Oriented Principles and Practice / C++

Tutorial 7. Y. Bernat. Object Oriented Programming 2, Spring Y. Bernat Tutorial 7

class Polynomial { public: Polynomial(const string& N = "no name", const vector<int>& C = vector<int>());... };

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

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

QUIZ Friends class Y;

CS 162, Lecture 25: Exam II Review. 30 May 2018

Object-Oriented Principles and Practice / C++

Concepts (this lecture) CSC 143. Classes with Dynamically Allocated Data. List of ints w/dups (cont.) Example: List of ints with dups.

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

The mechanism that allows us to extend the definition of a class without making any physical changes to the existing class is called inheritance.

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

G52CPP C++ Programming Lecture 20

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

Classes Ch

Special Member Functions

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

Object Oriented Design

An Introduction to C++

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

G52CPP C++ Programming Lecture 14. Dr Jason Atkin

Chapter 10 :: Data Abstraction and Object Orientation

Objects Managing a Resource

6.096 Introduction to C++ January (IAP) 2009

Computer Programming Inheritance 10 th Lecture

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

Midterm Review. PIC 10B Spring 2018

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

(12-1) OOP: Polymorphism in C++ D & D Chapter 12. Instructor - Andrew S. O Fallon CptS 122 (April 3, 2019) Washington State University

Instantiation of Template class

C++ Programming. Classes, Constructors, Operator overloading (Continued) M1 Math Michail Lampis

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

Chapter 9 :: Data Abstraction and Object Orientation

Do not write in this area TOTAL. Maximum possible points: 75

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

Module 10 Inheritance, Virtual Functions, and Polymorphism

CSC1322 Object-Oriented Programming Concepts

COMP6771 Advanced C++ Programming

C++ Coding Standards and Practices. Tim Beaudet March 23rd 2015

Casting in C++ (intermediate level)

Lecturer: William W.Y. Hsu. Programming Languages

G52CPP C++ Programming Lecture 12

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

For Teacher's Use Only Q No Total Q No Q No

COMP6771 Advanced C++ Programming

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

QUIZ. How could we disable the automatic creation of copyconstructors

Allocation & Efficiency Generic Containers Notes on Assignment 5

Introduction to C++ Introduction to C++ Dr Alex Martin 2013 Slide 1

JAYARAM COLLEGE OF ENGINEERING AND TECHNOLOGY Pagalavadi, Tiruchirappalli (An approved by AICTE and Affiliated to Anna University)

IS0020 Program Design and Software Tools Midterm, Fall, 2004

Laboratorio di Tecnologie dell'informazione. Ing. Marco Bertini

Chapter 13: Copy Control. Overview. Overview. Overview

Singleton, Factory Method, Abstract Factory, Named Constructor. Using one or more base classes to hide details from the client

COSC 2P95 Lab 5 Object Orientation

Outline. Dynamic Memory Classes Dynamic Memory Errors In-class Work. 1 Chapter 10: C++ Dynamic Memory

G52CPP C++ Programming Lecture 7. Dr Jason Atkin

Week 8: Operator overloading

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?

Critique this Code. Hint: It will crash badly! (Next slide please ) 2011 Fawzi Emad, Computer Science Department, UMCP

Tutorial 6. Y. Bernat. Object Oriented Programming 2, Spring Y. Bernat Tutorial 6

QUIZ. How could we disable the automatic creation of copyconstructors

CSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010

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

Constructors and Destructors. OOC 4 th Sem, B Div Prof. Mouna M. Naravani

Exception Namespaces C Interoperability Templates. More C++ David Chisnall. March 17, 2011

CMSC202 Computer Science II for Majors

Do not write in this area A.1 A.2 A.3 A.4 A.5 A.6 B.1 B.2 B.3 TOTAL. Maximum possible points:


Fast Introduction to Object Oriented Programming and C++

B16 Object Oriented Programming

Suppose we find the following function in a file: int Abc::xyz(int z) { return 2 * z + 1; }

Polymorphism. Miri Ben-Nissan (Kopel) Miri Kopel, Bar-Ilan University

Object Oriented Programming COP3330 / CGS5409

QUIZ. Can you find 5 errors in this code?

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

explicit class and default definitions revision of SC22/WG21/N1582 =

Software Design and Analysis for Engineers

What is Polymorphism? Quotes from Deitel & Deitel s. Why polymorphism? How? How? Polymorphism Part 1

Part VII. Object-Oriented Programming. Philip Blakely (LSC) C++ Introduction 194 / 370

C++ Inheritance and Encapsulation

However, in C we can group related variables together into something called a struct.

G52CPP C++ Programming Lecture 10. Dr Jason Atkin

Laboratorio di Tecnologie dell'informazione

Laboratorio di Tecnologie dell'informazione. Ing. Marco Bertini

C++ 8. Constructors and Destructors

CS201- Introduction to Programming Current Quizzes

Polymorphism Part 1 1

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

Assignment 1: grid. Due November 20, 11:59 PM Introduction

Transcription:

Constructors, Destructors, and Assignment Operators Literature: Effective C++, Third Edition Chapter 2

Overview Autogenerated Functions in Classes Prevent Autogeneration Explicitly Declare Destructors Virtual in Base Classes Don't call virtual functions during construction or destruction Handle assignment to self in operator= Copy all elements, when you are copying

Autogenerated Functions in Classes class Empty{ }; These two codes are THE SAME! - Default constructor - Copy constructor - Destructor - Copy assignment operator are created are autogenerated, if necessary and possible. Exceptions are discussed on the next slides. class Empty{ public: Empty ( ) { } // default constructor Empty(const Empty& rhs) { // copy constructor } ~Empty(){ } // destructor Empty& operator=(const Empty& rhs) { } // copy assignement // operator }; Empty empty1; Empty empty2 (empty1); empty2 = empty1;

- Autocreated constructor/destructor do nothing special (only usual creation of member variables etc.) - Destructor is virtual, if class inherits from base class with virtual destructor - Copy constructor, assignment operator initialize each non-static member variable from left side with value of right side.

No Autogeneration - constructor if there there is any constructor defined. This means as well, you can force a parameter is given. - Copy Assignment Operator - if the object has references or constants as member variables because C++ doesn't allow change of references or constants expect at initialization. - if class has base class with Copy Assignment Operator private, because class attempts to call operator of base class.

Prevent Autogeneration Explicitly Two ways to do so: Way 1 - declare your own versions of the functions privately only friend and member functions have access; write no definition linker error when used. Way 2 - get error at compile time, when using a base class with private function. You may use private inheritance e.g. class QuantumParticle{ public: Private: QantumParticle(const QuantumParticle&); // NOTE: DECLARATION ONLY; // NO DEFINITION QuantumParticle& operator=(const QuantumParticle&); }; Class QuantumParticle: private noncopyable A base class noncopyable can be written by yourself, or taken from the boost package.

Declare Destructors Virtual in Base Classes Virtual destructors do two things - makes sure, that a pointer to the base type calls the destructor of potential daughter classes. - makes the object bigger. Background info: - if you have a virtual function, an object of this type will have an additional internal pointer, that defines, which function is actually called. This pointer takes space, but makes sure, that you can overwrite the function by making the pointer pointing to a derived object function. ObjectBase virtual function [extra pointer] XYZObject function

Problems occur in this case: Note: STL containers are NOT supposed to be base classes. class SpecialString : public std::string { } SpecialString* specialstring = new Special String( Impending Doom ); std::string* string; string = specialstring; // autocast to string delete string; // string doesn't now of derived class, delete // just deletes the string part of the object // UNDEFINED BEHAVIOUR

Don't call virtual functions during construction or destruction Background info: - if you construct a derived class, the constructor of the base class is called BEFORE the constructor of the derived class - the object is in the beginning of type of the base class, before the derived class constructor is called. Therefore the call to the virtual function will act as defined in the base class, not the derived class, even when the initial call is from the derived class. This is rarely what you want (maybe sometimes it is). class BaseClass{ public: BaseClass{function();} virtual function(); } class DerivedClass{ public: DerivedClass{} function(); } NOT used in constructor, but for later calls.

- if you need information from derived class in base class construction, try using a base class constructor and call this constructor in the base class initialization list. In the initialization list, you can specify which constructor to use from the base class, but this has to be the first entry of the list. By this, you can as well make use of base classes without default constructor. B() :A(3,4), b(5) {} //possible constructor class A { public: A(int m,int n) :m(m), n(n) {} private: int m; int n; }; class B : public A { public: B() :b(5) // error : default // constructor to initialize // A is not found {} private: int b; };

Handle assignment to self in In loops things like operator= Object1 = Object1 can happen easily, e.g. if you do a[i] = a[j]; and i = j once in the loop. Resource Managing Objects, e.g. with pointers, that are responsible to delete, what they are pointing to, you can get in trouble, when first deleting and then assigning the deleting object. Therefore do things like this or test for self assignment explicitly: Object* objectorig = pointer; pointer = new Object (*rhs.pointer) // rhs being the object copied from delete objectorig; // delete the old return *this;

Copy all elements, when you are copying When writing your own copy constructor and assignment operators, be careful to - copy all data members you want to have copied, so be careful when add data members later - call the base class partners in derived classes, e.g. : BaseClass(rhs) in the initialization list BaseClass::operator=(rhs); in the body of the assignment operator. - If you need both, a copy constructor and an assignment operator, NEVER call one from the other for easier implementation. Use a 3. function!

Summary Keep in mind, which functions are created automatically and disallow them explicitly, if they don't do what you want. Make destructors virtual in base classes, if derived objects may ever be casted to the base class. Avoid virtual destructors otherwise. [Exceptions must not leave Destructors.] Don't call virtual functions during construction or destruction. Usually it doesn't what you want in derived objects. [Have assignment operators return a reference to *this.] Make sure self assignment is safe (operator=), make sure functions work, which operate on two objects of same type, if they get the same object twice. Be careful with copy constructors and assignment operators when writing them, especially in derived classes.