Comp151. Construction & Initialization

Similar documents
Short Notes of CS201

CS201 - Introduction to Programming Glossary By

CS201 Some Important Definitions

COMP 2355 Introduction to Systems Programming

THE NAME OF THE CONSTRUCTOR AND DESTRUCTOR(HAVING (~) BEFORE ITS NAME) FUNCTION MUST BE SAME AS THE NAME OF THE CLASS IN WHICH THEY ARE DECLARED.

INITIALISING POINTER VARIABLES; DYNAMIC VARIABLES; OPERATIONS ON POINTERS

Ch. 12: Operator Overloading

Financial computing with C++

CPSC 427: Object-Oriented Programming

Ch. 11: References & the Copy-Constructor. - continued -

Lecture 14. No in-class files today. Homework 7 (due on Wednesday) and Project 3 (due in 10 days) posted. Questions?

Pointers. Developed By Ms. K.M.Sanghavi

CPSC 427: Object-Oriented Programming

Object-Oriented Programming for Scientific Computing

C++ for Java Programmers

C++ Addendum: Inheritance of Special Member Functions. Constructors Destructor Construction and Destruction Order Assignment Operator

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

CSC 1600 Memory Layout for Unix Processes"

Lecture 15a Persistent Memory & Shared Pointers

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

1. Describe History of C++? 2. What is Dev. C++? 3. Why Use Dev. C++ instead of C++ DOS IDE?

Object-Oriented Programming

nptr = new int; // assigns valid address_of_int value to nptr std::cin >> n; // assigns valid int value to n

A brief introduction to C++

Chapter 10 Pointers and Dynamic Arrays. GEDB030 Computer Programming for Engineers Fall 2017 Euiseong Seo

Classes and Objects. Class scope: - private members are only accessible by the class methods.

Pointers II. Class 31

Constants, References

CA31-1K DIS. Pointers. TA: You Lu

Fast Introduction to Object Oriented Programming and C++


DYNAMIC ARRAYS; FUNCTIONS & POINTERS; SHALLOW VS DEEP COPY

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?

Vector and Free Store (Vectors and Arrays)

Call The Project Dynamic-Memory

Variables, Memory and Pointers

Object Oriented Software Design II

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

04-19 Discussion Notes

Chapter 10. Pointers and Dynamic Arrays. Copyright 2016 Pearson, Inc. All rights reserved.

CSE 303: Concepts and Tools for Software Development

G52CPP C++ Programming Lecture 13

Quiz Start Time: 09:34 PM Time Left 82 sec(s)

CSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010

CS201 Latest Solved MCQs

2 ADT Programming User-defined abstract data types

Chapter 6: User-Defined Functions. Objectives (cont d.) Objectives. Introduction. Predefined Functions 12/2/2016

Pointers, Dynamic Data, and Reference Types

Introducing C++ to Java Programmers

Pointers and Memory 1

Assignment of Structs

Homework 4. Any questions?

Vector and Free Store (Pointers and Memory Allocation)

Initializing and Finalizing Objects

Cpt S 122 Data Structures. Course Review Midterm Exam # 2

6. Pointers, Structs, and Arrays. 1. Juli 2011

Object-Oriented Programming, Iouliia Skliarova

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

More About Classes. Gaddis Ch. 14, CS 2308 :: Fall 2015 Molly O'Neil

Object-Oriented Principles and Practice / C++

CS 101: Computer Programming and Utilization

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

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

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

04-17 Discussion Notes

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

Memory Leak. C++: Memory Problems. Memory Leak. Memory Leak. Pointer Ownership. Memory Leak

QUIZ Friends class Y;

Programming, numerics and optimization

Object-Oriented Programming, Iouliia Skliarova

Lecture 6 Dynamic Classes and the Law of the Big Three. Instructor: George Wolberg Department of Computer Science City College of New York

CSE 333 Midterm Exam July 24, Name UW ID#

Come and join us at WebLyceum

Chapter 17 vector and Free Store

Memory and Addresses. Pointers in C. Memory is just a sequence of byte-sized storage devices.

Classes: Member functions // classes example #include <iostream> using namespace std; Objects : Reminder. Member functions: Methods.

2 2

Discussion 1E. Jie(Jay) Wang Week 10 Dec.2

CSC1322 Object-Oriented Programming Concepts

Constructors & Destructors

Common Misunderstandings from Exam 1 Material

CSE 333 Midterm Exam 5/10/13

PIC 10B Lecture 1 Winter 2014 Homework Assignment #3

6. Pointers, Structs, and Arrays. March 14 & 15, 2011

