CS31 Discussion 1H Winter19: week 9

Slides:



Advertisements
Similar presentations
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.
Advertisements

Introduction to Programming Lecture 39. Copy Constructor.
A C LOSER L OOK AT C LASSES 1. A SSIGNING O BJECTS One object can be assigned to another provided that both objects are of the same type. It is not sufficient.
CS 31 Discussion, Week 9 Faisal Alquaddoomi, Office Hours: BH 2432, W 4:30-6:30pm, F 12:30-1:30pm.
Beginning C++ Through Game Programming, Second Edition by Michael Dawson.
OBJECT ORIENTED PROGRAMMING Instructor: Rashi Garg Coordinator: Gaurav Saxena.
1 Pointers A pointer variable holds an address We may add or subtract an integer to get a different address. Adding an integer k to a pointer p with base.
CS31: Introduction to Computer Science I Discussion 1A 5/28/2010 Sungwon Yang
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
More Classes in C++ Bryce Boe 2012/08/20 CS32, Summer 2012 B.
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.
Pointers review Let a variable aa be defined as ‘int *aa;’, what is stored in aa? Let a variable aa be defined as ‘int ** aa;’ what is stored in aa? Why.
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+
CS 11 C++ track: lecture 5 Today: Member initialization lists Linked lists friend functions.
Pointers and Dynamic Memory Allocation Copyright Kip Irvine 2003, all rights reserved. Revised 10/28/2003.
Object-Oriented Programming in C++
The Big Three Based on Weiss “Data Structures and algorithm Analysis CS240 Computer Science II.
CS-1030 Dr. Mark L. Hornick 1 Basic C++ State the difference between a function/class declaration and a function/class definition. Explain the purpose.
1 Classes II Chapter 7 2 Introduction Continued study of –classes –data abstraction Prepare for operator overloading in next chapter Work with strings.
Template Lecture 11 Course Name: High Level Programming Language Year : 2010.
Chapter 1 C++ Basics Review (Section 1.4). Classes Defines the organization of a data user-defined type. Members can be  Data  Functions/Methods Information.
CS162 - Topic #6 Lecture: Pointers and Dynamic Memory –Review –Dynamically allocating structures –Combining the notion of classes and pointers –Destructors.
CS32 Discussion Section 1B Week 2 TA: Hao Yu (Cody)
Dynamic Memory Management & Static Class Members Lecture No 7 Object Oriented Programming COMSATS Institute of Information Technology.
Yan Shi CS/SE 2630 Lecture Notes
Pointer to an Object Can define a pointer to an object:
Pointers and Dynamic Arrays
Overloading Operator MySting Example
classes and objects review
CMPE 135: Object-Oriented Analysis and Design October 17 Class Meeting
14.4 Copy Constructors.
Class: Special Topics Copy Constructors Static members Friends this
Dynamic Memory CSCE 121 J. Michael Moore.
Chapter 10: Pointers Starting Out with C++ Early Objects Ninth Edition
This pointer, Dynamic memory allocation, Constructors and Destructor
The dirty secrets of objects
group work #hifiTeam
Today’s Topic Dynamic allocation Slides for CS 31 discussion session
Pointers and References
Chapter 16-2 Linked Structures
Classes with Dynamically Allocated Data
Chapter 15 Pointers, Dynamic Data, and Reference Types
Pointers, Dynamic Data, and Reference Types
Constant pointers and pointers to constants
Dynamic Memory A whole heap of fun….
Chapter 15 Pointers, Dynamic Data, and Reference Types
Dynamic Memory A whole heap of fun….
Dynamic Memory A whole heap of fun….
Today’s Topic Const Ref:
9-10 Classes: A Deeper Look.
Destructor CSCE 121.
Passing Arguments and The Big 5
Computing and Statistical Data Analysis Lecture 6
Dynamic Memory A whole heap of fun….
Dynamic Memory.
Passing Arguments and The Big 5
COP 3330 Object-oriented Programming in C++
CS31 Discussion 1D Winter18: week 6
CS31 Discussion 1D Winter19: week 4
EECE.3220 Data Structures Instructor: Dr. Michael Geiger Spring 2019
CS31 Discussion 1H Fall18: week 6
CS31 Discussion 1H Fall18: week 9
CS 144 Advanced C++ Programming March 21 Class Meeting
EECE.3220 Data Structures Instructor: Dr. Michael Geiger Spring 2019
Dynamic Memory CSCE 121.
Pointers, Dynamic Data, and Reference Types
CS 144 Advanced C++ Programming April 30 Class Meeting
9-10 Classes: A Deeper Look.
Lesson 13 Pointers & Dynamic Memory
Presentation transcript:

