Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

C++ Constructors and Initialization: A Comprehensive Guide, Study notes of Construction

An in-depth exploration of constructors, initialization lists, copy constructors, assignment operators, and destructors in C++. Students will learn how to initialize objects, create copies, assign values, and manage resources through examples and explanations. The document also includes exercises and a complex example for further practice.

Typology: Study notes

2021/2022

Uploaded on 09/12/2022

marylen
marylen 🇺🇸

4.6

(26)

250 documents

1 / 24

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
CSE333, Summer 2018L11: C++ Constructor Insanity
C++ Constructor Insanity
CSE 333 Summer 2018
Instructor: Hal Perkins
Teaching Assistants:
Renshu Gu William Kim Soumya Vasisht
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18

Partial preview of the text

Download C++ Constructors and Initialization: A Comprehensive Guide and more Study notes Construction in PDF only on Docsity!

C++ Constructor Insanity

CSE 333 Summer 2018

Instructor: Hal Perkins

Teaching Assistants:

Renshu Gu William Kim Soumya Vasisht

Administrivia v Exercise 10 released today, due Monday § Write a substantive class in C++! (but no dynamic allocation – yet) § Refer to Complex.h/Complex.cc v Homework 2 due next Thursday (7/19) § 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

Constructors v 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 v 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 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; }

SimplePoint.cc

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 }

Initialization Lists v 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: // 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; } Point::Point(const int x, const int y) { x_ = x; y_ = y; std::cout << "Point constructed: (" << x_ << ","; std::cout << y_<< ")" << std::endl; }

Lecture Outline v Constructors v Copy Constructors v Assignment v Destructors v An extended example

Copy Constructors v 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)

Compiler Optimization v 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 v 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; }

Assignment != Construction v “=” 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 v 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 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

Lecture Outline v Constructors v Copy Constructors v Assignment v Destructors v An extended example

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