C++ Constructor Insanity CSE 333 Spring 2018

C++ Constructor Insanity CSE 333 Spring 2018

L11: C++ Constructor Insanity CSE333, Spring 2018 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 L11: C++ Constructor Insanity CSE333, Spring 2018 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 L11: C++ Constructor Insanity CSE333, Spring 2018 Class Definition (.h file) Point.h #ifndef _POINT_H_ #define _POINT_H_ class Point { public: Point(const int x, const int y); // int get_x() const { return x_; } // int get_y() const { return y_; }

// double Distance(const Point& p) const; void SetLocation(const int x, const int constructor inline member inline member // member y); // member function function function function private: int x_; // data member int y_; // data member }; // class Point #endif // _POINT_H_ 3 L11: C++ Constructor Insanity CSE333, Spring 2018

Class Member Definitions (.cc Point.cc file) #include #include "Point.h" 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 ps x_ and y_ variables either through the // get_x(), get_y() accessor functions or the x_, y_ private // member variables directly, since were 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 L11: C++ Constructor Insanity Class Usage (.cc file) CSE333, Spring 2018

usepoint.cc #include #include "Point.h" 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 L11: C++ Constructor Insanity CSE333, Spring 2018 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 6 L11: C++ Constructor Insanity CSE333, Spring 2018 Lecture Outline Constructors Copy Constructors Assignment

Destructors 7 L11: C++ Constructor Insanity CSE333, Spring 2018 Constructors A constructor (ctor) initializes a newlyinstantiated object A class can have multiple ctors that differ in parameters Which one is invoked depends on how the object is instantiated Point::Point(const int x, const int y); 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

8 L11: C++ Constructor Insanity CSE333, Spring 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 #include "SimplePoint.h" SimplePoint.h SimplePoint.cc ... // definitions for Distance() and SetLocation() int main(int argc, char** argv) {

SimplePoint x; // invokes synthesized default constructor SimplePoint y(x); y = x; return 0; } 9 L11: C++ Constructor Insanity CSE333, Spring 2018 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; SimplePoint y(1, 2); // compiler error: if you define any // ctors, C++ will NOT synthesize a // default constructor for you. // works: invokes the 2-int-arguments

// constructor } 10 L11: C++ Constructor Insanity CSE333, Spring 2018 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; SimplePoint a[3]; SimplePoint y(1, 2); } // invokes the default constructor

// invokes the default ctor 3 times // invokes the 2-int-arguments ctor 11 L11: C++ Constructor Insanity CSE333, Spring 2018 Initialization Lists C++ lets you optionally declare an initialization list as part of your constructor definition Initializes fields according to parameters in the list Point::Point(const The following two are int x, (nearly) const int identical: 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 L11: C++ Constructor Insanity CSE333, Spring 2018 Initialization vs. Construction class 3DPoint { First, initialization list is public: applied. // constructor with 3 int arguments 3DPoint(const int x, const int y, const int z) : y_(y), x_(x) { z_ = z; } Next, constructor body is executed. private: int x_, y_, z_; // data members }; // class 3DPoint Data members are initialized in the order they are defined, not by the initialization list ordering (!)

Data members that dont appear in the initialization list are default initialized/constructed before body is executed Initialization preferred to assignment to avoid extra steps 13 L11: C++ Constructor Insanity CSE333, Spring 2018 Lecture Outline Constructors Copy Constructors Assignment Destructors 14 L11: C++ Constructor Insanity

CSE333, Spring 2018 Copy Constructors C++ has the notion of a copy constructor (cctor) Used to createint a new object an existing Point::Point(const x, const int as y) a : copy x_(x),of y_(y) { } object // copy constructor Point::Point(const Point& copyme) { x_ = copyme.x_; y_ = copyme.y_; }

void foo() { Point x(1, 2); Point y(x); // invokes the 2-int-arguments constructor // invokes the copy constructor // could also be written as "Point y = x;" } 15 L11: C++ Constructor Insanity CSE333, Spring 2018 When Do Copies Happen? The copy constructor is invoked if: You initialize an object from Point another object of the same type: You pass a non-reference object as a parameter to a function: You return a non-reference

object from a function: x; Point y(x); Point z = y; // default ctor // copy ctor // copy ctor void foo(Point x) { ... } Point y; foo(y); // default ctor // copy ctor Point foo() { Point y; // default ctor return y; // copy ctor } 16 L11: C++ Constructor Insanity CSE333, Spring 2018

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); Point y = x; Point z = foo(); // two-ints-argument ctor // copy ctor // copy ctor? optimized? 17 L11: C++ Constructor Insanity

CSE333, Spring 2018 Synthesized Copy Constructor If you dont 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 L11: C++ Constructor Insanity CSE333, Spring 2018 Lecture Outline

Constructors Copy Constructors Assignment Destructors 19 L11: C++ Constructor Insanity CSE333, Spring 2018 Assignment != Construction = is the assignment operator Assigns values to an existing, already constructed object Point w; Point x(1, 2); Point y(x); Point z = w; y = x; // // //

// // default ctor two-ints-argument ctor copy ctor copy ctor assignment operator 20 L11: C++ Constructor Insanity CSE333, Spring 2018 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;

