C++ Constructor Insanity

Similar documents
C++ Constructor Insanity

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

CSE 333. Lecture 10 - references, const, classes. Hal Perkins Paul G. Allen School of Computer Science & Engineering University of Washington

C++ Class Details, Heap

C++ Inheritance II, Casting

C++ Inheritance I. CSE 333 Spring Instructor: Justin Hsia

Server-side Programming

C++ Templates. CSE 333 Autumn 2018

Concurrency and Threads

Memory and Arrays. CSE 333 Spring Instructor: Justin Hsia

Intermediate Programming, Spring 2017*

IP Addresses, DNS. CSE 333 Spring Instructor: Justin Hsia

CS11 Introduction to C++ Fall Lecture 1

CS 11 C++ track: lecture 1

CS11 Intro C++ Spring 2018 Lecture 1

pointers & references

CPSC 427: Object-Oriented Programming

CSE 333 Lecture smart pointers

the gamedesigninitiative at cornell university Lecture 7 C++ Overview

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

CSE 333 Lecture smart pointers

CS 251 INTERMEDIATE SOFTWARE DESIGN SPRING C ++ Basics Review part 2 Auto pointer, templates, STL algorithms

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

1/29/2011 AUTO POINTER (AUTO_PTR) INTERMEDIATE SOFTWARE DESIGN SPRING delete ptr might not happen memory leak!

CSE 374 Programming Concepts & Tools. Hal Perkins Fall 2015 Lecture 19 Introduction to C++

Classes in C++98 and C++11

Announcements. CSCI 334: Principles of Programming Languages. Lecture 18: C/C++ Announcements. Announcements. Instructor: Dan Barowy

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

12/2/2009. The plan. References. References vs. pointers. Reference parameters. const and references. HW7 is out; new PM due date Finish last lecture

CSE 333 Lecture smart pointers

CS 162 Intro to CS II. Structs vs. Classes

Lecture 3 ADT and C++ Classes (II)

CS11 Intro C++ Spring 2018 Lecture 3

CS93SI Handout 04 Spring 2006 Apr Review Answers

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

Programmazione. Prof. Marco Bertini

CSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010

C++ Smart Pointers. CSE 333 Autumn 2018

Ch 2 ADTs and C++ Classes

SFU CMPT Topic: Classes

PIC 10A Objects/Classes

Homework 4. Any questions?

CIS 190: C/C++ Programming. Classes in C++

CSE 303: Concepts and Tools for Software Development

COMP 2355 Introduction to Systems Programming

Lecture 15a Persistent Memory & Shared Pointers

Abstract Data Types (ADT) and C++ Classes

Program template-smart-pointers-again.cc

2 ADT Programming User-defined abstract data types

Scope. Scope is such an important thing that we ll review what we know about scope now:

CPSC 427: Object-Oriented Programming

CE221 Programming in C++ Part 1 Introduction

Common Misunderstandings from Exam 1 Material

Starting Savitch Chapter 10. A class is a data type whose variables are objects. Some pre-defined classes in C++ include int,

EL2310 Scientific Programming

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

Intermediate Programming, Spring 2017*

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

Lecture 7. Log into Linux New documents posted to course webpage

CSE 333 Lecture 9 - intro to C++

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

COMP6771 Advanced C++ Programming

Function Declarations. Reference and Pointer Pitfalls. Overloaded Functions. Default Arguments

C++ Inheritance II, Casting

Lecture 14: more class, C++ streams

CS24 Week 3 Lecture 1

System Programming. Practical Session 9. C++ classes

The Heap and Structs. CSE 333 Spring Instructor: Justin Hsia

The University of Nottingham

CSE 12 Spring 2016 Week One, Lecture Two

C++ Mini-Course. Part 1: Mechanics Part 2: Basics Part 3: References Part 4: Const Part 5: Inheritance Part 6: Libraries Part 7: Conclusion. C Rulez!

Short Notes of CS201

1.124 Quiz 1 Thursday October 8, 1998 Time: 1 hour 15 minutes Answer all questions. All questions carry equal marks.

QUIZ Friends class Y;

CS201 - Introduction to Programming Glossary By

CSE 333. Lecture 9 - intro to C++ Hal Perkins Department of Computer Science & Engineering University of Washington

Final C Details, Build Tools

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

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

CS11 Introduction to C++ Fall Lecture 3

Implementing an ADT with a Class

