CS32 - Week 1. Umut Oztok. June 24, Umut Oztok CS32 - Week 1

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

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

Object-Oriented Principles and Practice / C++

CS201 Some Important Definitions

Implementing Abstractions

Programming, numerics and optimization

CS 101: Computer Programming and Utilization

COMP6771 Advanced C++ Programming

Special Member Functions

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

Object-Oriented Principles and Practice / C++

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

CSI33 Data Structures

More About Classes. Gaddis Ch. 14, CS 2308 :: Fall 2015 Molly O'Neil

CS32 - Week 4. Umut Oztok. Jul 15, Umut Oztok CS32 - Week 4

Written by John Bell for CS 342, Spring 2018

the gamedesigninitiative at cornell university Lecture 7 C++ Overview

Allocation & Efficiency Generic Containers Notes on Assignment 5

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

Object-Oriented Principles and Practice / C++

CPSC 427: Object-Oriented Programming

Announcements. Lecture 05a Header Classes. Midterm Format. Midterm Questions. More Midterm Stuff 9/19/17. Memory Management Strategy #0 (Review)

Assignment of Structs

Intermediate Programming & Design (C++) Classes in C++

Advanced Systems Programming

Memory Leak. C++: Memory Problems. Memory Leak. Memory Leak. Pointer Ownership. Memory Leak

ComS 228 Exam 1. September 27, 2004

Class Vector: Interface CSE 143. Dynamic Memory In Classes [Chapter 4, p ] Vector Implementation. Many Ways to Implement. Draw the picture!

The C++ Object Lifecycle. EECS 211 Winter 2019

CSCI 262 Data Structures. The Big 3. Copy Constructor. Destructor. Assignment Operator 3/4/ The Big 3

Object Oriented Programming COP3330 / CGS5409

Exception Safety. CS 311 Data Structures and Algorithms Lecture Slides Wednesday, October 28, Glenn G. Chappell. continued

Chapter 10 Introduction to Classes

Introduction to C++ Part II. Søren Debois. Department of Theoretical Computer Science IT University of Copenhagen. September 12th, 2005

CSE 303: Concepts and Tools for Software Development

Vector and Free Store (Pointers and Memory Allocation)

Vector and Free Store (Vectors and Arrays)

Chapter 10. Pointers and Dynamic Arrays. Copyright 2016 Pearson, Inc. All rights reserved.

QUIZ. What is wrong with this code that uses default arguments?

04-19 Discussion Notes

CS 11 C track: lecture 5

More class design with C++ Starting Savitch Chap. 11

The issues. Programming in C++ Common storage modes. Static storage in C++ Session 8 Memory Management

LECTURE 03 LINKED LIST

Link-Based Implementations. Chapter 4

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

! Determine if a number is odd or even. ! Determine if a number/character is in a range. ! Assign a category based on ranges (wind speed)

! Determine if a number is odd or even. ! Determine if a number/character is in a range. - 1 to 10 (inclusive) - between a and z (inclusive)

Praktikum: Entwicklung interaktiver eingebetteter Systeme

Section Handout #4: Classes, Pointers, and Dynamic Memory

Design Patterns in C++

a data type is Types

Next week s homework. Classes: Member functions. Member functions: Methods. Objects : Reminder. Objects : Reminder 3/6/2017

Object Oriented Software Design - II

C++ and OO. l C++ classes and OO. l More Examples. l HW2. C++ for C Programmers by Ira Pohl

Introducing C++ to Java Programmers

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

CSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010

Constructors for classes

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

CS 376b Computer Vision

From Java to C. Thanks to Randal E. Bryant and David R. O'Hallaron (Carnegie-Mellon University) for providing the basis for these slides

Software Design and Analysis for Engineers

Engineering Tools III: OOP in C++

lecture05: The Big Three

Memory Management: The Details

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

Object-Oriented Programming for Scientific Computing

Dynamic Allocation in C

class Polynomial { public: Polynomial(const string& N = "no name", const vector<int>& C = vector<int>());... };

Slide Set 14. for ENCM 339 Fall Steve Norman, PhD, PEng. Electrical & Computer Engineering Schulich School of Engineering University of Calgary

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

