SlideShare a Scribd company logo
CSE240 – Introduction to
Programming Languages
Lecture 13:
Programming with C++ | memory management
Javier Gonzalez-Sanchez
javiergs@asu.edu
javiergs.engineering.asu.edu
Office Hours: By appointment
Javier Gonzalez-Sanchez | CSE 240 | Fall 2017 | 2
Outline
• static,
• constructor and destructor,
• new and delete
static
Javier Gonzalez-Sanchez | CSE 240 | Fall 2017 | 4
Example
1. #include <iostream>
2. using namespace std;
3. class Foo {
4. public:
5. void counting();
6. int getCounterB();
7. static int counterA;
8. private:
9. int counterB;
10. };
11.
12. // initial value to static member variable
13. int Foo::counterA = 0;
14. int counter = 0;
A static variable is shared by all the
objects from a class. Therefore,
changes made to a static variable will
impact all objects from the class
Javier Gonzalez-Sanchez | CSE 240 | Fall 2017 | 5
1. #include <iostream>
2. using namespace std;
3. class Foo {
4. public:
5. void counting();
6. int getCounterB();
7. static int counterA;
8. private:
9. int counterB;
10. };
11.
12. // initial value to static member variable
13. int Foo::counterA = 0;
14. int counter = 0;
Example
static versus global Variables
static variables prevents functions
outside the class to access the
variable. As a global variable, all
other functions can read/write it.
A static variable is shared by all the
objects from a class. Therefore,
changes made to a static variable will
impact all objects from the class
Javier Gonzalez-Sanchez | CSE 240 | Fall 2017 | 6
Example
18. void Foo::counting() { // Set a new mil Time
19. counterA++;
20. counterB++;
21. }
22. int Foo::getCounterB() {
23. return counterB;
24. }
25. int main() {
26. Foo f1, f2, f3;
27. f1.counting();
28. f2.counting();
29. f2.counting();
30. f3.counting();
31. cout << Foo::counterA<<endl;
32. cout << f1.getCounterB()<<endl;
33. cout << Foo::counterA<<endl;
34. cout << f2.getCounterB()<<endl;
35. return 0;
36. }
A static variable go out of scope only
if the program terminated. And it can
be used even without creating an
object from the class.
Constructors and destructors
Javier Gonzalez-Sanchez | CSE 240 | Fall 2017 | 8
Constructor and Destructor
A constructor in a class:
• is a function whose name is same as the class name, and
• is used to automatically initialize objects.
A destructor in a class:
• is a function whose name is same as the class name (with a ~ as
prefix), and
• is used to collect garbage.
Javier Gonzalez-Sanchez | CSE 240 | Fall 2017 | 9
Constructor and Destructor
#include <iostream>
using namespace std;
class Queue {
private:
int queue_size;
protected:
int *buffer;
int front;
int rear;
public:
Queue();
Queue(int n);
~Queue();
};
Queue::Queue() { // constructor
cout << "constructor(void)"<<endl;
// code...
}
Queue::Queue(int n) { // constructor overload
cout << "constructor (int)"<<endl;
// code...
}
Queue::~Queue(void) {
cout << "destructor"<<endl;
// code...
}
int main () {
Queue myQueue1(500);
Queue myQueue2;
// more code...
return 0;
}
Javier Gonzalez-Sanchez | CSE 240 | Fall 2017 | 10
Constructor and Destructor
#include <iostream>
using namespace std;
class Queue {
private:
int queue_size;
protected:
int *buffer;
int front;
int rear;
public:
Queue();
Queue(int n);
~Queue();
};
Queue::Queue() { // constructor
cout << "constructor(void)"<<endl;
// code...
}
Queue::Queue(int n) { // constructor overload
cout << "constructor (int)"<<endl;
// code...
}
Queue::~Queue(void) {
cout << "destructor"<<endl;
// code...
}
int main () {
Queue myQueue1(500);
Queue myQueue2;
// more code...
return 0;
}
Javier Gonzalez-Sanchez | CSE 240 | Fall 2017 | 11
When is a destructor called?
• When a local object (from stack) with block scope goes out of scope.
• When a program (main function) ends and global or static objects
exist (OS will collect them anyway).
• When the destructor is explicitly called.
• When the delete keyword is called.
new and delete
Javier Gonzalez-Sanchez | CSE 240 | Fall 2017 | 13
new and delete
int main () {
Queue myQueue2(500);
// declare a pointer only
Queue *myQueue;
// reserve memory for an object
myQueue = new Queue(500);
// use the object
myQueue->enqueue(23);
myQueue2.enqueue(8);
// delete will call ~Queue();
delete myQueue;
...
delete myQueue2;//no needed
}
Javier Gonzalez-Sanchez | CSE 240 | Fall 2017 | 14
new and delete with constructors and destructors
#include <iostream>
using namespace std;
class Queue {
private:
int queue_size;
protected:
int *buffer;
int front;
int rear;
public:
Queue();
Queue(int n);
~Queue();
};
Queue::Queue() { // constructor
cout << "constructor(void)"<<endl;
// code...
buffer = NULL;
}
Queue::Queue(int n) { // constructor overload
cout << "constructor (int)"<<endl;
// code...
buffer = new int[queue_size];
}
Queue::~Queue(void) {
cout << "destructor"<<endl;
// code...
delete [] buffer;
}
int main () {
Queue myQueue1(500);
Queue myQueue2;
Queue *myQueue3 = new Queue(100);
// more code...
delete myQueue3;
return 0;
}
Javier Gonzalez-Sanchez | CSE 240 | Fall 2017 | 15
Summary
• If an object is on the stack, instead of on the heap, destructor will be
called when the object goes out of scope. No delete operation is
necessary.
• All heap objects must be explicitly deleted before leaving the
function, if they are no longer needed.
• The function delete will implicitly call the destructor of the class, so
that an object linked to a variable in the to-be-deleted object can
be de-allocated too, i.e., using delete for variables created in the
class (normally in the constructor).
Javier Gonzalez-Sanchez | CSE 240 | Fall 2017 | 16
delete and Array of Objects
#include <iostream>
using namespace std;
#define size 4
class arrayObject {
public:
int x; double y;
arrayObject() { cout << "arrayObject's constructor called" << endl; }
~arrayObject() { cout << "arrayObject's destructor called" << endl; }
};
int main() {
arrayObject *p, *q; // declare two pointers
p = new arrayObject[size]; // Create an array of objects
for (q = p; q < p + size; q++) { // Initialize the objects
q->x = 10; q->y = 1.5;
}
for (q = p; q < p + size; q++) {
cout << "Element address " << q << " Element x value: " << q->x << endl;
cout << "Element address " << q << " Element y value: " << q->y << endl;
}
delete[] p;
return 0;
}
Javier Gonzalez-Sanchez | CSE 240 | Fall 2017 | 17
Summary
• How do we delete an array of objects?
We can use a loop to delete each element,
• However, the language provides a library function to delete all
the elements one by one without the user to explicitly use a loop:
delete[] array;
Javier Gonzalez-Sanchez | CSE 240 | Fall 2017 | 18
Summary
Java
• Primitive variables (int, float, boolean) use value type.
• All other variables (string, array, user defined classes) use reference type. (Java uses
automatic garbage collection).
C++
• Both value and reference types exist:
• if value semantics used then memory is allocated on stack or on static by compiler.
Memory de-allocation is done automatically.
• if reference semantics used (e.g. variable is a pointer to an object), then memory must
be allocated explicitly using new and explicitly de-allocated using delete
Javier Gonzalez-Sanchez | CSE 240 | Fall 2017 | 19
Summary
// in C++
Report r; // an object is allocated to r
Report *rp1, *rp2; // two pointers declared
rp1 = &r; // rp1 points to object r
rp2 = new Report(); // an object is created, linked to rp2
// ..
delete rp2;
// in Java
Report r; // an reference is allocated
r = new Report (); // an object is created and linked to r
CSE240 – Introduction to Programming Languages
Javier Gonzalez-Sanchez
javiergs@asu.edu
Fall 2017
Disclaimer. These slides can only be used as study material for the class CSE240 at ASU. They cannot be distributed or used for another purpose.