C++ Namespaces, Exceptions

C++ Mini-Course. Part 1: Mechanics Part 2: Basics Part 3: References Part 4: Const Part 5: Inheritance Part 6: Libraries Part 7: Conclusion. C Rulez!

CS3157: Advanced Programming. Outline

1.124 Quiz 1 Thursday October 8, 1998 Time: 1 hour 15 minutes Answer all questions. All questions carry equal marks.

G52CPP C++ Programming Lecture 9

Assumptions. History

Where do we stand on inheritance?

Review: C Strings. A string in C is just an array of characters. Lecture #4 C Strings, Arrays, & Malloc

Unified Modeling Language a case study

Computer Programming with C++ (21)

CS 376b Computer Vision

G52CPP C++ Programming Lecture 7. Dr Jason Atkin

Lab 1: First Steps in C++ - Eclipse

Programming C++ Lecture 3. Howest, Fall 2012 Instructor: Dr. Jennifer B. Sartor

Homework 5. Yuji Shimojo CMSC 330. Instructor: Prof. Reginald Y. Haseltine

MARKING KEY The University of British Columbia MARKING KEY Computer Science 260 Midterm #1 Examination 12:30 noon, Tuesday, February 14, 2012

G52CPP C++ Programming Lecture 13

EL2310 Scientific Programming

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

Transcription:

C++ Constructor Insanity CSE 333 Spring 2018 Instructor: Justin Hsia Teaching Assistants: Danny Allen Dennis Shao Eddie Huang Kevin Bi Jack Xu Matthew Neldam Michael Poulain Renshu Gu Robby Marver Waylon Huang Wei Lin

Administrivia Exercise 9 released today, due Friday First submitted Makefile! Homework 2 due next Thursday (4/26) File system crawler, indexer, and search engine Note: libhw1.a (yours or ours) and the.h files from hw1 need to be in right directory (~yourgit/hw1/) Note: use Ctrl-D to exit searchshell, test on directory of small self-made files 2

Class Definition (.h file) #ifndef _POINT_H_ #define _POINT_H_ Point.h class Point { public: Point(const int x, const int y); // constructor int get_x() const { return x_; // inline member function int get_y() const { return y_; // inline member function double Distance(const Point& p) const; // member function void SetLocation(const int x, const int y); // member function private: int x_; // data member int y_; // data member ; // class Point #endif // _POINT_H_ 3

Class Member Definitions (.cc file) #include <cmath> #include "Point.h" Point.cc Point::Point(const int x, const int y) { x_ = x; this->y_ = y; // "this->" is optional unless name conflicts double Point::Distance(const Point& p) const { // We can access p s x_ and y_ variables either through the // get_x(), get_y() accessor functions or the x_, y_ private // member variables directly, since we re in a member // function of the same class. double distance = (x_ - p.get_x()) * (x_ - p.get_x()); distance += (y_ - p.y_) * (y_ - p.y_); return sqrt(distance); void Point::SetLocation(const int x, const int y) { x_ = x; y_ = y; 4

Class Usage (.cc file) #include <iostream> #include "Point.h" usepoint.cc using namespace std; int main(int argc, char** argv) { Point p1(1, 2); // allocate a new Point on the Stack Point p2(4, 6); // allocate a new Point on the Stack cout << "p1 is: (" << p1.get_x() << ", "; cout << p1.get_y() << ")" << endl; cout << "p2 is: (" << p2.get_x() << ", "; cout << p2.get_y() << ")" << endl; cout << "dist : " << p1.distance(p2) << endl; return 0; 5

struct vs. class In C, a struct can only contain data fields No methods and all fields are always accessible In C++, struct and class are (nearly) the same! Both can have methods and member visibility (public/private/protected) Minor difference: members are default public in a struct and default private in a class Common style convention: Use struct for simple bundles of data Use class for abstractions with data + functions 6

Lecture Outline Constructors Copy Constructors Assignment Destructors 7

Constructors A constructor (ctor) initializes a newly-instantiated object A class can have multiple ctors that differ in parameters Which one is invoked depends on how the object is instantiated Written with the class name as the method name: Point::Point(const int x, const int y); C++ will automatically create a synthesized default constructor if you have no user-defined constructors Takes no arguments and calls the default ctor on all non- plain old data (non-pod) member variables Synthesized default ctor will fail if you have non-initialized const or reference data members 8