l Determine if a number is odd or even l Determine if a number/character is in a range - 1 to 10 (inclusive) - between a and z (inclusive)

Object-Oriented Programming

Constructor - example

CS32 Discussion Sec.on 1B Week 2. TA: Zhou Ren

GEA 2017, Week 4. February 21, 2017

Lecture 14: more class, C++ streams

Pointers and Arrays CS 201. This slide set covers pointers and arrays in C++. You should read Chapter 8 from your Deitel & Deitel book.

Dynamic Allocation in C


Midterm Review. PIC 10B Spring 2018

COMP6771 Advanced C++ Programming

A brief introduction to C++

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

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

Common Misunderstandings from Exam 1 Material

Classes: Member functions // classes example #include <iostream> using namespace std; Objects : Reminder. Member functions: Methods.

Concepts (this lecture) CSC 143. Classes with Dynamically Allocated Data. List of ints w/dups (cont.) Example: List of ints with dups.

CMSC 202 Section 010x Spring Justin Martineau, Tuesday 11:30am

Memory management COSC346

BBM 102 Introduction to Programming II Spring 2017

CS 161 Exam II Winter 2018 FORM 1

PIC 10B Lecture 1 Winter 2014 Homework Assignment #3

Name: Username: I. 10. Section: II. p p p III. p p p p Total 100. CMSC 202 Section 06 Fall 2015

Assignment of Objects

Outline. A C++ Linked Structure Class A C++ Linked List C++ Linked Dynamic Memory Errors In-class work. 1 Chapter 11: C++ Linked Structures

Lecture 15: Even more pointer stuff Virtual function table

Short Notes of CS201

C++: Const Function Overloading Constructors and Destructors Enumerations Assertions

Transcription:

CS32 - Week 1 Umut Oztok June 24, 2016

Administration Email:umut@ucla.edu Office hours: R 09:30am-12:30pm (BH 4663)

Constructor Special member function to initialize an instance of a class. Called whenever a class object is created. Has the same name as the class name. No return type, so returns nothing. Can have parameters. A constructor without any parameter is called default constructor. A class can have more than one constructor. But they cannot have the exact same parameters/types. Where to put its implementation? Inside the class definition (i.e., header file) Outside the class definition (i.e., cpp file)

