C++ Class Details, Heap

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

C++ Constructor Insanity

C++ Constructor Insanity

C++ Templates. CSE 333 Autumn 2018

C++ Inheritance II, Casting

C++ Smart Pointers. CSE 333 Autumn 2018

C++ Inheritance I. CSE 333 Autumn 2018

C++ Intro. CSE 333 Autumn 2018

Final C Details. CSE 333 Autumn 2018

Server-side Programming

Pointers, Pointers, Pointers

Data Structures and Modules

Client-side Networking

Concurrency: Threads. CSE 333 Autumn 2018

Introduction to Concurrency

Final C Details. CSE 333 Winter Teaching Assistants: Alexey Beall Renshu Gu Harshita Neti David Porter Forrest Timour Soumya Vasisht

CSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010

CSE 303: Concepts and Tools for Software Development

C++ Standard Template Library

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

04-19 Discussion Notes

CSE 333. Lecture 10 - references, const, classes. Hal Perkins Paul G. Allen School of Computer Science & Engineering University of Washington

Lecture 14. No in-class files today. Homework 7 (due on Wednesday) and Project 3 (due in 10 days) posted. Questions?

C++ PROGRAMMING LANGUAGE: DYNAMIC MEMORY ALLOCATION AND EXCEPTION IN C++. CAAM 519, CHAPTER 15

CSE 333 Midterm Exam Nov. 3, 2017 Sample Solution

CSI33 Data Structures

C++ Mini-Course. Part 1: Mechanics Part 2: Basics Part 3: References Part 4: Const Part 5: Inheritance Part 6: Libraries Part 7: Conclusion. C Rulez!

Pointers, Dynamic Data, and Reference Types

CS3157: Advanced Programming. Outline

C++ Inheritance II, Casting

Lecture 8: Object-Oriented Programming (OOP) EE3490E: Programming S1 2017/2018 Dr. Đào Trung Kiên Hanoi Univ. of Science and Technology

C++ Mini-Course. Part 1: Mechanics Part 2: Basics Part 3: References Part 4: Const Part 5: Inheritance Part 6: Libraries Part 7: Conclusion. C Rulez!

12/2/2009. The plan. References. References vs. pointers. Reference parameters. const and references. HW7 is out; new PM due date Finish last lecture

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

G52CPP C++ Programming Lecture 13

EL2310 Scientific Programming

Short Notes of CS201

the gamedesigninitiative at cornell university Lecture 7 C++ Overview

CS201 - Introduction to Programming Glossary By

Object Oriented Software Design II

2 ADT Programming User-defined abstract data types

Financial computing with C++

Classes in C++98 and C++11

CSE 333 Midterm Exam July 24, Name UW ID#

PIC 10A Pointers, Arrays, and Dynamic Memory Allocation. Ernest Ryu UCLA Mathematics

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

EL2310 Scientific Programming

Intermediate Programming, Spring 2017*

CPSC 427: Object-Oriented Programming

CSE 333 Lecture smart pointers

Lecture 7. Log into Linux New documents posted to course webpage

PIC 10A Objects/Classes

04-17 Discussion Notes

Lecture 13: more class, C++ memory management

QUIZ Friends class Y;

C++ Programming Lecture 4 Software Engineering Group

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

Fast Introduction to Object Oriented Programming and C++

CS201 Some Important Definitions

COMP 2355 Introduction to Systems Programming

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

G52CPP C++ Programming Lecture 14. Dr Jason Atkin

CSE 333. Lecture 9 - intro to C++ Hal Perkins Department of Computer Science & Engineering University of Washington

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

CS201- Introduction to Programming Current Quizzes

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

Exercise 1.1 Hello world

CSE 333 Midterm Exam Nov. 3, Name UW ID#

COMP6771 Advanced C++ Programming

CS24 Week 3 Lecture 1

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

Announcements. CSCI 334: Principles of Programming Languages. Lecture 18: C/C++ Announcements. Announcements. Instructor: Dan Barowy

EL2310 Scientific Programming

Starting Savitch Chapter 10. A class is a data type whose variables are objects. Some pre-defined classes in C++ include int,

Object-Oriented Principles and Practice / C++

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

CSE 333 Midterm Exam July 24, 2017 Sample Solution

The University of Nottingham

Financial computing with C++

Basic Types, Variables, Literals, Constants

EL2310 Scientific Programming

CSE 333 Lecture 9 - intro to C++

CSCI 262 Data Structures. Arrays and Pointers. Arrays. Arrays and Pointers 2/6/2018 POINTER ARITHMETIC

Object-Oriented Programming for Scientific Computing

pointers & references

C++_ MARKS 40 MIN

Lecture 14: more class, C++ streams

Pointers and References

CS11 Intro C++ Spring 2018 Lecture 3