More Related Content

What's hot

谈谈Javascript设计
谈谈Javascript设计谈谈Javascript设计
谈谈Javascript设计
Alipay
 
Untitled presentation(4)
Untitled presentation(4)Untitled presentation(4)
Untitled presentation(4)chan20kaur
 
C sharp 8.0 new features
C sharp 8.0 new featuresC sharp 8.0 new features
C sharp 8.0 new features
Miguel Bernard
 
Operator overloading2
Operator overloading2Operator overloading2
Operator overloading2
zindadili
 
Продвинутая отладка JavaScript с помощью Chrome Dev Tools
Продвинутая отладка JavaScript с помощью Chrome Dev ToolsПродвинутая отладка JavaScript с помощью Chrome Dev Tools
Продвинутая отладка JavaScript с помощью Chrome Dev Tools
FDConf
 
High performance web programming with C++14
High performance web programming with C++14High performance web programming with C++14
High performance web programming with C++14
Matthieu Garrigues
 
vbscript-reference book
vbscript-reference bookvbscript-reference book
vbscript-reference book
Anand Dhana
 
"О некоторых особенностях Objective-C++" Влад Михайленко (Maps.Me)
"О некоторых особенностях Objective-C++" Влад Михайленко (Maps.Me)"О некоторых особенностях Objective-C++" Влад Михайленко (Maps.Me)
"О некоторых особенностях Objective-C++" Влад Михайленко (Maps.Me)
AvitoTech
 