Announcements. Lecture 04b Header Classes. Review (again) Comments on PA1 & PA2. Warning about Arrays. Arrays 9/15/17

C++ Crash Kurs. Polymorphism. Dr. Dennis Pfisterer Institut für Telematik, Universität zu Lübeck

Object-Oriented Principles and Practice / C++

内存管理. Memory management

Lecture 2, September 4

Lab#5 Due Wednesday, February 25, at the start of class. Purpose: To develop familiarity with C++ pointer variables

CE221 Programming in C++ Part 2 References and Pointers, Arrays and Strings

gcc hello.c a.out Hello, world gcc -o hello hello.c hello Hello, world

CS24 Week 3 Lecture 1

Announcements. Lecture 05a Header Classes. Midterm Format. Midterm Questions. More Midterm Stuff 9/19/17. Memory Management Strategy #0 (Review)

CPSC 427: Object-Oriented Programming

CS201- Introduction to Programming Current Quizzes

Separate Compilation Model

Written by John Bell for CS 342, Spring 2018

Constructors for classes

Chapter 17 vector and Free Store

Transcription:

Comp151 Construction & Initialization

Class Object Initialization [comp151] 1 If ALL data members of the class are public, they can be initialized when they are created as follows: class Word int frequency; char str; int main() Word movie = 1, "Titantic"

Class Object Initialization.. [comp151] 2 What happens if some of data members are private? class Word char str; int frequency; int main() Word movie = 1, "Titantic" Error: a.cc:8: movie must be initialized by constructor, not by...

Constructor: Introduction [comp151] 3 blank CD default constructor MD to CD conversion constructor pirated CD copy constructor All4One s "I Swear" Eric Clapton s "Tears in Heaven" Beethoven s Symphony No. 5 Phantom of the Opera other constructors

C++ Constructors [comp151] 4 C++ supports a more general mechanism for user-defined initialization of class objects through constructor member functions. Word movie; Word director = James Cameron ; Word movie = Word( Titanic ); Word *p = new Word( action, 1); Syntactically, a constructor of a class is a special member function having the same name as the class. A constructor is called whenever an object of a class is created. A constructor must NOT specify a return type or explicitly returns a value NOT even the void type.

Default Constructor [comp151] 5 class Word int frequency; char str; Word() frequncey = 0; str = 0; int main(int argc, char argv) Word movie; A default constructor is a constructor that is called with NO argument: X::X() for class X. It is used to initialize an object with user-defined default values.

Compiler Generates a Default Constructor [comp151] 6 class Word int frequency; char str; int main(int argc, char argv) Word movie; If there are NO user-defined constructors, the compiler will generate the default constructor: X::X() for class X for you. Word() only creates a record with space for an int quantity and a char* quantity. Their initial values CANNOT be trusted.

Default Constructor: Bug [comp151] 7 BUT: Only when there are NO user-defined constructors, will the compiler automatically supply the default constructor. class Word... Word(const char s, int k = 0); int main() Word movie; Word song("titanic"); // which constructor? // which constructor? a.cc:16: no matching function for call to Word::Word () a.cc:12: candidates are: Word::Word(const Word &) a.cc:7: Word::Word(const char *, int)

Type Conversion Constructor [comp151] 8 class Word... Word(const char s) frequency = 1; str = new char [strlen(s)+1]; strcpy(str, s); int main() Word p = new Word("action"); Word movie("titanic"); Word director = "James Cameron"; A constructor accepting a single argument specifies a conversion from its argument type to the type of its class: Word(const char*) converts from type const char* to type Word.

Type Conversion Constructor.. [comp151] 9 class Word... Word(const char s, int k = 1) frequency = k; str = new char [strlen(s)+1]; strcpy(str, s); int main() Word p = new Word("action"); Word movie("titanic"); Word director = "James Cameron"; Notice that if all but ONE argument of a constructor have default values, it is still considered a conversion constructor.

Copy Constructor: Example [comp151] 10 class Word Word(const char s, int k = 1); Word(const Word& w) frequency = w.frequency; str = new char [strlen(w.str)+1]; strcpy(str, w.str); int main() Word movie("titanic"); Word song(movie); // which constructor? // which constructor?

Copy Constructor [comp151] 11 Copy constructor has only ONE argument of the same class. Syntax: X(const X&) for class X. It is called upon: parameter passing to a function (call-by-value) initialization assignment: Word x( Brian ); Word y = x; value returned by a function: Word Word::to upper case() Word x( this); for (char p = x.str; p!= \0 ; p++) p += A - a ; return x;

