1 Constructors and Destructors Ying Wu Electrical Engineering & Computer Science Northwestern...

26
1 Constructors and Destructors Ying Wu Electrical Engineering & Computer Science Northwestern University [email protected] ECE230 Lectures Series
  • date post

    20-Dec-2015
  • Category

    Documents

  • view

    227
  • download

    5

Transcript of 1 Constructors and Destructors Ying Wu Electrical Engineering & Computer Science Northwestern...

Page 1: 1 Constructors and Destructors Ying Wu Electrical Engineering & Computer Science Northwestern University yingwu@ece.northwestern.edu ECE230 Lectures Series.

1

Constructors and Destructors

Ying Wu Electrical Engineering & Computer

ScienceNorthwestern [email protected]

ECE230 Lectures Series

Page 2: 1 Constructors and Destructors Ying Wu Electrical Engineering & Computer Science Northwestern University yingwu@ece.northwestern.edu ECE230 Lectures Series.

2

A Class is a blueprint

Data

Functions

access

Data

Functions

Class

• “Class” is the blueprint of a class of “packages”

Page 3: 1 Constructors and Destructors Ying Wu Electrical Engineering & Computer Science Northwestern University yingwu@ece.northwestern.edu ECE230 Lectures Series.

3

Class vs. Object A blueprint can be instantiated to different “packages” or

objects

ExampleClass COffer{

Title

Base_salary

Bonus rate

Benefit

Allowance

Working_load

};

Different people may get different offers, so we haveCOffer John_offer, Mike_offer, Joe_offer;

Then, you may need to specify the values in the offer for each people

Page 4: 1 Constructors and Destructors Ying Wu Electrical Engineering & Computer Science Northwestern University yingwu@ece.northwestern.edu ECE230 Lectures Series.

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);

Page 5: 1 Constructors and Destructors Ying Wu Electrical Engineering & Computer Science Northwestern University yingwu@ece.northwestern.edu ECE230 Lectures Series.

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

Page 6: 1 Constructors and Destructors Ying Wu Electrical Engineering & Computer Science Northwestern University yingwu@ece.northwestern.edu ECE230 Lectures Series.

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

Page 7: 1 Constructors and Destructors Ying Wu Electrical Engineering & Computer Science Northwestern University yingwu@ece.northwestern.edu ECE230 Lectures Series.

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);

}

a

b

1.0

3.3

‘v’

‘a’

‘r’

‘_’

‘a’

0

‘v’

0

Page 8: 1 Constructors and Destructors Ying Wu Electrical Engineering & Computer Science Northwestern University yingwu@ece.northwestern.edu ECE230 Lectures Series.

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 likeCVariable var;

– On the other hand, if we only have a constructor CVariable(const char*name,

double v)

– We can only instantiate an object by usingCVariable 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?

Page 9: 1 Constructors and Destructors Ying Wu Electrical Engineering & Computer Science Northwestern University yingwu@ece.northwestern.edu ECE230 Lectures Series.

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

a0

0

Page 10: 1 Constructors and Destructors Ying Wu Electrical Engineering & Computer Science Northwestern University yingwu@ece.northwestern.edu ECE230 Lectures Series.

10

Another Way: member initializer

CVariable::CVariable() :

m_dValue(0.0),

m_sName(NULL)

{

// empty

}

Page 11: 1 Constructors and Destructors Ying Wu Electrical Engineering & Computer Science Northwestern University yingwu@ece.northwestern.edu ECE230 Lectures Series.

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 …

Page 12: 1 Constructors and Destructors Ying Wu Electrical Engineering & Computer Science Northwestern University yingwu@ece.northwestern.edu ECE230 Lectures Series.

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”

“I have no idea”“I have no idea”

“I have no idea”

“I have no idea”

“I have no idea”

“I have no idea”

………

Page 13: 1 Constructors and Destructors Ying Wu Electrical Engineering & Computer Science Northwestern University yingwu@ece.northwestern.edu ECE230 Lectures Series.

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?

Page 14: 1 Constructors and Destructors Ying Wu Electrical Engineering & Computer Science Northwestern University yingwu@ece.northwestern.edu ECE230 Lectures Series.

14

Destructors

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

nameRecall that the constructor’s name is the class

name

– Receives no parameters, returns no value– One destructor per class

No overloading allowed

Page 15: 1 Constructors and Destructors Ying Wu Electrical Engineering & Computer Science Northwestern University yingwu@ece.northwestern.edu ECE230 Lectures Series.

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?

Page 16: 1 Constructors and Destructors Ying Wu Electrical Engineering & Computer Science Northwestern University yingwu@ece.northwestern.edu ECE230 Lectures Series.

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

Page 17: 1 Constructors and Destructors Ying Wu Electrical Engineering & Computer Science Northwestern University yingwu@ece.northwestern.edu ECE230 Lectures Series.

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)

Page 18: 1 Constructors and Destructors Ying Wu Electrical Engineering & Computer Science Northwestern University yingwu@ece.northwestern.edu ECE230 Lectures Series.

18

Can I have sth like this?

void main()

{

CVariable a(“var_a”, 1.5);

CVariable b;

b = a;

}

Page 19: 1 Constructors and Destructors Ying Wu Electrical Engineering & Computer Science Northwestern University yingwu@ece.northwestern.edu ECE230 Lectures Series.

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)

Page 20: 1 Constructors and Destructors Ying Wu Electrical Engineering & Computer Science Northwestern University yingwu@ece.northwestern.edu ECE230 Lectures Series.

20

Let’s go deep!

‘v’

‘a’

‘r’

‘_’

‘a’

0

a 1.5

b 1.5

CVariable b;

CVariable a(“var_a”, 1.5);

b = a;

Page 21: 1 Constructors and Destructors Ying Wu Electrical Engineering & Computer Science Northwestern University yingwu@ece.northwestern.edu ECE230 Lectures Series.

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.5a

‘v’

‘a’

‘r’

‘_’

‘a’

0

b 1.5

‘c’

‘h’

‘a’

‘n’

‘g’

‘e’

0

?

Page 22: 1 Constructors and Destructors Ying Wu Electrical Engineering & Computer Science Northwestern University yingwu@ece.northwestern.edu ECE230 Lectures Series.

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.

Page 23: 1 Constructors and Destructors Ying Wu Electrical Engineering & Computer Science Northwestern University yingwu@ece.northwestern.edu ECE230 Lectures Series.

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.5a

‘v’

‘a’

‘r’

‘_’

‘a’

0

1.5t

Page 24: 1 Constructors and Destructors Ying Wu Electrical Engineering & Computer Science Northwestern University yingwu@ece.northwestern.edu ECE230 Lectures Series.

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.0t

0.0tmp

0.0a???

Page 25: 1 Constructors and Destructors Ying Wu Electrical Engineering & Computer Science Northwestern University yingwu@ece.northwestern.edu ECE230 Lectures Series.

25

Save them for next week!

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

Page 26: 1 Constructors and Destructors Ying Wu Electrical Engineering & Computer Science Northwestern University yingwu@ece.northwestern.edu ECE230 Lectures Series.

26

Questions for todayFinding errors

1. void ~Time( int );

2. Definition of class Timeclass Time{

public:// function prototypesprivate:

int hour = 0;int mintue = 0;int second = 0;

}