Int64
Int64Int64
Unleash your inner console cowboy
Unleash your inner console cowboyUnleash your inner console cowboy
Unleash your inner console cowboy
Kenneth Geisshirt
 
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
GeeksLab Odessa
 
Rainer Grimm, “Functional Programming in C++11”
Rainer Grimm, “Functional Programming in C++11”Rainer Grimm, “Functional Programming in C++11”
Rainer Grimm, “Functional Programming in C++11”
Platonov Sergey
 
Type Driven Development with TypeScript
Type Driven Development with TypeScriptType Driven Development with TypeScript
Type Driven Development with TypeScript
Garth Gilmour
 
Machine-level Composition of Modularized Crosscutting Concerns
Machine-level Composition of Modularized Crosscutting ConcernsMachine-level Composition of Modularized Crosscutting Concerns
Machine-level Composition of Modularized Crosscutting Concerns
saintiss
 
Class ‘increment’
Class ‘increment’Class ‘increment’
Class ‘increment’
Syed Zaid Irshad
 
Blazing Fast Windows 8 Apps using Visual C++
Blazing Fast Windows 8 Apps using Visual C++Blazing Fast Windows 8 Apps using Visual C++
Blazing Fast Windows 8 Apps using Visual C++
Microsoft Developer Network (MSDN) - Belgium and Luxembourg
 
Swift で JavaScript 始めませんか? #iOSDC
Swift で JavaScript 始めませんか? #iOSDCSwift で JavaScript 始めませんか? #iOSDC
Swift で JavaScript 始めませんか? #iOSDC
Tomohiro Kumagai
 

What's hot (19)

P2
P2P2
P2
 
谈谈Javascript设计
谈谈Javascript设计谈谈Javascript设计
谈谈Javascript设计
 
Untitled presentation(4)
Untitled presentation(4)Untitled presentation(4)
Untitled presentation(4)
 
C sharp 8.0 new features
C sharp 8.0 new featuresC sharp 8.0 new features
C sharp 8.0 new features
 
Operator overloading2
Operator overloading2Operator overloading2
Operator overloading2
 
Продвинутая отладка JavaScript с помощью Chrome Dev Tools
Продвинутая отладка JavaScript с помощью Chrome Dev ToolsПродвинутая отладка JavaScript с помощью Chrome Dev Tools
Продвинутая отладка JavaScript с помощью Chrome Dev Tools
 
High performance web programming with C++14
High performance web programming with C++14High performance web programming with C++14
High performance web programming with C++14
 
vbscript-reference book
vbscript-reference bookvbscript-reference book
vbscript-reference book
 
"О некоторых особенностях Objective-C++" Влад Михайленко (Maps.Me)
"О некоторых особенностях Objective-C++" Влад Михайленко (Maps.Me)"О некоторых особенностях Objective-C++" Влад Михайленко (Maps.Me)
"О некоторых особенностях Objective-C++" Влад Михайленко (Maps.Me)
 
Int64
Int64Int64
Int64
 
Unleash your inner console cowboy
Unleash your inner console cowboyUnleash your inner console cowboy
Unleash your inner console cowboy
 
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
 
Rainer Grimm, “Functional Programming in C++11”
Rainer Grimm, “Functional Programming in C++11”Rainer Grimm, “Functional Programming in C++11”
Rainer Grimm, “Functional Programming in C++11”
 
Type Driven Development with TypeScript
Type Driven Development with TypeScriptType Driven Development with TypeScript
Type Driven Development with TypeScript
 
Machine-level Composition of Modularized Crosscutting Concerns
Machine-level Composition of Modularized Crosscutting ConcernsMachine-level Composition of Modularized Crosscutting Concerns
Machine-level Composition of Modularized Crosscutting Concerns
 
Class ‘increment’
Class ‘increment’Class ‘increment’
Class ‘increment’
 
Blazing Fast Windows 8 Apps using Visual C++
Blazing Fast Windows 8 Apps using Visual C++Blazing Fast Windows 8 Apps using Visual C++
Blazing Fast Windows 8 Apps using Visual C++
 
C++ file
C++ fileC++ file
C++ file
 
Swift で JavaScript 始めませんか? #iOSDC
Swift で JavaScript 始めませんか? #iOSDCSwift で JavaScript 始めませんか? #iOSDC
Swift で JavaScript 始めませんか? #iOSDC
 