CSE 333 Midterm Exam 7/27/15 Sample Solution

CS11 Intro C++ Spring 2018 Lecture 1

Vectors of Pointers to Objects. Vectors of Objects. Vectors of unique ptrs C++11. Arrays of Objects

Fundamentals of Programming. Lecture 19 Hamed Rasifard

CPSC 427: Object-Oriented Programming

CS 61C: Great Ideas in Computer Architecture. Lecture 3: Pointers. Bernhard Boser & Randy Katz

Programming in C and C++

Pointers. Developed By Ms. K.M.Sanghavi

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

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

Suppose we find the following function in a file: int Abc::xyz(int z) { return 2 * z + 1; }

Transcription:

C++ Class Details, Heap CSE 333 Autumn 2018 Instructor: Hal Perkins Teaching Assistants: Tarkan Al-Kazily Renshu Gu Trais McGaha Harshita Neti Thai Pham Forrest Timour Soumya Vasisht Yifan Xu

Administriia Yet another exercise released today, due Wednesday Rework exercise 10 but with dynamic memory this time Fine to use ex10 solution as a starting point for ex11 No new exercise after that until weekend (i.e., nothing due Friday) because Homework 2 due Thursday night File system crawler, indexer, and search engine 2

Lecture Outline Class Details Filling in some gaps from last time Using the Heap new / delete / delete[] 3