Constructor Syntax of Constructor ClassName (); ClassName (Parameter p 1,..., Parameter p n ); class Circ { public: Circ(); //default constructor Circ(float x, float y, float r);... private: float m_x, m_y, m_r; ;

Destructor Special member function to de-initialize an instance of a class. Called whenever a class object is destroyed. No return type, so returns nothing. Cannot have parameters. A class can have at most one destructor. Where to put its implementation? Inside the class definition (i.e., header file) Outside the class definition (i.e., cpp file) When do you need it? Whenever you need to do any kind of maintenance before the object of the class is destroyed. Cleaning the memory allocated, closing a file, etc.

Destructor Syntax of Destructor ~ClassName (); DON T FORGET TILDE class Circ { public: Circ(); //default constructor Circ(float x, float y, float r); ~Circ(); //destructor... private: float m_x, m_y, m_r; ;

Dynamic Memory Usage Sometimes you won t know size of some variables before runtime. E.g., the memory needed may depend on user input. In such cases, you need to dynamically allocate memory. Also, whenever you are done with allocated memory, you should deallocate (free) it. Otherwise, you have memory leaks. In C++, we use operators new and delete for dynamic memory management. In Java, there is automatic garbage collection, so you don t need to worry about freeing stuff.

Dynamic Memory Allocation Syntax of new Operator pointer = new type; pointer = new type [number of elements]; int* foo; foo = new int [10]; Circ* a_ptr; a_ptr = new Circ(1,2,3); Circ* b_ptr; b_ptr = new Circ[10];

Dynamic Memory Deallocation Syntax of delete Operator delete pointer; delete[] pointer; int* foo; foo = new int [10]; delete[] foo; Circ* a_ptr; a_ptr = new Circ(1,2,3); delete a_ptr; Circ* b_ptr; b_ptr = new Circ[10]; delete[] b_ptr;

A Digression How do you check whether the new operation fails? That is, you try to allocate memory but OS cannot perform your request? int* foo; foo = new int [10]; if(foo == nullptr) { //failure else { //success How do you check whether the delete operation fails? That is, you try to free memory but OS cannot perform your request? You don t :)

Memory Allocation on Class Types What is really happening when the following code is executed? Circ* a_ptr; a_ptr = new Circ(1,2,3); delete a_ptr; new OS allocates memory. The constructor for class is called on this memory (if class has one). delete The destructor for class is called (if class has one). OS frees the memory.

Copy Constructor Special member function to initialize an instance of a class from an existing instance of the same class. In fact, it is nothing but a special constructor with a parameter of the class type. When is it being called? Creating an instance using another instance. Circ a(1,2,3); Circ b(a); Assigning an uninitialized instance with another one. Circ a(1,2,3); Circ b = a; Passing an argument by value. compute_area(circ a);

Copy Constructor In fact C++ always provides you with a default copy constructor, which basically copies all data members to be exactly the same. Why do we need our own copy constructor? Allocate dynamic memory. Open system resources, e.g., opening a file.

Copy Constructor Steps to implement a copy constructor: Determine how much memory is allocated in the existing variable. Allocate the same amount of memory for the new variable. Copy the content from the existing variable to new one.

Copy Constructor Syntax of Copy Constructor ClassName (const ClassName&); class Circ { public:... //copy constructor Circ(const Circ& oldvar) { m_x = oldvar.m_x; m_y = oldvar.m_y; m_r = oldvar.m_r;... private: float m_x, m_y, m_r;

Real use of Copy Constructor class Circles { private: int size; Circ* circles; public:... ~Circles() {delete[] circles; //destructor Circles(const Circles& src) { //copy constructor size = src.size; circles = new Circ[size]; for(int i=0; i<size; i++) circles[i] = src.circles[i]; ; If you rely on default constructor, you do shallow copy. But, you need deep copy. So, you should write your own default constructor.

Assignment Operator Assignment operator "=". C++ always provides you with a default assignment operator. However, default one copies all the data members. So, shallow copy again. As for copy constructor, when you allocate dynamic memory, you need to override default assignment operator.

Assignment Operator Steps to override an assignment operator. Free all dynamic memory used by target instance. Re-allocate memory for target instance. Copy all contents from source instance to target instance Return a reference to target instance. So, more work to do, compared to copy constructor. The reason is target instance is already initialized, so need to take care of allocated memory.

Assignment Operator Syntax of Assignment Operator ClassName& operator= (const ClassName& src); class Circ { public:... Circ& operator=(const Circ& src) { //assignment op. if(this!= &src) { m_x = src.m_x; m_y = src.my; m_r = src.m_r; return (*this); private: float m_x, m_y, m_r; ;

Real use of Assignment Operator class Circles { private: int size; Circ* circles; public:... //assignment operator Circles& operator=(const Circles& src) { if(this!= &src) { delete[] circles; size = src.size; circles = new Circ[size]; for(int i=0; i<size; i++) circles[i] = src.circles[i]; return (*this); ;

Copy Constructor vs. Assignment Operator // #1 main () { Circles a(4), b(5); b = a; // #3 Circles print() { Circles f(10); return f; // #2 main () { Circles c(4), d(c); c = d; main () { Circles g = print();

Assignment Operator Revisited Current approach: //assignment operator Circles& operator=(const Circles& src) { if(this!= &src) { delete[] circles; size = src.size; circles = new Circ[size]; for(int i=0; i<size; i++) circles[i] = src.circles[i]; return (*this); That is, delete memory first, reallocate it, and then copy. What is not good with that method? Code duplication (destructor and copy constructor).

Assignment Operator Revisited How to prevent code duplication? Copy-and-swap approach. Use swap function. void swap(circles& c) {... //exchange size and c.size (integers)... //exchange circles and c.circles (pointers)

Assignment Operator Revisited //assignment operator Circles& operator=(const Circles& src) { if(this!= &src) { Circles temp(src); swap(temp); return (*this); This provides you no code duplication: Deallocation - automatically done by destructor. Reallocation and copy - automatically done by copy constructor.

Slides Slides are available at http://www.cs.ucla.edu/~umut/cs32