Similar to 201801 CSE240 Lecture 13

Constructors and Destructors
Constructors and DestructorsConstructors and Destructors
Constructors and Destructors
Keyur Vadodariya
 
constructorsfjy5ediykEASFul;IUWORHusi;gfb.pptx
constructorsfjy5ediykEASFul;IUWORHusi;gfb.pptxconstructorsfjy5ediykEASFul;IUWORHusi;gfb.pptx
constructorsfjy5ediykEASFul;IUWORHusi;gfb.pptx
AshrithaRokkam
 
201801 CSE240 Lecture 14
201801 CSE240 Lecture 14201801 CSE240 Lecture 14
201801 CSE240 Lecture 14
Javier Gonzalez-Sanchez
 
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCECONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
Venugopalavarma Raja
 
Constructors and destructors in C++
Constructors and destructors in  C++Constructors and destructors in  C++
Constructors and destructors in C++
RAJ KUMAR
 
Constructors & Destructors [Compatibility Mode].pdf
Constructors & Destructors [Compatibility Mode].pdfConstructors & Destructors [Compatibility Mode].pdf
Constructors & Destructors [Compatibility Mode].pdf
LadallaRajKumar
 
CONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptx
CONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptxCONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptx
CONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptx
DeepasCSE
 
C# - What's Next?
C# - What's Next?C# - What's Next?
C# - What's Next?
Christian Nagel
 
Constructors in C++.pptx
Constructors in C++.pptxConstructors in C++.pptx
Constructors in C++.pptx
Rassjb
 
C sharp 8.0 new features
C sharp 8.0 new featuresC sharp 8.0 new features
C sharp 8.0 new features
MSDEVMTL
 
C#2
C#2C#2
Friend this-new&delete
Friend this-new&deleteFriend this-new&delete
Friend this-new&delete
Shehzad Rizwan
 
C# What's next? (7.x and 8.0)
C# What's next? (7.x and 8.0)C# What's next? (7.x and 8.0)
C# What's next? (7.x and 8.0)
Christian Nagel
 
Static code analysis: what? how? why?
Static code analysis: what? how? why?Static code analysis: what? how? why?
Static code analysis: what? how? why?
Andrey Karpov
 
Introduction to C#
Introduction to C#Introduction to C#
Introduction to C#
ANURAG SINGH
 
2 BytesC++ course_2014_c3_ function basics&parameters and overloading
2 BytesC++ course_2014_c3_ function basics&parameters and overloading2 BytesC++ course_2014_c3_ function basics&parameters and overloading
2 BytesC++ course_2014_c3_ function basics&parameters and overloading
kinan keshkeh
 
Constructor and Destructors in C++
Constructor and Destructors in C++Constructor and Destructors in C++
Constructor and Destructors in C++
sandeep54552
 
C# 7 development
C# 7 developmentC# 7 development
C# 7 development
Fisnik Doko
 
Return of c++
Return of c++Return of c++
Return of c++
Yongwei Wu
 
Sencha Roadshow 2017: Modernizing the Ext JS Class System and Tooling
Sencha Roadshow 2017: Modernizing the Ext JS Class System and ToolingSencha Roadshow 2017: Modernizing the Ext JS Class System and Tooling
Sencha Roadshow 2017: Modernizing the Ext JS Class System and Tooling
Sencha
 

Similar to 201801 CSE240 Lecture 13 (20)

Constructors and Destructors
Constructors and DestructorsConstructors and Destructors
Constructors and Destructors
 
constructorsfjy5ediykEASFul;IUWORHusi;gfb.pptx
constructorsfjy5ediykEASFul;IUWORHusi;gfb.pptxconstructorsfjy5ediykEASFul;IUWORHusi;gfb.pptx
constructorsfjy5ediykEASFul;IUWORHusi;gfb.pptx
 
201801 CSE240 Lecture 14
201801 CSE240 Lecture 14201801 CSE240 Lecture 14
201801 CSE240 Lecture 14
 
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCECONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
 
Constructors and destructors in C++
Constructors and destructors in  C++Constructors and destructors in  C++
Constructors and destructors in C++
 
Constructors & Destructors [Compatibility Mode].pdf
Constructors & Destructors [Compatibility Mode].pdfConstructors & Destructors [Compatibility Mode].pdf
Constructors & Destructors [Compatibility Mode].pdf
 
CONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptx
CONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptxCONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptx
CONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptx
 
C# - What's Next?
C# - What's Next?C# - What's Next?
C# - What's Next?
 
Constructors in C++.pptx
Constructors in C++.pptxConstructors in C++.pptx
Constructors in C++.pptx
 