a = b = c; a = (b = c); (a = b) = c; // // // // default constructor works because = return *this equiv. to above (= is right-associative) "works" because = returns a non-const 21 L11: C++ Constructor Insanity CSE333, Spring 2018 Synthesized Assignment Operator If you dont 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 L11: C++ Constructor Insanity CSE333, Spring 2018 Lecture Outline Constructors Copy Constructors Assignment Destructors 23

L11: C++ Constructor Insanity CSE333, Spring 2018 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 Point::~Point() { // destructor Slogan: Resource Acquisition Is Initialization (RAII) // do any cleanup needed when a Point object goes away // (nothing to do here since we have no dynamic resources) } 24 L11: C++ Constructor Insanity

CSE333, Spring 2018 Peer Instruction Question How many times does the destructor get invoked? Assume Point with everything defined (ctor, cctor, =, dtor) Point PrintRad(Point& pt) { Point origin(0, 0); Assume no compiler optimizations 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; } A. 1 B. 2 C. 3 int main(int argc, char** argv) { Point pt(3, 4);

PrintRad(pt); return 0; } 25 L11: C++ Constructor Insanity CSE333, Spring 2018 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; ~Point() = default; Point(const Point& copyme) = default;

Point& operator=(const Point& rhs) = default; ... // // // // the the the the default default default default ctor dtor cctor "=" 26 L11: C++ Constructor Insanity CSE333, Spring 2018

Dealing with the Insanity C++ style guide tip: If possible, disable the copy constructor and assignment operator by declaring as private and not Point.h defining them 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; Point x(1, 2); Point y = w; y = x; // // // //

compiler error (no default constructor) OK! compiler error (no copy constructor) compiler error (no assignment operator) 27 L11: C++ Constructor Insanity CSE333, Spring 2018 Disabling in C++11 C++11 add new syntax to do this directly This is the better choice in C++11 code Point_2011.h 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; Point x(1, 2);

Point y = w; y = x; // // // // compiler error (no default constructor) OK! compiler error (no copy constructor) compiler error (no assignment operator) 28 L11: C++ Constructor Insanity CSE333, Spring 2018 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 sanepoint.cc Point x(1, 2); Point y(3, 4); x.CopyFrom(y); // OK // OK // OK 29 L11: C++ Constructor Insanity CSE333, Spring 2018 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 L11: C++ Constructor Insanity CSE333, Spring 2018 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

Recently Viewed Presentations

  • Steps in Designing IMC Campaign Step 1. Situational

    Steps in Designing IMC Campaign Step 1. Situational

    Arial Times New Roman Tahoma Default Design Clip Steps in Designing IMC Campaign The IMC RABOSTIC Planning Model 1. Situational Analysis 1. Situational Analysis SWOT Analysis 2. Identify Target Audience 2. Identify Target Audience 2. Identify Target Audience Target Audience...
  • 1/24/2002 doc.: IEEE 802.15-02/072r0 Project: IEEE P802.15 Working

    1/24/2002 doc.: IEEE 802.15-02/072r0 Project: IEEE P802.15 Working

    IEEE 802.11g TG Liaison Report for January 2002 Jeyhan Karaoguz TGg Passed the Following Motions on Recommended use of RTS/CTS exchange mechanism to avoid collisions between legacy 802.11b transmissions and 802.11g OFDM transmissions in a BSS network Inclusion of a...
  • www.halliburton.com

    www.halliburton.com

    Whether you're in the field, lab, yard or refinery, going home alive and well can come down to instantly recognizing — and obeying — a workplace phrase, color or symbol. These signs are there to give warning. Your job is...
  • Say &quot;NO&quot; to AMI

    Say "NO" to AMI

    Rebuttal - General. Technical. Only wireless options are being considered. What about Fiber Optics, Phone line, Power line communication options? Transmission can be as high as 190,000 bursts per day
  • Auxiliary: (adj.) giving assistance or support; (n) a

    Auxiliary: (adj.) giving assistance or support; (n) a

    Children sometimes feign illness to avoid going to school. Synonyms: fake, sham, affect, simulate. Flair: (n.) a natural quality, talent, or skill; a distinctive style. An opera singer needs a flair for the dramatic as well as a good voice.
  • Welcome to 8th Grade Read180! - pdsd.org

    Welcome to 8th Grade Read180! - pdsd.org

    About the Book* August Pullman was born with a facial deformity that, up until now, has prevented him from going to a regular school. Starting 5th grade at Beecher Prep, he wants nothing more than to be treated as an...
  • KS4 Food (D&amp;T) - Crofton Academy

    KS4 Food (D&T) - Crofton Academy

    Raspberry coulis is an example of an uncooked single fruit sauce - fresh raspberries are pressed through a sieve to make a seedless sauce. Red pepper purée is an example of a cooked mixed vegetable sauce - peppers, onion and...
  • The Scottish Wars of Independence 1286-1328

    The Scottish Wars of Independence 1286-1328

    Treaty of Birgham careful to make Scotland independent. BUT asking Edward I of England to choose Scots king = dangerous (it's what an overlord would do) So why? Margaret died 1290. Birgham = not usable. Civil war in Scotland =...