Default Copy Constructor [comp151] 12 For a class X, if no copy constructor is defined by the user, the compiler will automatically supply: X(const X&). class Word Word(const char s, int k = 0); int main() Word movie("titanic"); Word song(movie); Word song = movie; // which constructor? // which constructor? // which constructor? memberwise copy song.frequency = movie.frequency; song.str = movie.str;

Constructor: Quiz [comp151] 13 Quiz: How are class initializations done in the following statements: Word vowel( a ); Word article = vowel; Word movie = Titanic ;

Function Overloading [comp151] 14 Overloading allows programmers to use the same name for functions that do similar things but with different input arguments. Constructors are often overloaded. class Word int frequency; char str; Word() Word(const char s, int k = 1); Word(const Word& w);

Function Overloading.. [comp151] 15 In general, function names can be overloaded in C++. class Word... set(int k) frequency = k; set(const char s) str = new char [strlen(s)+1]; strcpy(str, s); set(char c) str = new char [2]; str[0] = c; str[1] = \0 ; set() cout str; // Bad overloading! Obscure understanding Actually, operators are often overloaded. e.g. What is the type of the operands for +?

Default Arguments [comp151] 16 If a function shows some default behaviors most of the time, and some exceptional behaviors only once awhile, specifying default arguments is a better option than using overloading. class Word... Word(const char s, int k = 1) frequency = k; str = new char [strlen(s)+1]; strcpy(str, s); int main() Word movie("titanic"); Word director("steven Spielberg", 20);

Default Arguments.. [comp151] 17 There may be more than one default arguments. void download(char prog, char os = LINUX, char format = ZIP); All arguments without default values must be declared to the left of default arguments. Thus, the following is an error: void download(char os = LINUX, char prog, char format = ZIP); An argument can have its default initializer specified only once in a file, usually in the public header file, and not in the function definition. Thus, the following is an error. // word.h class Word Word(const char s, int k = 1);... // word.cpp #include word.h Word::Word(const char s, int k = 1)...

Member Initialization List [comp151] 18 Most of the class members may be initialized inside the body of constructors or through member initialization list as follows: class Word int frequency; char str; Word(const char s, int k = 1) : frequency(k) str = new char [strlen(s)+1]; strcpy(str, s);

Member Initialization List.. [comp151] 19 Member initialization list also works for data members which are user-defined class objects. class Word Pair Word w1; Word w2; Word Pair(const char s1, const char s2) : w1(s1), w2(s2) But make sure that the corresponding member constructor exist!

Initialization of const or & Members [comp151] 20 const or reference members can ONLY be initialized through member initialization list. class Word const char language; int frequency; char str; Word(const char s1, int k = 1) : language( E ), frequency(k) str = new char [strlen(s)+1]; strcpy(str, s);

Default Memberwise Assignment [comp151] 21 Word x("titanic", 1); Word y; y = x; // Word(const char, int) constructor // Word() constructor // default memberwise assignment => y.frequency = x.frequency y.str = x.str If an assignment operator function is NOT supplied (through operator overloading), the compiler will provide the default assignment function memberwise assignment. c.f. The case of copy constructor: if you DON T write your own copy constructor, the compiler will provide the default copy constructor memberwise copy. Memberwise assignment/copy does NOT work whenever memory allocation is required for the class members.

Default Memberwise Assignment.. [comp151] 22 Default x = y Shallow Copy Desirable x = y Deep Copy x : frequency = 1 x : frequency = 1 str = 0x24ff "Titanic" str = 0x24ff "Titanic" y : frequency = 1 y : frequency = 1 str = 0x24ff str = 0x53a7 "Titanic"

Member Class Initialization [comp151] 23 Class members should be initialized through member initialization list which calls the appropriate constructors than by assignments. class Word Pair Word word1; Word word2; Word Pair(const char x, const char y): word1(x), word2(y) word1/word2 are initialized using the type conversion constructor, Word(const char*). Word Pair(const char x, const char y) word1 = x; word2 = y; error-prone because word1/word2 are initialized by assignment. If there is no user-defined assignment operator function, the default memberwise assignment may NOT do what is required.

Summary [comp151] 24 Constructors: default, conversion, copy Constructor overloading Default arguments Member initialization list The important relationship between Assignment of class objects, and default/copy constructor

Comp151 Garbage Collection & Destructors

[comp151] 25 Memory Layout of a Running Program static data program code stack ( run-time ) heap ( run-time ) [..., local variables, temporary variables, [ objects dynamically allocated by "new" ] passed arguments ] void f() // x, y are local variables // on the runtime stack int x = 4; Word y("titanic"); // p is another local variable // on the runtime stack. // But the array of 100 int // that p points to // is on the heap int p = new int [100];