C sharp 8.0 new features
C sharp 8.0 new featuresC sharp 8.0 new features
C sharp 8.0 new features
 
C#2
C#2C#2
C#2
 
Friend this-new&delete
Friend this-new&deleteFriend this-new&delete
Friend this-new&delete
 
C# What's next? (7.x and 8.0)
C# What's next? (7.x and 8.0)C# What's next? (7.x and 8.0)
C# What's next? (7.x and 8.0)
 
Static code analysis: what? how? why?
Static code analysis: what? how? why?Static code analysis: what? how? why?
Static code analysis: what? how? why?
 
Introduction to C#
Introduction to C#Introduction to C#
Introduction to C#
 
2 BytesC++ course_2014_c3_ function basics&parameters and overloading
2 BytesC++ course_2014_c3_ function basics&parameters and overloading2 BytesC++ course_2014_c3_ function basics&parameters and overloading
2 BytesC++ course_2014_c3_ function basics&parameters and overloading
 
Constructor and Destructors in C++
Constructor and Destructors in C++Constructor and Destructors in C++
Constructor and Destructors in C++
 
C# 7 development
C# 7 developmentC# 7 development
C# 7 development
 
Return of c++
Return of c++Return of c++
Return of c++
 
Sencha Roadshow 2017: Modernizing the Ext JS Class System and Tooling
Sencha Roadshow 2017: Modernizing the Ext JS Class System and ToolingSencha Roadshow 2017: Modernizing the Ext JS Class System and Tooling
Sencha Roadshow 2017: Modernizing the Ext JS Class System and Tooling
 

More from Javier Gonzalez-Sanchez

201804 SER332 Lecture 01
201804 SER332 Lecture 01201804 SER332 Lecture 01
201804 SER332 Lecture 01
Javier Gonzalez-Sanchez
 
201801 SER332 Lecture 03
201801 SER332 Lecture 03201801 SER332 Lecture 03
201801 SER332 Lecture 03
Javier Gonzalez-Sanchez
 
201801 SER332 Lecture 04
201801 SER332 Lecture 04201801 SER332 Lecture 04
201801 SER332 Lecture 04
Javier Gonzalez-Sanchez
 
201801 SER332 Lecture 02
201801 SER332 Lecture 02201801 SER332 Lecture 02
201801 SER332 Lecture 02
Javier Gonzalez-Sanchez
 
201801 CSE240 Lecture 26
201801 CSE240 Lecture 26201801 CSE240 Lecture 26
201801 CSE240 Lecture 26
Javier Gonzalez-Sanchez
 
201801 CSE240 Lecture 25
201801 CSE240 Lecture 25201801 CSE240 Lecture 25
201801 CSE240 Lecture 25
Javier Gonzalez-Sanchez
 
201801 CSE240 Lecture 24
201801 CSE240 Lecture 24201801 CSE240 Lecture 24
201801 CSE240 Lecture 24
Javier Gonzalez-Sanchez
 
201801 CSE240 Lecture 23
201801 CSE240 Lecture 23201801 CSE240 Lecture 23
201801 CSE240 Lecture 23
Javier Gonzalez-Sanchez
 
201801 CSE240 Lecture 22
201801 CSE240 Lecture 22201801 CSE240 Lecture 22
201801 CSE240 Lecture 22
Javier Gonzalez-Sanchez
 
201801 CSE240 Lecture 21
201801 CSE240 Lecture 21201801 CSE240 Lecture 21
201801 CSE240 Lecture 21
Javier Gonzalez-Sanchez
 
201801 CSE240 Lecture 20
201801 CSE240 Lecture 20201801 CSE240 Lecture 20
201801 CSE240 Lecture 20
Javier Gonzalez-Sanchez
 
201801 CSE240 Lecture 19
201801 CSE240 Lecture 19201801 CSE240 Lecture 19
201801 CSE240 Lecture 19
Javier Gonzalez-Sanchez
 
201801 CSE240 Lecture 18
201801 CSE240 Lecture 18201801 CSE240 Lecture 18
201801 CSE240 Lecture 18
Javier Gonzalez-Sanchez
 
201801 CSE240 Lecture 17
201801 CSE240 Lecture 17201801 CSE240 Lecture 17
201801 CSE240 Lecture 17
Javier Gonzalez-Sanchez
 
201801 CSE240 Lecture 16
201801 CSE240 Lecture 16201801 CSE240 Lecture 16
201801 CSE240 Lecture 16
Javier Gonzalez-Sanchez
 
201801 CSE240 Lecture 15
201801 CSE240 Lecture 15201801 CSE240 Lecture 15
201801 CSE240 Lecture 15
Javier Gonzalez-Sanchez
 