Rule of Three If you define any of: 1) Destructor 2) Copy Constructor 3) Assignment (operator=) Then you should normally define all three Can explicitly ask for default synthesized ersions (C++11): class Point { public: Point() = default; // the default ctor ~Point() = default; // the default dtor Point(const Point& copyme) = default; // the default cctor Point& operator=(const Point& rhs) = default; // the default "=" 4

Dealing with the Insanity C++ style guide tip: If possible, disable the copy constructor and assignment operator by declaring as priate and not defining them (pre-c++11) Point.h class Point { public: Point(const int x, const int y) : x_(x), y_(y) { } // ctor priate: Point(const Point& copyme); // disable cctor (no def.) Point& operator=(const Point& rhs); // disable "=" (no def.) }; // class Point Point w; // compiler error (no default constructor) Point x(1, 2); // OK! Point y = w; // compiler error (no copy constructor) y = x; // compiler error (no assignment operator) 5

Disabling in C++11 C++11 add new syntax to do this directly This is the better choice in C++11 code class Point { public: Point(const int x, const int y) : x_(x), y_(y) { } // ctor Point(const Point& copyme) = delete; // declare cctor and "=" as Point& operator=(const Point& rhs) = delete; // as deleted (C++11) priate: }; // class Point Point w; // compiler error (no default constructor) Point x(1, 2); // OK! Point y = w; // compiler error (no copy constructor) y = x; // compiler error (no assignment operator) Point_2011.h 6

CopyFrom C++11 style guide tip: If you disable them, then you instead may want an explicit CopyFrom function Point.h class Point { public: Point(const int x, const int y) : x_(x), y_(y) { } // ctor oid CopyFrom(const Point& copy_from_me); Point(Point& copyme) = delete; // disable cctor Point& operator=(point& rhs) = delete; // disable "=" priate: }; // class Point Point x(1, 2); // OK Point y(3, 4); // OK x.copyfrom(y); // OK sanepoint.cc 7

struct s. class In C, a struct can only contain data fields No methods and all fields are always accessible In C++, struct and class are (nearly) the same! Both can hae methods and member isibility (public/priate/protected) Minor difference: members are default public in a struct and default priate in a class Common style/usage conention: Use struct for simple bundles of data Use class for abstractions with data + functions 8

Access Control Access modifiers for members: public: accessible to all parts of the program priate: accessible to the member functions of the class Priate to class, not object instances protected: accessible to the member functions of the class and any deried classes (subclasses more to come, later) Reminders: Access modifiers apply to all members that follow until another access modifier is reached If no access modifier is specified, struct members default to public and class members default to priate 9

Nonmember Functions Nonmember functions are just normal functions that happen to use our class Called like a regular function instead of as a member of a class object instance This gets a little weird when we talk about operators These do not hae access to the class priate members Useful nonmember functions often included as part of interface Declaration goes in header file, but outside of class definition 10

friend Nonmember Functions A class can gie a nonmember function (or class) access to its nonpublic members by declaring it as a friend within its definition friend function is not a class member, but has access priileges as if it were friend functions are usually unnecessary if your class includes appropriate getter public functions Complex.h class Complex { friend std::istream& operator>>(std::istream& in, Complex& a); }; // class Complex std::istream& operator>>(std::istream& in, Complex& a) { } Complex.cc 11

Namespaces Each namespace is a separate scope Useful for aoiding symbol collisions! Namespace definition: namespace name { // declarations go here } Creates a new namespace name if it did not exist, otherwise adds to the existing namespace (!) This means that namespaces can be defined in multiple source files Definitions can appear outside of the namespace definition 12

Classes s. Namespaces They look ery similar, but classes are not namespaces: There are no instances/objects of a namespace; a namespace is just a group of logically-related things (classes, functions, etc.) To access a member of a namespace, you must use the fully qualified name (i.e. nsp_name::member) Unless you are using that namespace You only used the fully qualified name of a class member when you are defining it outside of the scope of the class definition 13

Lecture Outline Class Details Filling in some gaps from last time Using the Heap new / delete / delete[] 14

C++11 nullptr C and C++ hae long used NULL as a pointer alue that references nothing C++11 introduced a new literal for this: nullptr New resered word Interchangeable with NULL for all practical purposes, but it has type T* for any/eery T, and is not an integer alue Aoids funny edge cases (see C++ references for details) Still can conert to/from integer 0 for tests, assignment, etc. Adice: prefer nullptr in C++11 code Though NULL will also be around for a long, long time 15

new/delete To allocate on the heap using C++, you use the new keyword instead of malloc() from stdlib.h You can use new to allocate an object (e.g. new Point) You can use new to allocate a primitie type (e.g. new int) To deallocate a heap-allocated object or primitie, use the delete keyword instead of free() from stdlib.h Don t mix and match! Neer free() something allocated with new Neer delete something allocated with malloc() Careful if you re using a legacy C code library or module in C++ 16

new/delete Example int* AllocateInt(int x) { int* heapy_int = new int; *heapy_int = x; return heapy_int; } #include "Point.h" using namespace std; Point* AllocatePoint(int x, int y) { Point* heapy_pt = new Point(x,y); return heapy_pt; } heappoint.cc // definitions of AllocateInt() and AllocatePoint() int main() { Point* x = AllocatePoint(1, 2); int* y = AllocateInt(3); cout << "x's x_ coord: " << x->get_x() << endl; cout << "y: " << y << ", *y: " << *y << endl; } delete x; delete y; return 0; 17

Dynamically Allocated Arrays To dynamically allocate an array: Default initialize: type* name = new type[size]; To dynamically deallocate an array: Use delete[] name; name; It is an incorrect to use delete name; on an array The compiler probably won t catch this, though (!) because it can t tell if it was allocated with new type[size]; or new type; Especially inside a function where a pointer parameter could point to a single item or an array and there s no way to tell which! Result of wrong delete is undefined behaior 18

Arrays Example (primitie) #include "Point.h" using namespace std; arrays.cc int main() { int stack_int; int* heap_int = new int; int* heap_init_int = new int(12); int stack_arr[10]; int* heap_arr = new int[10]; int* heap_init_arr = new int[10](); // default init int* heap_init_error = new int[10](12); // bad syntax delete heap_int; // delete heap_init_int; // delete heap_arr; // delete[] heap_init_arr; // } return 0; 19

Arrays Example (class objects) #include "Point.h" using namespace std; arrays.cc int main() { Point stack_point(1, 2); Point* heap_point = new Point(1, 2); Point* err_pt_arr = new Point[10]; // no Point() ctor Point* err2_pt_arr = new Point[10](1,2); // bad syntax delete heap_point; } return 0; 20

malloc s. new malloc() new What is it? a function an operator or keyword How often used (in C)? often neer How often used (in C++)? rarely often Allocated memory for Returns anything a oid* (should be cast) arrays, structs, objects, primities appropriate pointer type (doesn t need a cast) When out of memory returns NULL throws an exception Deallocating free() delete or delete[] 21

Heap Member Example Let s build a class to simulate some of the functionality of the C++ string Internal representation: c-string to hold characters What might we want to implement in the class? 23

Str Class Walkthrough #include <iostream> using namespace std; Str.h class Str { public: Str(); // default ctor Str(const char* s); // c-string ctor Str(const Str& s); // copy ctor ~Str(); // dtor int length() const; // return length of string char* c_str() const; // return a copy of st_ oid append(const Str& s); Str& operator=(const Str& s); // string assignment friend std::ostream& operator<<(std::ostream& out, const Str& s); priate: char* st_; // c-string on heap (terminated by '\0') }; // class Str 24

Str Example Walkthrough See: Str.h Str.cc strtest.cc (Look carefully at assignment operator= self-assignment test is especially important here) 26

Extra Exercise #1 Write a C++ function that: Uses new to dynamically allocate an array of strings and uses delete[] to free it Uses new to dynamically allocate an array of pointers to strings Assign each entry of the array to a string allocated using new Cleans up before exiting Use delete to delete each allocated string Uses delete[] to delete the string pointer array (whew!) 27