Memory Usage on Runtime Stack and Heap [comp151] 26 Local variables are constructed (created) when they are defined in a function/block on the run-time stack. When the function/block terminates, the local variables inside and the CBV arguments will be destructed (and removed) from the run-time stack. Both construction and destruction of variables are done automatically by the compiler by calling the appropriate constructors and destructors. BUT, dynamically allocated memory remains after function/block terminates, and it is the user s responsibility to return it back to the heap for recycling; otherwise, it will stay until the program finishes.

Garbage and Memory Leak [comp151] 27 main() for (int j = 1; j 10000; j++) int snoopy = new int [100]; int vampire = new int [100]; snoopy = vampire; // Now snoopy becomes vampire... // Where is the old snoopy? Garbage is a piece of storage that is part of a program but there are no more references to it in the program. Memory Leak occurs when there is garbage. Question: What happens if garbages are huge or continuously created inside a big loop?!

Example: Before and After p = q [comp151] 28 p : 0x36a4 q : 0x8a48 BEFORE AFTER q : 0x8a48 p : 0x8a48

delete: To Remove Garbage [comp151] 29 main() Stack p = new Stack(9); // A dynamically allocated stack object int q = new int [100]; // A dynamically allocated array of integers... delete p; // delete an object delete [ ] q; // delete an array of objects p = 0; // It is a good practice to set a pointer to NULL q = 0; // when it is not pointing to anything Explicitly remove a single garbage object by calling delete on a pointer to the object. Explicitly remove an array of garbage objects by calling delete [ ] on a pointer to the first object of the array. Notice that delete ONLY puts the dynamically allocated memory back to the heap, and the local variables (p and q above) stay behind on the run-time stack until the function terminates.

Dangling References and Pointers [comp151] 30 However, careless use of delete may cause dangling references. main() char p; char q = new char [128];... p = q; delete [ ] q; q = 0; / Now p is a dangling pointer! / p[0] = a ; delete [ ] p; // Dynamically allocate a char buffer // p and q now points to the same char buffer // delete the char buffer // Error: possibly segmentation fault // Error: possibly segmentation fault A dangling reference is created when memory pointed by a pointer is deleted but the user thinks that the address is still valid. Dangling references are due to carelessness and pointer aliasing an object is pointed to by more than one pointer.

Example: Dangling References [comp151] 31 AFTER BEFORE delete [ ] q ; q = 0; p : 0x8a48 p : 0x8a48 q : 0x8a48 q : 0

[comp151] 32 Other Solutions: Garbage, Dangling References Garbage and dangling references are due to careless pointer manipulation and pointer aliasing. Some languages provide automatic garbage collection facility which stops a program from running from time to time, checks for garbages, and puts them back to the heap for recycling. Some languages do not have pointers at all! (It was said that most program bugs are due to pointers.)

Destructors: Introduction [comp151] 33 void Example() Word x("bug", 4);... int main() Example();.... On return from Example(), the local Word object x of Example() is destroyed from the run-time stack of Example(). i.e. the memory space of (int) x.frequency and (char*) x.str are released. Quiz: How about the dynamically allocated memory for the string, bug that x.str points to?

Destructors [comp151] 34 C++ supports a more general mechanism for user-defined destruction of class objects through destructor member functions. Word() delete [ ] str; A destructor of a class X is a special member function with the name X:: X( ). A destructor takes no arguments, and has no return type thus, there can only be ONE destructor for a class. The destructor of a class is invoked automatically whenever its object goes out of scope out of a function/block. If not defined, the compiler will generate a default destructor of the form X:: X( ) which does nothing.

Example: Destructors [comp151] 35 class Word int frequency; char str; Word() : frequency(0), str(0) Word(const char s, int k = 0)... Word() delete [ ] str; int main() Word p = new Word("Titanic"); Word x = new Word [5];... delete p; delete [ ] x; // destroy a single object // destroy an array of objects

Bug: Default Assignment [comp151] 36 void Bug(Word& x) Word bug("bug", 4); x = bug; int main() Word movie("titanic"); Bug(movie); // which constructor? Quiz: What is movie.str after returning from the call Bug(movie)?

What you should take from this lecture [comp151] 37 The causes of garbages and memory leak How to define destructor function

Comp151 Order of Construction & Destruction

Has relationship [comp151] 38 When an object A has an object B as a data member, we say that A has a B. class B... class A B my b; // some public members or functions It is easy to see which objects have other objects. All you need to do is to look at the class definition.