CS31 Discussion 1H Winter19: week 9 TA: Behnam Shahbazi bshahbazi@cs.ucla.edu Credit to former TAs: Chelsea Ju Bo Jhang

What is “new” Dynamically allocate memory Step 1: allocate memory Step 2: return the memory address Don’t forget to return the memory delete operator Don’t lose the pointer, otherwise you will never be able to recycle the allocated memory!

Stack / heap

Stack / heap Local variables go here! Dynamic memory allocations go here!

Local variable v.s. dynamic allocation Local variables are easier to manage The last showing up variable is going recycled first Dynamic memory allocation A more flexible way to get available memory! There is no way to determine when an allocated memory piece is going to be freed. Developers need to explicitly say which memory have to be recycled. Memory fragmentation problem

An array of pointers Scorpion* objects[10]; nullptr nullptr nullptr

Accessing member operator Dot (.) operator Scorpion scor; scor.m_row = 3; Arrow (->) operator Scorpion *ptr = new Scorpion; ptr->m_row = 3; Just treat dot (.) and arrow (->) operator as ‘s

Constructor / destructor Constructor is for class (structure) initialization Destructor gives the victim a chance to say good bye to the main program before it gets recycled Usually we don’t need to override the default destructor, but if you dynamically allocate memory in constructor, this is the only chance you can free the allocated memory.

Class Destructor The destructor is called when an object is deleted It can’t have a return type (not even void) It can’t have any argument Ex: class Pet{ public: Pet(string nm, int initialHealth); void eat(int amt); void play(); string name() const; int health() const; bool alive() const; ~Pet(); private: string m_name; int m_health; }; Pet::~Pet(){ cout << name() << " is destroyed" << endl; }