Synthesized Default Constructor class SimplePoint { public: // no constructors declared! int get_x() const { return x_; // inline member function int get_y() const { return y_; // inline member function double Distance(const SimplePoint& p) const; void SetLocation(const int x, const int y); private: int x_; // data member int y_; // data member ; // class SimplePoint SimplePoint.h #include "SimplePoint.h"... // definitions for Distance() and SetLocation() SimplePoint.cc int main(int argc, char** argv) { SimplePoint x; // invokes synthesized default constructor SimplePoint y(x); y = x; return 0; 9

Synthesized Default Constructor #include "SimplePoint.h" // defining a constructor with two arguments SimplePoint::SimplePoint(const int x, const int y) { x_ = x; y_ = y; void foo() { SimplePoint x; // compiler error: if you define any // ctors, C++ will NOT synthesize a // default constructor for you. SimplePoint y(1, 2); // works: invokes the 2-int-arguments // constructor 10

Multiple Constructors #include "SimplePoint.h" // default constructor SimplePoint::SimplePoint() { x_ = 0; y_ = 0; // constructor with two arguments SimplePoint::SimplePoint(const int x, const int y) { x_ = x; y_ = y; void foo() { SimplePoint x; // invokes the default constructor SimplePoint a[3]; // invokes the default ctor 3 times SimplePoint y(1, 2); // invokes the 2-int-arguments ctor 11

Initialization Lists C++ lets you optionally declare an initialization list as part of your constructor definition Initializes fields according to parameters in the list The following two are (nearly) identical: Point::Point(const int x, const int y) { x_ = x; y_ = y; std::cout << "Point constructed: (" << x_ << ","; std::cout << y_<< ")" << std::endl; // constructor with an initialization list Point::Point(const int x, const int y) : x_(x), y_(y) { std::cout << "Point constructed: (" << x_ << ","; std::cout << y_<< ")" << std::endl; 12

Initialization vs. Construction class 3DPoint { public: // constructor with 3 int arguments 3DPoint(const int x, const int y, const int z) : y_(y), x_(x) { z_ = z; private: int x_, y_, z_; // data members ; // class 3DPoint Next, constructor body is executed. First, initialization list is applied. Data members are initialized in the order they are defined, not by the initialization list ordering (!) Data members that don t appear in the initialization list are default initialized/constructed before body is executed Initialization preferred to assignment to avoid extra steps 13

Lecture Outline Constructors Copy Constructors Assignment Destructors 14

Copy Constructors C++ has the notion of a copy constructor (cctor) Used to create a new object as a copy of an existing object Point::Point(const int x, const int y) : x_(x), y_(y) { // copy constructor Point::Point(const Point& copyme) { x_ = copyme.x_; y_ = copyme.y_; void foo() { Point x(1, 2); // invokes the 2-int-arguments constructor Point y(x); // invokes the copy constructor // could also be written as "Point y = x;" 15

When Do Copies Happen? The copy constructor is invoked if: You initialize an object from another object of the same type: Point x; // default ctor Point y(x); // copy ctor Point z = y; // copy ctor You pass a non-reference object as a parameter to a function: void foo(point x) {... Point y; // default ctor foo(y); // copy ctor You return a non-reference object from a function: Point foo() { Point y; // default ctor return y; // copy ctor 16

Compiler Optimization The compiler sometimes uses a return by value optimization or move semantics to eliminate unnecessary copies Sometimes you might not see a constructor get invoked when you might expect it Point foo() { Point y; return y; // default ctor // copy ctor? optimized? Point x(1, 2); // two-ints-argument ctor Point y = x; // copy ctor Point z = foo(); // copy ctor? optimized? 17

Synthesized Copy Constructor If you don t define your own copy constructor, C++ will synthesize one for you It will do a shallow copy of all of the fields (i.e. member variables) of your class Sometimes the right thing; sometimes the wrong thing #include "SimplePoint.h"... // definitions for Distance() and SetLocation() int main(int argc, char** argv) { SimplePoint x; SimplePoint y(x); // invokes synthesized copy constructor y = x; return 0; 18

Lecture Outline Constructors Copy Constructors Assignment Destructors 19

Assignment!= Construction = is the assignment operator Assigns values to an existing, already constructed object Point w; // default ctor Point x(1, 2); // two-ints-argument ctor Point y(x); // copy ctor Point z = w; // copy ctor y = x; // assignment operator 20

Overloading the = Operator You can choose to overload the = operator But there are some rules you should follow: Point& Point::operator=(const Point& rhs) { if (this!= &rhs) { // (1) always check against this x_ = rhs.x_; y_ = rhs.y_; return *this; // (2) always return *this from = Point a; // default constructor a = b = c; // works because = return *this a = (b = c); // equiv. to above (= is right-associative) (a = b) = c; // "works" because = returns a non-const 21

Synthesized Assignment Operator If you don t overload the assignment operator, C++ will synthesize one for you It will do a shallow copy of all of the fields (i.e. member variables) of your class Sometimes the right thing; sometimes the wrong thing #include "SimplePoint.h"... // definitions for Distance() and SetLocation() int main(int argc, char** argv) { SimplePoint x; SimplePoint y(x); y = x; // invokes synthesized assignment operator return 0; 22

Lecture Outline Constructors Copy Constructors Assignment Destructors 23

Destructors C++ has the notion of a destructor (dtor) Invoked automatically when a class instance is deleted, goes out of scope, etc. (even via exceptions or other causes!) Place to put your cleanup code free any dynamic storage or other resources owned by the object Standard C++ idiom for managing dynamic resources Slogan: Resource Acquisition Is Initialization (RAII) Point::~Point() { // destructor // do any cleanup needed when a Point object goes away // (nothing to do here since we have no dynamic resources) 24

Peer Instruction Question How many times does the destructor get invoked? Assume Point with everything defined (ctor, cctor, =, dtor) Assume no compiler optimizations A. 1 B. 2 C. 3 D. 4 E. We re lost Point PrintRad(Point& pt) { Point origin(0, 0); double r = origin.distance(pt); double theta = atan2(pt.get_y(), pt.get_x()); cout << "r = " << r << endl; cout << "theta = " << theta << " rad" << endl; return pt; int main(int argc, char** argv) { Point pt(3, 4); PrintRad(pt); return 0; 25

Rule of Three If you define any of: 1) Destructor 2) Copy Constructor 3) Assignment (operator=) Then you should normally define all three Can explicitly ask for default synthesized versions (C++11): class Point { public: Point() = default; // the default ctor ~Point() = default; // the default dtor Point(const Point& copyme) = default; // the default cctor Point& operator=(const Point& rhs) = default; // the default "="... 26

Dealing with the Insanity C++ style guide tip: If possible, disable the copy constructor and assignment operator by declaring as private and not defining them Point.h class Point { public: Point(const int x, const int y) : x_(x), y_(y) { // ctor... private: Point(const Point& copyme); // disable cctor (no def.) Point& operator=(const Point& rhs); // disable "=" (no def.)... ; // class Point Point w; // compiler error (no default constructor) Point x(1, 2); // OK! Point y = w; // compiler error (no copy constructor) y = x; // compiler error (no assignment operator) 27

Disabling in C++11 C++11 add new syntax to do this directly This is the better choice in C++11 code class Point { public: Point(const int x, const int y) : x_(x), y_(y) { // ctor... Point(const Point& copyme) = delete; // declare cctor and "=" as Point& operator=(const Point& rhs) = delete; // as deleted (C++11) private:... ; // class Point Point w; // compiler error (no default constructor) Point x(1, 2); // OK! Point y = w; // compiler error (no copy constructor) y = x; // compiler error (no assignment operator) Point_2011.h 28

CopyFrom C++11 style guide tip If you disable them, then you should instead probably have an explicit CopyFrom function Point.h class Point { public: Point(const int x, const int y) : x_(x), y_(y) { // ctor void CopyFrom(const Point& copy_from_me);... Point(Point& copyme); // disable cctor (no def.) Point& operator=(point& rhs); // disable "=" (no def.) private:... ; // class Point Point x(1, 2); // OK Point y(3, 4); // OK x.copyfrom(y); // OK sanepoint.cc 29

Extra Exercise #1 Modify your 3DPoint class from Lec 10 Extra #1 Disable the copy constructor and assignment operator Attempt to use copy & assignment in code and see what error the compiler generates Write a CopyFrom() member function and try using it instead 30

Extra Exercise #2 Write a C++ class that: Is given the name of a file as a constructor argument Has a GetNextWord() method that returns the next whitespace- or newline-separated word from the file as a copy of a string object, or an empty string once you hit EOF Has a destructor that cleans up anything that needs cleaning up 31