1 Constructors and Destructors Ying Wu Electrical Engineering & Computer Science Northwestern University ECE230 Lectures Series.

Slides:



Advertisements
Similar presentations
Chapter 4 Constructors and Destructors. Objectives Constructors – introduction and features The zero-argument constructor Parameterized constructors Creating.
Advertisements

Constructors and Destructors. Constructor Constructor—what’s this? Constructor—what’s this? method used for initializing objects (of certain class) method.
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.
Introduction to Programming Lecture 39. Copy Constructor.
F UNCTION O VERLOADING Chapter 5 Department of CSE, BUET 1.
Beginning C++ Through Game Programming, Second Edition by Michael Dawson.
Class and Objects.
1 Classes with Pointer Data Members (II) Ying Wu Electrical Engineering & Computer Science Northwestern University EECS 230.
OOP Using Classes - I. Structures vs. Classes C-style structures –No “interface” If implementation changes, all programs using that struct must change.
Wrap Up and Misc Ying Wu Electrical & Computer Engineering Northwestern University ECE230 Lectures Series.
1 Array, Pointer and Reference ( III ) Ying Wu Electrical Engineering & Computer Science Northwestern University ECE230 Lectures.
1 Midterm Review Ying Wu Electrical Engineering & Computer Science Northwestern University EECS230 Lectures Series.
Dynamically Allocated Arrays May 2, Quiz 5 Today.
1 Dynamic Memory Allocation Ying Wu Electrical Engineering & Computer Science Northwestern University EECS 230 Lectures Series.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 16: Classes and Data Abstraction Outline 16.1Introduction.
1 Array, Pointer and Reference ( I ) Ying Wu Electrical Engineering and Computer Science Northwestern University EECS 230 Lectures.
Review of C++ Programming Part II Sheng-Fang Huang.
Call-by-Value vs. Call-by-Reference Call-by-value parameters are used for passing information from the calling function to the called function (input parameters).
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
Copy Control Joe Meehean. More Class Responsibilities When making a new type (i.e., class) we must specify what happens when it is: Copied Assigned Destroyed.
C++ Programming for Graphics Lecture 5 References, New, Arrays and Destructors.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Classes: A Deeper Look Part.
More C++ Classes Systems Programming. C++ Classes  Preprocessor Wrapper  Time Class Case Study –Two versions (old and new)  Class Scope and Assessing.
Copyright  Hannu Laine C++-programming Part 3 Hannu Laine.
CS 11 C++ track: lecture 4 Today: More on memory management the stack and the heap inline functions structs vs. classes.
CS212: Object Oriented Analysis and Design Lecture 7: Arrays, Pointers and Dynamic Memory Allocation.
1 Overloading Overloading allows a function or operator to have a different meaning depending on the type of objects it is used on. Examples: operator+
Array, Pointer and Reference ( I ) Ying Wu Electrical & Computer Engineering Northwestern University ECE230 Lectures Series.
1 Inside the Vector Class: with additional needed methods CPS212CPS212 Gordon College.
Pointers and Dynamic Memory Allocation Copyright Kip Irvine 2003, all rights reserved. Revised 10/28/2003.
Dynamically Allocated Arrays December 4, Skip the Rest of this PowerPoint.
Object-Oriented Programming in C++
SMIE-121 Software Design II School of Mobile Information Engineering, Sun Yat-sen University Lecture.
 Classes in c++ Presentation Topic  A collection of objects with same properties and functions is known as class. A class is used to define the characteristics.
