Download presentation
Presentation is loading. Please wait.
1
1 Constructors and Destructors Ying Wu Electrical Engineering & Computer Science Northwestern University yingwu@ece.northwestern.edu ECE230 Lectures Series
2
2 A Class is a blueprint Data Functions access Data Functions Class “Class” is the blueprint of a class of “packages”
3
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
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
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
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
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 1.0 3.3 ‘v’ ‘a’ ‘r’ ‘_’ ‘a’ 0 ‘v’ 0
8
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
9 A safe way! CVariable::CVariable() { m_dValue = 0.0; m_sName = NULL; } What the compiler will do for you: a 3248393 3446564 It is safer to do it yourself by have a default constructor a 0 0
10
10 Another Way: member initializer CVariable::CVariable() : m_dValue(0.0), m_sName(NULL) { // empty }
11
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
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
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
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
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
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
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
18 Can I have sth like this? void main() { CVariable a(“var_a”, 1.5); CVariable b; b = a; }
19
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
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
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
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
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’ 0 1.5 t
24
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’ 0 0.0 t tmp 0.0 a ???
25
25 Save them for next week! Yes, we have big problems! Let’s solve them next week.
26
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; }
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.