Class Destructor Example 8: What is the output? class Pet{ public: Pet(string nm, int initialHealth); void eat(int amt); void play(); string name() const; int health() const; bool alive() const; ~Pet(); private: string m_name; int m_health; }; Pet::~Pet(){ cout << name() << " is destroyed" << endl; } int main(){ Pet* myPets[2]; myPets[0] = new Pet("Fluffy", 2); myPets[1] = new Pet("Frisky", 4); for (int k = 0; k < 2; k++){ cout << myPets[k] -> name() << " " << myPets[k] -> health() << endl; delete myPets[k]; }

Class Destructor Solution 8: What is the output? Fluffy 2 class Pet{ public: Pet(string nm, int initialHealth); void eat(int amt); void play(); string name() const; int health() const; bool alive() const; ~Pet(); private: string m_name; int m_health; }; Pet::~Pet(){ cout << name() << " is destroyed" << endl; } int main(){ Pet* myPets[2]; myPets[0] = new Pet("Fluffy", 2); myPets[1] = new Pet("Frisky", 4); for (int k = 0; k < 2; k++){ cout << myPets[k] -> name() << " " << myPets[k] -> health() << endl; delete myPets[k]; } Fluffy 2 Fluffy is destroyed Frisky 4 Frisky is destroyed

Class Destructor Example 9: What is the output? class Pet{ public: Pet(string nm, int initialHealth); void eat(int amt); void play(); string name() const; int health() const; bool alive() const; ~Pet(); private: string m_name; int m_health; }; Pet::~Pet(){ cout << name() << " is destroyed" << endl; } int main(){ Pet petA = Pet("Fluffly", 2); Pet *petB = new Pet("Frisky", 4); delete petB; }

Class Destructor Solution 9: What is the output? Frisky is destroyed class Pet{ public: Pet(string nm, int initialHealth); void eat(int amt); void play(); string name() const; int health() const; bool alive() const; ~Pet(); private: string m_name; int m_health; }; Pet::~Pet(){ cout << name() << " is destroyed" << endl; } int main(){ Pet petA = Pet("Fluffly", 2); Pet *petB = new Pet("Frisky", 4); delete petB; } Frisky is destroyed Fluffly is destroyed

this Pointer A special keyword that is usable within member functions It refers to the pointer that points to the calling object Ex: we can rewrite the member functions with this class Pet{ public: Pet(string nm, int initialHealth); void eat(int amt); void play(); string name() const; int health() const; bool alive() const; private: string m_name; int m_health; }; int main(){ Pet *myPet = new Pet("Fluffy",10); cout << myPet -> name() << endl; } void Pet::eat(int amt){ this -> m_health += amt; } void Pet::play(){ this -> m_health --; string Pet::name() const{ return this -> m_name; int Pet::health() const{ return this -> m_health; bool Pet::alive() const{ return this -> m_health > 0;

Dynamic Memory Allocation Memory Leak Not giving back the allocated memory (forgetting delete) It is not always obvious Example 3 int *p, *q; q = new int; p = new int; *p = 45; *q = 55; p = q;

Dynamic Memory Allocation Dangling Pointer Using a pointer to memory no longer allocated Example 4 int *p = new int; int *q; *p = 45; q = p; delete p; *q = 55;

Example 6 Q: Which member functions/variables calls are valid? class Zurt{ public: Zurt() { m_health = m_row = m_col = 0; } Zurt(int health, int r,int c) { m_health = health; m_row = r; m_col = c; int health() const { return m_health; int row() const { return m_row; int col() const { return m_col; void setHealth(int health) { void setRow(int r) { void setCol(int c) { private: int m_health, m_row, m_col; }; int main(){ Zurt z(100,1,1); const Zurt* zp = &z; zp->Zurt(); // (a) zp->Zurt(100,1,2); // (b) int h = zp->health(); // (c) int r = zp->row(); // (d) int c = zp->col(); // (e) zp->setHealth(50); // (f) zp-> setRow(2); // (g) zp->setCol(2); // (h) zp->m_col = 5; // (i) return 0; } Q: Which member functions/variables calls are valid?

Solution 6 Q: Which member functions/variables calls are valid? class Zurt{ public: Zurt() { m_health = m_row = m_col = 0; } Zurt(int health, int r,int c) { m_health = health; m_row = r; m_col = c; int health() const { return m_health; int row() const { return m_row; int col() const { return m_col; void setHealth(int health) { void setRow(int r) { void setCol(int c) { private: int m_health, m_row, m_col; }; int main(){ Zurt z(100,1,1); const Zurt* zp = &z; zp->Zurt(); // (a) zp->Zurt(100,1,2); // (b) int h = zp->health(); // (c) int r = zp->row(); // (d) int c = zp->col(); // (e) zp->setHealth(50); // (f) zp-> setRow(2); // (g) zp->setCol(2); // (h) zp->m_col = 5; // (i) return 0; } To construct an object using a pointer: new Ex: zp -> new Zurt(); Since zp is a pointer to constant data, we can’t modify the data content through zp Const qualifier is not allowed on a constructor Q: Which member functions/variables calls are valid? (c) (d) (e)

Example 7 Q: Which member functions/variables calls are valid? class Zurt{ public: Zurt() { m_health = m_row = m_col = 0; } Zurt(int health, int r,int c) { m_health = health; m_row = r; m_col = c; int health() const { return m_health; int row() const { return m_row; int col() const { return m_col; void setHealth(int health) { void setRow(int r) { void setCol(int c) { private: int m_health, m_row, m_col; }; int main(){ Zurt z(100,1,1); Zurt* zp = &z; zp->Zurt(); // (a) zp->Zurt(100,1,2); // (b) int h = zp->health(); // (c) int r = zp->row(); // (d) int c = zp->col(); // (e) zp->setHealth(50); // (f) zp-> setRow(2); // (g) zp->setCol(2); // (h) zp->m_col = 5; // (i) return 0; } Q: Which member functions/variables calls are valid?

Solution 7 Q: Which member functions/variables calls are valid? class Zurt{ public: Zurt() { m_health = m_row = m_col = 0; } Zurt(int health, int r,int c) { m_health = health; m_row = r; m_col = c; int health() const { return m_health; int row() const { return m_row; int col() const { return m_col; void setHealth(int health) { void setRow(int r) { void setCol(int c) { private: int m_health, m_row, m_col; }; int main(){ Zurt z(100,1,1); Zurt* zp = &z; zp->Zurt(); // (a) zp->Zurt(100,1,2); // (b) int h = zp->health(); // (c) int r = zp->row(); // (d) int c = zp->col(); // (e) zp->setHealth(50); // (f) zp-> setRow(2); // (g) zp->setCol(2); // (h) zp->m_col = 5; // (i) return 0; } Q: Which member functions/variables calls are valid? (c) (d) (e) (f) (g) (h)

Operator Overloading Operator overloading is the act of providing user-defined behavior for different C++ operators. Object 3 = Obj1 + Obj2 Obj1 = Obj2

Operator Overloading - Exmaple

Operator Overloading - print Friend filestream