1 C++ Classes (I) Ying Wu Electrical Engineering & Computer Science Northwestern University ECE230 Lectures Series.
Slide 1 Chapter 10 Pointers and Dynamic Arrays. Slide 2 Learning Objectives  Pointers  Pointer variables  Memory management  Dynamic Arrays  Creating.
Object Oriented Programming Elhanan Borenstein Lecture #3 copyrights © Elhanan Borenstein.
More C++ Features True object initialisation
Lecture 3 Classes, Structs, Enums Passing by reference and value Arrays.
CPSC 252 The Big Three Page 1 The “Big Three” Every class that has data members pointing to dynamically allocated memory must implement these three methods:
C++ Programming Lecture 11 Functions – Part III By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
1 C++ Classes: Access (II) Ying Wu Electrical Engineering & Computer Science Northwestern University ECE230 Lectures Series.
Chapter 9 Classes: A Deeper Look, Part I Part II.
Function ( I ) Ying Wu Electrical & Computer Engineering Northwestern University ECE230 Lectures Series.
Class 4 (L34) u Constructors u Default Constructor u Example of Default Constructors u Destructors u Constructors Are Called in Global Scope u Constructors.
LECTURE LECTURE 11 Constructors and destructors Copy constructor Textbook: p , 183.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look, Part 1.
Constructors Initializing New Objects #include “fraction.h” int main() { float x; float y = 6.7; float z(7.2); Fraction.
نظام المحاضرات الالكترونينظام المحاضرات الالكتروني Destructors The destructor fulfills the opposite functionality. It is automatically called when an object.
Introduction to Classes in C++ Instructor - Andrew S. O’Fallon CptS 122 Washington State University.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 223 – Advanced Data Structures C++ Review 2.
CS162 - Topic #6 Lecture: Pointers and Dynamic Memory –Review –Dynamically allocating structures –Combining the notion of classes and pointers –Destructors.
CSE 332: C++ Exceptions Motivation for C++ Exceptions Void Number:: operator/= (const double denom) { if (denom == 0.0) { // what to do here? } m_value.
Object Access m1.write(44); m2.write(m2.read() +1); std::cout
Constructors and Destructors
Chapter 16: Classes and Data Abstraction
This pointer, Dynamic memory allocation, Constructors and Destructor
Chapter 15 Pointers, Dynamic Data, and Reference Types
Chapter 9 Classes: A Deeper Look, Part 1
Constructors and Destructors
CS148 Introduction to Programming II
9-10 Classes: A Deeper Look.
Passing Arguments and The Big 5
Recitation Course 0520 Speaker: Liu Yu-Jiun.
Classes: A Deeper Look, Part 1
ENERGY 211 / CME 211 Lecture 17 October 29, 2008.
Constructors & Destructors
More C++ Classes Systems Programming.
9-10 Classes: A Deeper Look.
Presentation transcript:

1 Constructors and Destructors Ying Wu Electrical Engineering & Computer Science Northwestern University ECE230 Lectures Series

2 A Class is a blueprint Data Functions access Data Functions Class “Class” is the blueprint of a class of “packages”

3 Class vs. Object A blueprint can be instantiated to different “packages” or objects Example Class COffer{ Title Base_salary Bonus rate Benefit Allowance Working_load … }; Different people may get different offers, so we have COffer John_offer, Mike_offer, Joe_offer; Then, you may need to specify the values in the offer for each people

4 Question? Can we have a way to specify a default one instead of setting them one by one? Is there is way to initialize a “package” in our need when I create it? –E.g., COffer John_Offer(“manager”, $80K)? –Instead of: Coffer John_Offer; John_Offer.SetTitle(“Manager”); John_Offer.SetBaseSalary($80K);

5 What to learn today? Constructor Default constructor Destructor When constructor and destructor are called Copy an object How to pass an object to a function

6 Initializing Class Objects: Constructors Constructors –Initialize class members –Same name as the class –No return type –Member variables can be initialized by the constructor or set afterwards Passing arguments to a constructor –When an object of a class is declared, initializers can be provided –Format of declaration with initializers: Class-type ObjectName( value1,value2,…); –Default arguments may also be specified in the constructor prototype

7 Example CVariable::CVariable(const char* name, const double& v) { m_dValue = v; m_sName = new char[strlen(name)+1]; strcpy(m_sName, name); } Void main() { CVariable a(“var_a”, 1.0); CVariable b(“v”, 3.3); } ab ‘v’ ‘a’ ‘r’ ‘_’ ‘a’ 0 ‘v’ 0

8 Default Constructor Pay more attention! –We’d better define a default constructor for a class i.e., a constructor CVariable() exists –So that we can use something like CVariable var; –On the other hand, if we only have a constructor CVariable(const char*name, double v) –We can only instantiate an object by using CVariable var(“a”,2.3); If you do not use a default constructor, the compiler will create one for you, but it will not guarantee it is what you want! !! Can you guess what the compiler will do for you?

9 A safe way! CVariable::CVariable() { m_dValue = 0.0; m_sName = NULL; } What the compiler will do for you: a It is safer to do it yourself by have a default constructor a 0 0

10 Another Way: member initializer CVariable::CVariable() : m_dValue(0.0), m_sName(NULL) { // empty }

11 You might wonder … In our previous lectures, we learnt DMA –If you need memory, you new some –If you don’t want them anymore, you should delete them, and the O/S will recycle them We know a rule: –Always pair new and delete Otherwise, those allocated memory will never be able to be used by other programs until your program ends Then your program might have eaten all the memories! Then, let’s see …

12 Memory Leak void myFunc() { CVariable tmp(“I have no idea!”, 1.0); } void main() { for(int k=0; k<1000;k++){ for(int j=0;j<1000;j++){ myFunc(); } What will happen? At each myFunc() call, you will “waste” 16Bytes. Then before your program ends, you will eat 16M in total!!! “I have no idea” ………………

13 How can we solve it? Can we have an automatic mechanism: –When an object is no longer needed, if it has some memory allocated by me, I should recycle them. –How to do it automatically?

14 Destructors –Are member function of class –Perform termination housekeeping before the system reclaims the object’s memory –Complement of the constructor –Name is tilde ( ~ ) followed by the class name Recall that the constructor’s name is the class name –Receives no parameters, returns no value –One destructor per class No overloading allowed

15 Housekeeping! CVariable::~CVariable() { if(m_sName!=NULL){ delete [] m_sName; } Note: (1) Each class has only ONE destructor (2) Generally, we don’t call the destructor explicitly. (3) It will be called ATUOMATICALLY. Question: when constructor and destructors are called?

16 When Constructors and Destructors Are Called Constructors and destructors called automatically –Order depends on scope of objects Global scope objects –Constructors called before any other function (including main ) –Destructors called when main terminates (or exit function called) –Destructors not called if program terminates with abort Automatic local objects –Constructors called when objects are defined –Destructors called when objects leave scope i.e., when the block in which they are defined is exited –Destructors not called if the program ends with exit or abort

17 Class CTest{ CTest(); ~CTest(); }; CTest::CTest() { cout << “Constructor called!\n”); } CTest:~CTest() { cout << “Destructor called!\n”); } CTest tg; void myFunc() { CTest tf; } void main() { CTest tm; myFunc(); Ctest tm_2; } constructor called!(tg) Constructor called!(tm) Constructor called!(tf) Destructor called!(~tf) Constructor called!(tm_2) Destructor called!(tm_2) Destructor called!(tm) Destructor called!(tg)

18 Can I have sth like this? void main() { CVariable a(“var_a”, 1.5); CVariable b; b = a; }

19 Memberwise Copy Assigning objects –An object can be assigned to another object of the same type using the assignment operator ( = ) –Member by member copy Objects may be –Passed as function arguments –Returned from functions (call-by-value default)

20 Let’s go deep! ‘v’ ‘a’ ‘r’ ‘_’ ‘a’ 0 a 1.5 b CVariable b; CVariable a(“var_a”, 1.5); b = a;

21 A problem! void main() { CVariable a(“var_a”, 1.5); CVariable b; b = a; a.SetName(“change”); cout << b.Name() << endl; } How to solve this problem? Keep this question and we’ll see it next week! 1.5 a ‘v’ ‘a’ ‘r’ ‘_’ ‘a’ 0 b 1.5 ‘c’ ‘h’ ‘a’ ‘n’ ‘g’ ‘e’ 0 ?

22 How to pass an object to functions Call-by-value –involves copying objects (memberwise) –is good for security (safe), but bad for performance Call-by-reference –passes the reference or the pointer –does not copy anything –is good for performance, but bad for security, because the function can change the object Call-by- const -reference –passes a const reference or a const pointer –is good for both! –WHY? The function will not be able to change the object, because it is a const object.

23 A BIG Problem! void myFunc(CVariable t) { cout << “something happen?\n”); } void main() { CVariable a(“var_a”, 1.5); myFunc(a); cout << a.Name() << endl; } 1.5 a ‘v’ ‘a’ ‘r’ ‘_’ ‘a’ t

24 Another BIG Problem! CVariable Create() { CVariable t(“var_a”, 0.0); return t; } void main() { CVariable a; a = Create(); cout << a.Name() << endl; } ‘v’ ‘a’ ‘r’ ‘_’ ‘a’ t tmp 0.0 a ???

25 Save them for next week! Yes, we have big problems! Let’s solve them next week.

26 Questions for today Finding errors 1.void ~Time( int ); 2.Definition of class Time class Time{ public: // function prototypes private: int hour = 0; int mintue = 0; int second = 0; }