201801 CSE240 Lecture 11
201801 CSE240 Lecture 11201801 CSE240 Lecture 11
201801 CSE240 Lecture 11
Javier Gonzalez-Sanchez
 
201801 CSE240 Lecture 10
201801 CSE240 Lecture 10201801 CSE240 Lecture 10
201801 CSE240 Lecture 10
Javier Gonzalez-Sanchez
 
201801 CSE240 Lecture 09
201801 CSE240 Lecture 09201801 CSE240 Lecture 09
201801 CSE240 Lecture 09
Javier Gonzalez-Sanchez
 
201801 CSE240 Lecture 08
201801 CSE240 Lecture 08201801 CSE240 Lecture 08
201801 CSE240 Lecture 08
Javier Gonzalez-Sanchez
 

More from Javier Gonzalez-Sanchez (20)

201804 SER332 Lecture 01
201804 SER332 Lecture 01201804 SER332 Lecture 01
201804 SER332 Lecture 01
 
201801 SER332 Lecture 03
201801 SER332 Lecture 03201801 SER332 Lecture 03
201801 SER332 Lecture 03
 
201801 SER332 Lecture 04
201801 SER332 Lecture 04201801 SER332 Lecture 04
201801 SER332 Lecture 04
 
201801 SER332 Lecture 02
201801 SER332 Lecture 02201801 SER332 Lecture 02
201801 SER332 Lecture 02
 
201801 CSE240 Lecture 26
201801 CSE240 Lecture 26201801 CSE240 Lecture 26
201801 CSE240 Lecture 26
 
201801 CSE240 Lecture 25
201801 CSE240 Lecture 25201801 CSE240 Lecture 25
201801 CSE240 Lecture 25
 
201801 CSE240 Lecture 24
201801 CSE240 Lecture 24201801 CSE240 Lecture 24
201801 CSE240 Lecture 24
 
201801 CSE240 Lecture 23
201801 CSE240 Lecture 23201801 CSE240 Lecture 23
201801 CSE240 Lecture 23
 
201801 CSE240 Lecture 22
201801 CSE240 Lecture 22201801 CSE240 Lecture 22
201801 CSE240 Lecture 22
 
201801 CSE240 Lecture 21
201801 CSE240 Lecture 21201801 CSE240 Lecture 21
201801 CSE240 Lecture 21
 
201801 CSE240 Lecture 20
201801 CSE240 Lecture 20201801 CSE240 Lecture 20
201801 CSE240 Lecture 20
 
201801 CSE240 Lecture 19
201801 CSE240 Lecture 19201801 CSE240 Lecture 19
201801 CSE240 Lecture 19
 
201801 CSE240 Lecture 18
201801 CSE240 Lecture 18201801 CSE240 Lecture 18
201801 CSE240 Lecture 18
 
201801 CSE240 Lecture 17
201801 CSE240 Lecture 17201801 CSE240 Lecture 17
201801 CSE240 Lecture 17
 
201801 CSE240 Lecture 16
201801 CSE240 Lecture 16201801 CSE240 Lecture 16
201801 CSE240 Lecture 16
 
201801 CSE240 Lecture 15
201801 CSE240 Lecture 15201801 CSE240 Lecture 15
201801 CSE240 Lecture 15
 
201801 CSE240 Lecture 11
201801 CSE240 Lecture 11201801 CSE240 Lecture 11
201801 CSE240 Lecture 11
 
201801 CSE240 Lecture 10
201801 CSE240 Lecture 10201801 CSE240 Lecture 10
201801 CSE240 Lecture 10
 
201801 CSE240 Lecture 09
201801 CSE240 Lecture 09201801 CSE240 Lecture 09
201801 CSE240 Lecture 09
 
201801 CSE240 Lecture 08
201801 CSE240 Lecture 08201801 CSE240 Lecture 08
201801 CSE240 Lecture 08
 

Recently uploaded

Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
Matt Welsh
 
Designing for Privacy in Amazon Web Services
Designing for Privacy in Amazon Web ServicesDesigning for Privacy in Amazon Web Services
Designing for Privacy in Amazon Web Services
KrzysztofKkol1
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Globus
 
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Globus
 
Cyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdfCyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdf
Cyanic lab
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2
 
Software Testing Exam imp Ques Notes.pdf
Software Testing Exam imp Ques Notes.pdfSoftware Testing Exam imp Ques Notes.pdf
Software Testing Exam imp Ques Notes.pdf
MayankTawar1
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Shahin Sheidaei
 
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
Juraj Vysvader
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Natan Silnitsky
 
