Dynamic memory in class Ch 9, 11.4, 13.1 & Appendix F

Similar documents
Pointers Ch 9, 11.3 & 13.1

And Even More and More C++ Fundamentals of Computer Science

Object-Oriented Principles and Practice / C++

Intro to OOP Visibility/protection levels and constructors Friend, convert constructor, destructor Operator overloading a<=b a.

Pointers and memory Nov 17, Ch 9 & 13.1

Classes Ch

Ch02. True/False Indicate whether the statement is true or false.

Programming in C ++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

Lecture 13: more class, C++ memory management

Launchpad Lecture -10

Short Notes of CS201

Ch. 11: References & the Copy-Constructor. - continued -

CS201 - Introduction to Programming Glossary By

QUIZ Friends class Y;

17. Classes. Encapsulation: public / private. Member Functions: Declaration. Member Functions: Call. class rational { int n; int d; // INV: d!

THE NAME OF THE CONSTRUCTOR AND DESTRUCTOR(HAVING (~) BEFORE ITS NAME) FUNCTION MUST BE SAME AS THE NAME OF THE CLASS IN WHICH THEY ARE DECLARED.

Outline. Dynamic Memory Classes Dynamic Memory Errors In-class Work. 1 Chapter 10: C++ Dynamic Memory

Lecture 6 Dynamic Classes and the Law of the Big Three. Instructor: George Wolberg Department of Computer Science City College of New York

QUIZ. Write the following for the class Bar: Default constructor Constructor Copy-constructor Overloaded assignment oper. Is a destructor needed?

QUIZ on Ch.5. Why is it sometimes not a good idea to place the private part of the interface in a header file?

C++ Review. CptS 223 Advanced Data Structures. Larry Holder School of Electrical Engineering and Computer Science Washington State University

CS24 Week 3 Lecture 1

Object Oriented Programming COP3330 / CGS5409

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor.

G52CPP C++ Programming Lecture 13

Special Member Functions

OBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe

Overview of C Feabhas Ltd 2012

Special Member Functions. Compiler-Generated Destructor. Compiler-Generated Default Constructor. Special Member Functions

C++ (Non for C Programmer) (BT307) 40 Hours

Ch. 12: Operator Overloading

CMSC 132: Object-Oriented Programming II

CSCI 123 Introduction to Programming Concepts in C++

Date. Structures. Housekeeping. functions stacks Centro) Last Ctt odds tends

Recap: Pointers. int* int& *p &i &*&* ** * * * * IFMP 18, M. Schwerhoff

Software Engineering Concepts: Invariants Silently Written & Called Functions Simple Class Example

Object-Oriented Principles and Practice / C++

Determine a word is a palindrome? bool ispalindrome(string word, int front, int back) { Search if a number is in an array

Chapter 10 Introduction to Classes

See the CS 2704 notes on C++ Class Basics for more details and examples. Data Structures & OO Development I

Lecture 18 Tao Wang 1

Copying Data. Contents. Steven J. Zeil. November 13, Destructors 2

CPSC 427: Object-Oriented Programming

Fast Introduction to Object Oriented Programming and C++

Iterator: A way to sequentially access ( traverse ) each object in a container or collection. - Access is done as needed, not necessarily at once.

CSE 333. Lecture 11 - constructor insanity. Hal Perkins Paul G. Allen School of Computer Science & Engineering University of Washington

QUIZ. How could we disable the automatic creation of copyconstructors

CPSC 427: Object-Oriented Programming

Programming C++ Lecture 3. Howest, Fall 2012 Instructor: Dr. Jennifer B. Sartor

Inheritance Ch

Object-Oriented Programming

Paytm Programming Sample paper: 1) A copy constructor is called. a. when an object is returned by value

