C++ Constructor Insanity CSE 333 Winter 2019

Slides:



Advertisements
Similar presentations
Object-Oriented programming in C++ Classes as units of encapsulation Information Hiding Inheritance polymorphism and dynamic dispatching Storage management.
Advertisements

Constructor. 2 constructor The main use of constructors is to initialize objects. A constructor is a special member function, whose name is same as class.
F UNCTION O VERLOADING Chapter 5 Department of CSE, BUET 1.
Classes: A Deeper Look Systems Programming.
CSE 332: C++ Classes From Procedural to Object-oriented Programming Procedural programming –Functions have been the main focus so far Function parameters.
1 Classes and Objects. 2 Outlines Class Definitions and Objects Member Functions Data Members –Get and Set functions –Constructors.
Review of C++ Programming Part II Sheng-Fang Huang.
CSE 333 – SECTION 4. Overview Pointers vs. references Const Classes, constructors, new, delete, etc. More operator overloading.
The Rest of the Story.  Constructors  Compiler-generated  The Initializer List  Copy Constructors  Single-arg (conversion ctors)  The Assignment.
CS212: Object Oriented Analysis and Design Lecture 6: Friends, Constructor and destructors.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look, Part 2.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 13: Introduction to Classes.
Chapter 13. Procedural programming vs OOP  Procedural programming focuses on accomplishing tasks (“verbs” are important).  Object-oriented programming.
ICOM 4035 – Data Structures Dr. Manuel Rodríguez Martínez Electrical and Computer Engineering Department Lecture 4 – August 30, 2001.
Object Oriented Programming Elhanan Borenstein Lecture #3 copyrights © Elhanan Borenstein.
Object-Based Programming Mostly Review. Objects Review what is object? class? member variables? member functions? public members? private members? friend.
Object Management. Constructors –Compiler-generated –The Initializer List –Copy Constructors –Single-arg (conversion ctors) The Assignment Operator.
CS-1030 Dr. Mark L. Hornick 1 Basic C++ State the difference between a function/class declaration and a function/class definition. Explain the purpose.
1 Classes II Chapter 7 2 Introduction Continued study of –classes –data abstraction Prepare for operator overloading in next chapter Work with strings.
LECTURE LECTURE 11 Constructors and destructors Copy constructor Textbook: p , 183.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 13: Introduction to Classes.
Learners Support Publications Constructors and Destructors.
Defining Data Types in C++ Part 2: classes. Quick review of OOP Object: combination of: –data structures (describe object attributes) –functions (describe.
C++ Features Function Overloading Default Functions arguments Thinking about objects – relationship to classes Types of member functions Constructor and.
CSE 332: C++ Exceptions Motivation for C++ Exceptions Void Number:: operator/= (const double denom) { if (denom == 0.0) { // what to do here? } m_value.
Constructors and Destructors
Pointer to an Object Can define a pointer to an object:
Procedural and Object-Oriented Programming
Learning Objectives Pointers as dada members
Chapter 6 CS 3370 – C++ Functions.
Friend Class Friend Class A friend class can access private and protected members of other class in which it is declared as friend. It is sometimes useful.
Motivation and Overview
Introduction to Classes
Constructor & Destructor
System Programming Practical Session 8 C++ classes.
Class: Special Topics Copy Constructors Static members Friends this
Memberwise Assignment / Initialization
The dirty secrets of objects
C++ Constructor Insanity CSE 333 Spring 2018
Introduction to Classes
C++ Templates CSE 333 Spring 2018
C++ Encapsulation, Heap CSE 333 Spring 2018
Constructors and Destructors
References, const and classes
References Revisited CSE 333 Spring 2018
References Revisited CSE 333 Summer 2018
CS148 Introduction to Programming II
C++ Inheritance II, Casting CSE 333 Summer 2018
C++ Templates CSE 333 Summer 2018
C++ Class Details, Heap CSE 333 Autumn 2018
C++ Constructor Insanity CSE 333 Summer 2018
C++ Class Details, Heap CSE 333 Summer 2018
Java Programming Language
C++ Templates CSE 333 Autumn 2018
Recitation Course 0603 Speaker: Liu Yu-Jiun.
C++ Constructor Insanity CSE 333 Autumn 2018
C++ Inheritance II, Casting CSE 333 Winter 2019
C++ Class Details, Heap CSE 333 Winter 2019
Client-side Networking CSE 333 Winter 2019
References Revisited CSE 333 Autumn 2018
References Revisited CSE 333 Winter 2019
C++ Inheritance I CSE 333 Winter 2019
Low-Level I/O – the POSIX Layer CSE 333 Winter 2019
C++ Templates CSE 333 Winter 2019
ENERGY 211 / CME 211 Lecture 17 October 29, 2008.
C++ Class Details, Heap CSE 333 Spring 2019
C++ Constructor Insanity CSE 333 Spring 2019
SPL – PS3 C++ Classes.
Presentation transcript:

C++ Constructor Insanity CSE 333 Winter 2019 Instructor: Hal Perkins Teaching Assistants: Alexey Beall Renshu Gu Harshita Neti David Porter Forrest Timour Soumya Vasisht Yifan Xu Sujie Zhou

Administrivia Next exercise released today, due Monday morning Write a substantive class in C++ (but no dynamic allocation – yet) And include a Makefile! Look at Complex.h/Complex.cc for ideas Feel free to adapt the Makefile examples from section Homework 2 due next Thursday (2/7) How’s it going? Any surprises, questions, problems?

Lecture Outline Constructors Copy Constructors Assignment Destructors An extended example

Constructors A constructor (ctor) initializes a newly-instantiated object A class can have multiple constructors that differ in parameters Which one is invoked depends on how the object is instantiated Written with the class name as the method name: 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 Point(const int x, const int y);

Synthesized Default Constructor 4/18/2018 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() int main(int argc, char** argv) { SimplePoint x; // invokes synthesized default constructor return 0; } const after member function names: guaranteed not to change _this_ SimplePoint.cc

Synthesized Default Constructor If you define any constructors, C++ assumes you have defined all the ones you intend to be available and will not add any others #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

Multiple Constructors (overloading) 4/18/2018 Multiple Constructors (overloading) #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

Initialization Lists C++ lets you optionally declare an initialization list as part of a 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; }

Initialization vs. Construction Data members in initializer list are initialized in the order they are defined in the class, 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 of default initialization (construction) followed by assignment (and no, real code should never mix the two styles this way ) class Point3D { public: // constructor with 3 int arguments Point3D(const int x, const int y, const int z) : y_(y), x_(x) { z_ = z; } private: int x_, y_, z_; // data members }; // class Point3D First, initialization list is applied. Next, constructor body is executed.

Lecture Outline Constructors Copy Constructors Assignment Destructors An extended example

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;" Initializer lists can also be used in copy constructors (preferred)

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

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; // default ctor return y; // copy ctor? optimized? } Point x(1, 2); // two-ints-argument ctor Point y = x; // copy ctor Point z = foo(); // copy ctor? optimized?

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 ... return 0; }

Lecture Outline Constructors Copy Constructors Assignment Destructors An extended example

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

Overloading the “=” Operator You can choose to define 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 op= 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

Synthesized Assignment Operator If you don’t define 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; }

Lecture Outline Constructors Copy Constructors Assignment Destructors An extended example

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) }

Lecture Outline Constructors Copy Constructors Assignment Destructors An extended example

Complex Example Walkthrough See: Complex.h Complex.cc testcomplex.cc (Some details like friend functions and namespaces are explained in more detail next lecture, but ideas should make sense from looking at the code and explanations in C++ Primer)

Extra Exercise #1 Modify your Point3D 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 (See details about CopyFrom() in next lecture)

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