Example: Order of Constructions [comp151] 39 class Clock Clock() cout "Constructor Clock\n"; Clock() cout "Destructor Clock\n"; class Postoffice Clock clock; Postoffice() cout "Constructor Postoffice\n"; Postoffice() cout "Destructor Postoffice\n"; #include <iostream.h> #include postoffice.h int main() cout "Beginning of main\n"; Postoffice x; cout "End of main\n"; return 0; Beginning of main Constructor Clock Constructor Postoffice End of main Destructor Postoffice Destructor Clock

Order of Constructions: Remarks [comp151] 40 When an object is constructed, all its data members are constructed first. The order of destruction is the exact opposite of the order of construction: The Clock constructor is called before the Postoffice constructor; but, the Clock destructor is called after the Postoffice destructor. As always, construction of data member objects is done by calling their appropriate constructors. If you do not do this explicitly then their default constructors are assumed. Make sure they exist! That is, is equivalent to, Postoffice::Postoffice() Postoffice::Postoffice() : clock() Or, you may do this explicitly by calling their appropriate constructors using the member initialization list syntax.

Order of Constructions with Owned Objects [comp151] 41 class Clock Clock() cout "Constructor Clock\n"; Clock() cout "Destructor Clock\n"; class Postoffice Clock clock; Postoffice() clock = new Clock; cout "Constructor Postoffice\n"; Postoffice() cout "Destructor Postoffice\n"; Beginning of main Constructor Clock Constructor Postoffice End of main Destructor Postoffice

[comp151] 42 Order of Constr. with Owned Objects: Remarks Now the Postoffice owns the Clock. The Clock object is constructed in the Postoffice constructor, but it is never destructed, since we have not implemented that. Remember that objects on the heap are never destructed automatically, so we have just created a memory leak. When object A owns object B, A is responsible for B s destruction.

Order of Constr. with Owned Objects: Fix [comp151] 43 class Clock Clock() cout "Constructor Clock\n"; Clock() cout "Destructor Clock\n"; class Postoffice Clock clock; Postoffice() clock = new Clock; cout "Constructor Postoffice\n"; Postoffice() cout "Destructor Postoffice\n"; delete clock; Beginning of main Constructor Clock Constructor Postoffice End of main Destructor Postoffice Destructor Clock

Order of Constructions w/ Multiple Objects [comp151] 44 class Clock int HHMM; Clock() : HHMM(0) cout "Constructor Clock\n"; Clock(int hhmm) : HHMM(hhmm) cout "Constructor Clock at " HHMM endl; Clock() cout "Destructor Clock at " HHMM endl; class Room Room() cout "Constructor Room\n"; Room() cout "Destructor Room\n"; class Postoffice Clock clock; Room room; Postoffice() cout "Constructor Postoffice\n"; Postoffice() cout "Destructor Postoffice\n"; Beginning of main Constructor Clock Constructor Room Constructor Postoffice End of main Destructor Postoffice Destructor Room Destructor Clock at 0 Note that the 2 data members, Clock and Room are constructed first, in the order in which they appear in the Postoffice class.

Order of Construction w/ Nested Objects [comp151] 45 Let s move the clock to the room. class Clock Clock() cout "Constructor Clock\n"; Clock() cout "Destructor Clock\n"; class Room Clock clock; Room() cout "Constructor Room\n"; Room() cout "Destructor Room\n"; Beginning of main Constructor Clock Constructor Room Constructor Postoffice End of main Destructor Postoffice Destructor Room Destructor Clock class Postoffice Room room; Postoffice()cout "Constructor Postoffice\n"; Postoffice()cout "Destructor Postoffice\n";

[comp151] 46 Order of Constructions w/ Temporary Objects class Clock int HHMM; Clock() : HHMM(0) cout "Constructor Clock\n"; Clock(int hhmm) : HHMM(hhmm) cout "Constructor Clock at " HHMM endl; Clock() cout "Destructor Clock\n"; Beginning of main Constructor Clock Constructor Clock at 800 Destructor Clock Constructor Postoffice End of main Destructor Postoffice Destructor Clock class Postoffice Clock clock; Postoffice() clock = Clock(800); cout "Constructor Postoffice\n"; Postoffice() cout "Destructor Postoffice\n"; Here a temporary clock object is created by Clock(800). Like a ghost, it is created and destroyed behind the scene.

Summary [comp151] 47 When an object is constructed, its data members are constructed first. When the object is destructed, the data members are destructed after the destructor for the object has been executed. When object A owns other objects, remember to destruct them as well in A s destructor. By default, the default constructor is used for the data members. We can use a different constructor for the data members by using member initialization list the colon syntax.