19. Classes. Encapsulation: public / private. Member Functions: Declaration. Member Functions: Call. class rational { int n; int d; // INV: d!

Announcements. Lecture 04b Header Classes. Review (again) Comments on PA1 & PA2. Warning about Arrays. Arrays 9/15/17

Constructors for classes

QUIZ. How could we disable the automatic creation of copyconstructors

Inheritance. OOP components. Another Example. Is a Vs Has a. Virtual Destructor rule. Virtual Functions 4/13/2017

Object Oriented Design

CMSC162 Intro to Algorithmic Design II Blaheta. Lab March 2019

Lecture 10: building large projects, beginning C++, C++ and structs

Object Oriented Programming COP3330 / CGS5409

Vector and Free Store (Vectors and Arrays)

CS304 Object Oriented Programming Final Term

QUIZ How do we implement run-time constants and. compile-time constants inside classes?

Midterm Review. PIC 10B Spring 2018

CSI33 Data Structures

static CS106L Spring 2009 Handout #21 May 12, 2009 Introduction

CSE 374 Programming Concepts & Tools. Hal Perkins Fall 2015 Lecture 19 Introduction to C++

Data Structures (list, dictionary, tuples, sets, strings)

An Introduction to C++

CSE 12, Week Six, Lecture Two Discussion: Getting started on hw7 & hw8

More C++ : Vectors, Classes, Inheritance, Templates

Project. C++: Smart Pointers. The Plan. Announcement. Memory Leak. Pointer Ownership. Today: STL 1 Wednesday: STL 2 Thursday: Smart Pointers

CSE 303: Concepts and Tools for Software Development

COSC 2P95. Procedural Abstraction. Week 3. Brock University. Brock University (Week 3) Procedural Abstraction 1 / 26

Composition I. composition is a way to combine or compose multiple classes together to create new class

Operator overloading. Conversions. friend. inline

QUIZ How do we implement run-time constants and. compile-time constants inside classes?

Classes and Objects. Class scope: - private members are only accessible by the class methods.

IS0020 Program Design and Software Tools Midterm, Fall, 2004

Lab 2: ADT Design & Implementation

1. Describe History of C++? 2. What is Dev. C++? 3. Why Use Dev. C++ instead of C++ DOS IDE?

More C++ : Vectors, Classes, Inheritance, Templates. with content from cplusplus.com, codeguru.com

21. Dynamic Datatypes and Memory Management

From Java to C++ From Java to C++ CSE250 Lecture Notes Weeks 1 2, part of 3. Kenneth W. Regan University at Buffalo (SUNY) September 10, 2009

explicit class and default definitions revision of SC22/WG21/N1582 =

21. Dynamic Datatypes and Memory Management

Class object initialization block destructor Class object

C++ Addendum: Inheritance of Special Member Functions. Constructors Destructor Construction and Destruction Order Assignment Operator

QUIZ. 1. Explain the meaning of the angle brackets in the declaration of v below:

EL2310 Scientific Programming

Constructors, Destructors, and Assignment Operators. Literature: Effective C++, Third Edition Chapter 2

Chapter 10 Pointers and Dynamic Arrays. GEDB030 Computer Programming for Engineers Fall 2017 Euiseong Seo

Vector and Free Store (Pointers and Memory Allocation)

Object Oriented Programming: Inheritance Polymorphism

(5 2) Introduction to Classes in C++ Instructor - Andrew S. O Fallon CptS 122 (February 7, 2018) Washington State University

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

Review and Recursion

Constructors and Destructors. OOC 4 th Sem, B Div Prof. Mouna M. Naravani

KOM3191 Object Oriented Programming Dr Muharrem Mercimek OPERATOR OVERLOADING. KOM3191 Object-Oriented Programming

Transcription:

Dynamic memory in class Ch 9, 11.4, 13.1 & Appendix F

Announcements Test next week (whole class) Covers: -Arrays -Functions -Recursion -Strings -File I/O

Highlights - Destructors - Copy constructors - operator= (basics)

Reasons why pointer Why use pointers? 1. Want to share variables (multiple names for the same box) 2. Dynamic sized arrays 3. Return arrays from functions (or any case of keep variable after scope ends) (DOWN WITH GLOBAL VARIABLES) 4. Store classes within themselves 5. Automatically initialize the number 4 above

Review: constructors Constructors are special functions that have the same name as the class Use a constructor to create an instance of the class (i.e. an object of the blueprint)

Constructors + dynamic What if we have a variable inside a class that uses dynamic memory? When do we stop using this class? What do we do if the int* was private? (See: classmemoryleak.cpp)

Constructors + dynamic Often, we might want a class to retain its information until the instance is deleted This means either: 1. Variable's scope ends (automatically deleted) oops out of scope = gone 2. You manually delete a dynamically created class with the delete command

Destructors Just as a constructor must run when a class is created... A destructor will always run when a class object/instance/variable is deleted Destructors (like constructors) must have the same name as the class, but with a ~: constructor destructor (See: classmemoryleakfixed.cpp)

Destructors A good analogy is file I/O, as there are 3 steps: 1. Open the file (read or write) 2. Use the file 3. Close the file The constructor is basically requiring step 1 to happen Do you want #3 to be automatic or explicit?

Destructors The benefit of destructors is the computer will run them for you when a variable ends This means you do not need to explicitly tell it when to delete the dynamic memory, simply how it should be done This fits better with classes as a blueprint that is used in other parts of the program (see: destructor.cpp)

const call-by-reference What is the difference between these two?

const call-by-reference What is the difference between these two? First one copies the values into x and y, thus these values exist in multiple places The second creates a link but does not let you modify the original (see: callbyvalue.cpp)

const call-by-reference Classes can be rather big, so in this case using const and '&' can save memory So a better way to write:... would be: (function definition the same) In fact, without & creates a copy, which is a new object and thus runs a constructor

Copy constructor There is actually a built-in copier (much like there is a built-in default constructor) This built-in copier makes the boxes hold identical values... but is this good enough? Issues with copying? (Hint: recent material) (See: copyissues.cpp)

Copy constructor Destructors are nice because they can automatically clean up memory However, you have to be careful that you do not cause things to delete twice This primarily happens when a copy is made poorly (a good copy is a deep copy ) i.e. all pointers should not be shared between copies, you recursively remake the pointers

Copy constructor To avoid double deleting (crashes program) or multiple pointers looking at the same spot... We have to redefine the copy constructor if we use dynamic memory The copy constructor is another special constructor (same name as class): copy constructor

Copy constructor In a copy constructor the const is optional, but the call-by-reference is necessary (the '&') Why?

Copy constructor In a copy constructor the const is optional, but the call-by-reference is necessary (the '&') Why? If you did not use a &, you would make a copy which would call a copy constructor... which would make a copy... which would call a copy constructor... which crashes your computer! (See: copyconstructor.cpp)

Copy constructor You will use a copy when: 1. You use an '=' sign when declaring a class 2. You call-by-value a class as an input to a function (i.e. do not use &) 3. You return an inputted class to function (Third the compiler sometimes skips) (See: placescopyconstructorruns.cpp)

Copy constructor The most common class we have used is the string class Lines like this were running copy constuctor: It actually converts lines like this: constructor (copy)

Operator = Ch 11.4 & Appendix F

Copy constructor: arrays How would you copy a dynamically created array inside a class? What if this was a normal array? (see: copyarray.cpp)

Copy constructor vs. '=' There is actually two ways in which you can use the '=' sign... 1. The copy constructor, if you ask for a box on that same line 2. Operator overload, if you already have a box when using '='; (See: copyvsequals.cpp)

Overload = What is the difference between copy and '='?

Overload = What is the difference between copy and '='? copy is a constructor, so it creates new boxes '=' is changing the value of an existing box (but same idea: not sharing the same address) The proper way to implement '=' is nuanced... see code comments if you care (See: overloadequals.cpp)

TLDR When using new in a constructor, you also should make: 1. Destructor 2. Copy constructor 3. Overload '=' operator Typically the built-in functions are not sufficient if you use a new or '*'

this Consider the following code: How do we write getx() and getme()?

this Q: It seems you should have information about yourself, but how do you access that? A: Inside every class, there is a this pointer, that points to yourself this points to itself (See: thisselfpointer.cpp)

typedef Side note: If you want to rename types, you can do that with typedef command: original name new synonymous name (See: redefiningtypes.cpp) If you have always been bothered that we use double instead of real, go ahead and fix it!