Strategies for Successful Data Migration Tools.pptx
Strategies for Successful Data Migration Tools.pptxStrategies for Successful Data Migration Tools.pptx
Strategies for Successful Data Migration Tools.pptx
varshanayak241
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
Max Andersen
 
Using IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New ZealandUsing IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New Zealand
IES VE
 
How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
wottaspaceseo
 
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Anthony Dahanne
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
abdulrafaychaudhry
 
Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with Platformless
WSO2
 
BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
Ortus Solutions, Corp
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke
 
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns
 

Recently uploaded (20)

Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
 
Designing for Privacy in Amazon Web Services
Designing for Privacy in Amazon Web ServicesDesigning for Privacy in Amazon Web Services
Designing for Privacy in Amazon Web Services
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
 
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...
 
Cyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdfCyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdf
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 
Software Testing Exam imp Ques Notes.pdf
Software Testing Exam imp Ques Notes.pdfSoftware Testing Exam imp Ques Notes.pdf
Software Testing Exam imp Ques Notes.pdf
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
 
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
 
Strategies for Successful Data Migration Tools.pptx
Strategies for Successful Data Migration Tools.pptxStrategies for Successful Data Migration Tools.pptx
Strategies for Successful Data Migration Tools.pptx
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
 
Using IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New ZealandUsing IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New Zealand
 
How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
 
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
 
Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with Platformless
 
BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
 
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology Solutions
 

201801 CSE240 Lecture 13

  • 1. CSE240 – Introduction to Programming Languages Lecture 13: Programming with C++ | memory management Javier Gonzalez-Sanchez javiergs@asu.edu javiergs.engineering.asu.edu Office Hours: By appointment
  • 2. Javier Gonzalez-Sanchez | CSE 240 | Fall 2017 | 2 Outline • static, • constructor and destructor, • new and delete
  • 4. Javier Gonzalez-Sanchez | CSE 240 | Fall 2017 | 4 Example 1. #include <iostream> 2. using namespace std; 3. class Foo { 4. public: 5. void counting(); 6. int getCounterB(); 7. static int counterA; 8. private: 9. int counterB; 10. }; 11. 12. // initial value to static member variable 13. int Foo::counterA = 0; 14. int counter = 0; A static variable is shared by all the objects from a class. Therefore, changes made to a static variable will impact all objects from the class
  • 5. Javier Gonzalez-Sanchez | CSE 240 | Fall 2017 | 5 1. #include <iostream> 2. using namespace std; 3. class Foo { 4. public: 5. void counting(); 6. int getCounterB(); 7. static int counterA; 8. private: 9. int counterB; 10. }; 11. 12. // initial value to static member variable 13. int Foo::counterA = 0; 14. int counter = 0; Example static versus global Variables static variables prevents functions outside the class to access the variable. As a global variable, all other functions can read/write it. A static variable is shared by all the objects from a class. Therefore, changes made to a static variable will impact all objects from the class
  • 6. Javier Gonzalez-Sanchez | CSE 240 | Fall 2017 | 6 Example 18. void Foo::counting() { // Set a new mil Time 19. counterA++; 20. counterB++; 21. } 22. int Foo::getCounterB() { 23. return counterB; 24. } 25. int main() { 26. Foo f1, f2, f3; 27. f1.counting(); 28. f2.counting(); 29. f2.counting(); 30. f3.counting(); 31. cout << Foo::counterA<<endl; 32. cout << f1.getCounterB()<<endl; 33. cout << Foo::counterA<<endl; 34. cout << f2.getCounterB()<<endl; 35. return 0; 36. } A static variable go out of scope only if the program terminated. And it can be used even without creating an object from the class.
  • 8. Javier Gonzalez-Sanchez | CSE 240 | Fall 2017 | 8 Constructor and Destructor A constructor in a class: • is a function whose name is same as the class name, and • is used to automatically initialize objects. A destructor in a class: • is a function whose name is same as the class name (with a ~ as prefix), and • is used to collect garbage.
  • 9. Javier Gonzalez-Sanchez | CSE 240 | Fall 2017 | 9 Constructor and Destructor #include <iostream> using namespace std; class Queue { private: int queue_size; protected: int *buffer; int front; int rear; public: Queue(); Queue(int n); ~Queue(); }; Queue::Queue() { // constructor cout << "constructor(void)"<<endl; // code... } Queue::Queue(int n) { // constructor overload cout << "constructor (int)"<<endl; // code... } Queue::~Queue(void) { cout << "destructor"<<endl; // code... } int main () { Queue myQueue1(500); Queue myQueue2; // more code... return 0; }
  • 10. Javier Gonzalez-Sanchez | CSE 240 | Fall 2017 | 10 Constructor and Destructor #include <iostream> using namespace std; class Queue { private: int queue_size; protected: int *buffer; int front; int rear; public: Queue(); Queue(int n); ~Queue(); }; Queue::Queue() { // constructor cout << "constructor(void)"<<endl; // code... } Queue::Queue(int n) { // constructor overload cout << "constructor (int)"<<endl; // code... } Queue::~Queue(void) { cout << "destructor"<<endl; // code... } int main () { Queue myQueue1(500); Queue myQueue2; // more code... return 0; }
  • 11. Javier Gonzalez-Sanchez | CSE 240 | Fall 2017 | 11 When is a destructor called? • When a local object (from stack) with block scope goes out of scope. • When a program (main function) ends and global or static objects exist (OS will collect them anyway). • When the destructor is explicitly called. • When the delete keyword is called.
  • 13. Javier Gonzalez-Sanchez | CSE 240 | Fall 2017 | 13 new and delete int main () { Queue myQueue2(500); // declare a pointer only Queue *myQueue; // reserve memory for an object myQueue = new Queue(500); // use the object myQueue->enqueue(23); myQueue2.enqueue(8); // delete will call ~Queue(); delete myQueue; ... delete myQueue2;//no needed }
  • 14. Javier Gonzalez-Sanchez | CSE 240 | Fall 2017 | 14 new and delete with constructors and destructors #include <iostream> using namespace std; class Queue { private: int queue_size; protected: int *buffer; int front; int rear; public: Queue(); Queue(int n); ~Queue(); }; Queue::Queue() { // constructor cout << "constructor(void)"<<endl; // code... buffer = NULL; } Queue::Queue(int n) { // constructor overload cout << "constructor (int)"<<endl; // code... buffer = new int[queue_size]; } Queue::~Queue(void) { cout << "destructor"<<endl; // code... delete [] buffer; } int main () { Queue myQueue1(500); Queue myQueue2; Queue *myQueue3 = new Queue(100); // more code... delete myQueue3; return 0; }
  • 15. Javier Gonzalez-Sanchez | CSE 240 | Fall 2017 | 15 Summary • If an object is on the stack, instead of on the heap, destructor will be called when the object goes out of scope. No delete operation is necessary. • All heap objects must be explicitly deleted before leaving the function, if they are no longer needed. • The function delete will implicitly call the destructor of the class, so that an object linked to a variable in the to-be-deleted object can be de-allocated too, i.e., using delete for variables created in the class (normally in the constructor).
  • 16. Javier Gonzalez-Sanchez | CSE 240 | Fall 2017 | 16 delete and Array of Objects #include <iostream> using namespace std; #define size 4 class arrayObject { public: int x; double y; arrayObject() { cout << "arrayObject's constructor called" << endl; } ~arrayObject() { cout << "arrayObject's destructor called" << endl; } }; int main() { arrayObject *p, *q; // declare two pointers p = new arrayObject[size]; // Create an array of objects for (q = p; q < p + size; q++) { // Initialize the objects q->x = 10; q->y = 1.5; } for (q = p; q < p + size; q++) { cout << "Element address " << q << " Element x value: " << q->x << endl; cout << "Element address " << q << " Element y value: " << q->y << endl; } delete[] p; return 0; }
  • 17. Javier Gonzalez-Sanchez | CSE 240 | Fall 2017 | 17 Summary • How do we delete an array of objects? We can use a loop to delete each element, • However, the language provides a library function to delete all the elements one by one without the user to explicitly use a loop: delete[] array;
  • 18. Javier Gonzalez-Sanchez | CSE 240 | Fall 2017 | 18 Summary Java • Primitive variables (int, float, boolean) use value type. • All other variables (string, array, user defined classes) use reference type. (Java uses automatic garbage collection). C++ • Both value and reference types exist: • if value semantics used then memory is allocated on stack or on static by compiler. Memory de-allocation is done automatically. • if reference semantics used (e.g. variable is a pointer to an object), then memory must be allocated explicitly using new and explicitly de-allocated using delete
  • 19. Javier Gonzalez-Sanchez | CSE 240 | Fall 2017 | 19 Summary // in C++ Report r; // an object is allocated to r Report *rp1, *rp2; // two pointers declared rp1 = &r; // rp1 points to object r rp2 = new Report(); // an object is created, linked to rp2 // .. delete rp2; // in Java Report r; // an reference is allocated r = new Report (); // an object is created and linked to r
  • 20. CSE240 – Introduction to Programming Languages Javier Gonzalez-Sanchez javiergs@asu.edu Fall 2017 Disclaimer. These slides can only be used as study material for the class CSE240 at ASU. They cannot be distributed or used for another purpose.