Discussion 1E. Jie(Jay) Wang Week 10 Dec.2

Similar documents
CS31 Discussion 1E. Jie(Jay) Wang Week3 Oct.12

CS31 Discussion. Jie(Jay) Wang Week8 Nov.18

CS 31 Discussion ABDULLAH-AL-ZUBAER IMRAN WEEK 6: C-STRINGS, STRUCT, CLASS AND PROJECT4

CS31 Discussion 1E. Jie(Jay) Wang Week5 Oct.27

CS31 Discussion. Jie(Jay) Wang Week6 Nov.4

Consider the above code. This code compiles and runs, but has an error. Can you tell what the error is?

Discussion 1H Notes (Week 4, April 22) TA: Brian Choi Section Webpage:

CS31 Discussion 1E. Jie(Jay) Wang Week1 Sept. 30

CS201- Introduction to Programming Current Quizzes

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

Pointers, Dynamic Data, and Reference Types

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

CS 31 Review Sheet. Tau Beta Pi - Boelter Basics 2. 2 Working with Decimals 2. 4 Operators 3. 6 Constants 3.

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

Separate Compilation Model

CS 31 Discussion 1A, Week 8. Zengwen Yuan (zyuan [at] cs.ucla.edu) Humanities A65, Friday 10:00 11:50 a.m.

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

OBJECT ORIENTED PROGRAMMING

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

Input And Output of C++

Homework #3 CS2255 Fall 2012

THE GOOD, BAD AND UGLY ABOUT POINTERS. Problem Solving with Computers-I

CS201 Some Important Definitions

Agenda. The main body and cout. Fundamental data types. Declarations and definitions. Control structures

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 1/9/ Review. Here s a simple C++ program:

cout << "How many numbers would you like to type? "; cin >> memsize; p = new int[memsize];

The C++ Language. Arizona State University 1

6. Pointers, Structs, and Arrays. March 14 & 15, 2011

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 8/19/ Review. Here s a simple C++ program:

Discussion 1H Notes (Week 3, April 14) TA: Brian Choi Section Webpage:

Fast Introduction to Object Oriented Programming and C++

Getting started with C++ (Part 2)

FORM 1 (Please put your name and section number (001/10am or 002/2pm) on the scantron!!!!) CS 161 Exam II: True (A)/False(B) (2 pts each):

Short Notes of CS201

Name. CPTR246 Spring '17 (100 total points) Exam 2

Dynamic Memory Allocation

CS201 - Introduction to Programming Glossary By

Pointers. Developed By Ms. K.M.Sanghavi

05-01 Discussion Notes

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Chapter 2: Basic Elements of C++

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

6. Pointers, Structs, and Arrays. 1. Juli 2011

Week 5. Muhao Chen.

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

CPSC 427: Object-Oriented Programming

CPSC 427: Object-Oriented Programming

CS31 Discussion 1E Spring 17 : week 08

CS 376b Computer Vision

Lecture 2, September 4

377 Student Guide to C++

Assignment 5: MyString COP3330 Fall 2017

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

CS24 Week 3 Lecture 1

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)

Discussion 1H Notes (Week 2, 4/8) TA: Brian Choi Section Webpage:

COEN244: Class & function templates

Type Aliases. Examples: using newtype = existingtype; // C++11 typedef existingtype newtype; // equivalent, still works

Object Oriented Programming COP3330 / CGS5409

Intermediate Programming, Spring 2017*

04-17 Discussion Notes

Structured Data. CIS 15 : Spring 2007

Introduction to Algorithms and Data Structures. Lecture 6 - Stringing Along - Character and String Manipulation

Scope. Scope is such an important thing that we ll review what we know about scope now:

CS201 Latest Solved MCQs

dynamically allocated memory char* x = new char; int* x = new int[n]; ???...?

Introduction to C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts

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

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

CE221 Programming in C++ Part 1 Introduction

Pointers. 1 Background. 1.1 Variables and Memory. 1.2 Motivating Pointers Massachusetts Institute of Technology


Object Reference and Memory Allocation. Questions:

Character Functions & Manipulators Arrays in C++ CS 16: Solving Problems with Computers I Lecture #10

COMP 2355 Introduction to Systems Programming

Vector and Free Store (Vectors and Arrays)

Chapter 2. Procedural Programming

Arrays. Returning arrays Pointers Dynamic arrays Smart pointers Vectors

C++ basics Getting started with, and Data Types.

Quiz Start Time: 09:34 PM Time Left 82 sec(s)

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

The C++ Object Lifecycle. EECS 211 Winter 2019

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

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

Principles of Programming Pointers, Dynamic Memory Allocation, Character Arrays, and Buffer Overruns

Written by John Bell for CS 342, Spring 2018

G52CPP C++ Programming Lecture 20

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

Basic program The following is a basic program in C++; Basic C++ Source Code Compiler Object Code Linker (with libraries) Executable

Please refer to the turn-in procedure document on the website for instructions on the turn-in procedure.

CS 103 Lab - Party Like A Char Star

C++ ARRAYS POINTERS POINTER ARITHMETIC. Problem Solving with Computers-I

Bruce Merry. IOI Training Dec 2013

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

WHAT POINTERS REALLY ARE

Lecture 10. To use try, throw, and catch Constructors and destructors Standard exception hierarchy new failures

Linked List using a Sentinel

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

a data type is Types

CMSC 202 Midterm Exam 1 Fall 2015

Transcription:

Discussion 1E Jie(Jay) Wang Week 10 Dec.2

Outline Dynamic memory allocation Class Final Review

Dynamic Allocation of Memory Recall int len = 100; double arr[len]; // error! What if I need to compute the size on-the-fly, and allocate the exact amount of memory for the array? int len = 100; double *arr = new double[len]; Syntax <type>* <name> = new <type>(parameter1, parameter2,...);

Dynamic Allocation of Memory int *func(); int main() { int *p = func(); return 0; int *func() { int arr[10]; return arr; arr func() main() Some data

Dynamic Allocation of Memory int *func(); int main() { int *p = func(); return 0; int *func() { int arr[10]; return arr; p??? main() Some data

Dynamic Allocation of Memory int main() { int *p = func(); delete[] p; return 0; int* func() { int* arr = new int[10]; return arr; arr heap main() Some data

Dynamic Allocation of Memory int main() { int *p = func(); delete[] p; return 0; int* func() { int* arr = new int[10]; return arr; p heap main() Some data

Stack vs. Heap Stack Local variables, functions, function arguments, etc. arr func() Variables in the stack vanish when outside the scope. main() Some data Heap arr heap Dynamically allocated memory reserved by the programmer Variables in the heap remain until you use delete main() to explicitly destroy them. Some data

Stack vs. Heap Programmers need to deallocate the memory by themselves!

Memory Leak What happens here? int *p; p = new int[10]; p = new int[8]; There is no way to access him anymore heap p A simple rule to remember: For each new statement, there should be one delete statement.

Memory Leak int *p = new int; delete p; int *p = new int[2]; delete[] p; int *parr[10]; for (int i = 0; i < 10; i++) parr[i] = new int; delete[] parr;

Memory Leak int *p = new int; delete p; int *p = new int[2]; delete[] p; int *parr[10]; for (int i = 0; i < 10; i++) parr[i] = new int; for (int i = 0; i < 10; i++) delete parr[i];

Class A class is a construct used to group related fields (variables) and methods (functions). class Cat { int m_age; void meow(); ; Cat meowth; One can access these members by using a dot. meowth.m_age meowth.meow()

Class member functions Two ways to define the member functions class Cat { int m_age; void meow() { cout << "Meow~" << endl; ; ; Scope resolution operator void Cat::meow() { cout << "Meow~" << endl; ; 1. Inside the class definition 2. outside of the class definition

Class access specifiers The output of this code? class Cat { int m_age; void meow() { cout << "Meow~" << endl; ; ; int main(){ Cat meowth; meowth.m_age = 3; meowth.meow(); The class members have the private access specifier by default and cannot be accessed by an outside class or function. class Cat { public: int m_age; void meow() { cout << "Meow~" << endl; ; ;

Class access specifiers meowth.m_age = -3; class Cat { Public members Private members int main(){ Cat meowth; meowth.m_age = 3; meowth.meow(); public: void meow() { cout << "Meow~" << endl; ; private: int m_age; ;

Class Accessors class Cat { public: int age(); void meow(); private: int m_age; ; int Cat::age() { return m_age; Modifiers (mutators) class Cat { public: int age(); void setage(int newage); void meow(); private: int m_age; ; void Cat::setAge(int newage) { m_age = newage;

Class vs. Structs Technically, the only difference between a class and a struct is the default access specifier. By convention, we use structs to represent simple collections of data and classes to represent complex objects. This comes from C, which has only structs and no member functions.

Class - Constructors A constructor is a member function that has the same name as the class, no return type, and automatically performs initialization when we declare an object: class Cat { public: Cat(); int age(); void meow(); private: int m_age; ; Cat::Cat() { setage(0); cout << "A cat is born" << endl; When a constructor has no arguments, it is called the default constructor. The compiler generates an empty one by default. Cat kitty; // uses default constructor -- Cat() Cat *p1 = new Cat; // uses Cat() Cat *p2 = new Cat(); // uses Cat()

Class - Constructors We can also create multiple constructors for a class by overloading it. class Cat { public: Cat(); // default constructor Cat(int initage); // constructor with an initial age void meow(); int age(); void setage(int newage); private: int m_age; ; Cat::Cat(int initage) { Cat(); // I can call the default constructor, setage(initage); // and then set the age to initage Cat kitty1(3);

Class - Constructors Using initialization lists to initialize fields class Cat { public: Cat(); int age(); void setage(int newage); private: int m_age; int m_weight; int m_gender; ; Cat::Cat(): m_age(0), m_weight(10), m_gender(1) { /* some code */

Class - Constructors Dynamic allocation Cat *pkitty = new Cat(); Cat *pkitty2 = new Cat(10); pkitty->meow() (*pkitty).meow()

Class - Constructors Can this compile? If so, what s the output? #include<iostream> using namespace std; class Cat { public: Cat(int initage); int age(); void setage(int newage); private: int m_age; ; Cat::Cat(int initage) { setage(initage); int main(){ Cat meowth; Cat meowth1(2); If we declare a constructor, the compiler will no longer generate a default constructor.

Class - Constructors Can this compile? If so, what s the output? #include<iostream> using namespace std; class Cat { public: Cat(int initage); int age(); void setage(int newage); private: int m_age; ; Cat::Cat(int initage) { setage(initage); int Cat::age(){ return m_age; void Cat::setAge(int newage){ m_age = newage; class Person { private: Cat pet; ; int main(){ Person Mary;

Class - Constructors A fixed solution #include<iostream> using namespace std; class Cat { public: Cat(int initage); int age(); void setage(int newage); private: int m_age; ; Cat::Cat(int initage) { setage(initage); int Cat::age(){ return m_age; void Cat::setAge(int newage){ m_age = newage; class Person { public: Person():pet(1){ cout << "Person initialized" << endl; ; private: Cat pet; ; int main(){ Person Mary;

Class - Constructors Order of construction When we instantiate an object, we begin by initializing its member variables then by calling its constructor. (Destruction happens the other way round!) The member variables are initialized by first consulting the initializer list. Otherwise, we use the default constructor for the member variable as a fallback. For this reason, member variable without a default constructor must be initialized through the initializer list.

Class - Constructors Can this compile? If so, what s the output? class Cat { public: Cat(string name) { cout << "I am a cat: " << name << endl; m_name = name; private: string m_name; ; class Person { public: Person(int age) { cout << "I am " << age << " years old. "; m_cat = Cat("Alfred"); m_age = age; private: int m_age; Cat m_cat; ; int main() { Person p(21); Person(int age) : m_cat("alfred") {...

Class -Destructors A destructor is a special member function of a class that is executed whenever an object of it's class goes out of scope or whenever the delete expression is applied to a pointer to the object of that class. The destructor should use delete to eliminate any dynamically allocated variables created by the object A destructor s name starts with ~, followed by the name of the class, with no return type or arguments. class Cat { public: Cat(int initage); ~Cat(); int age(); void setage(int newage); private: int m_age; ;

Class - this This The keyword s value is the address of the object, on which the member function is being called. Recall in your project 7

Final Review Refer to UPE Tutoring https://goo.gl/dhacfn

Week 1 Compilation/syntax rrrors Some common syntax errors: Missing semicolons at ends of statements Missing brackets around blocks Missing namespace or #include definitions Misspelled variables or names Runtime/logic errors Some common runtime errors: Division by 0 Overflow (e.g.: trying to hold a really big number in an int variable that exceeds its bounds)

Strings, chars, loops String #include <string> Operation What it does Example string s = hello ; string s =!!! ; Declare strings s and s2 s.length() or s.size() Return the length of s cout << s.size(); // prints 5 s[i] or s.at[i] Return i-th character. (i should be integer between 0 and size-1 (inclusive)) cout << s[1]; // prints e cout << s.at(0); // prints h s + s2 Concatenate two strings cout << s + s2; // prints hello!!!

Strings, chars, loops Char Characters can be represented by a unique integer value. ASCII(American Standard Code for Information Interchange) defines the mapping between characters and integers. Operation char c; isspace(c) isalpha(c) isdigit(c) islower(c) isupper(c) What it does Declare a character c True if c is a whitespace character True if c is a letter True if c is a digit True is c is a lowercase letter True if c is a uppercase letter <cctype> library

Strings, chars, loops cin >> var; command accesses input characters, ignores whitespace, and ignores the newline at the end of the user s input. We use this to get numerical input, and store it in variable var. getline(cin, s); command consumes all characters up to, and including, the newline character. It then throws away the newline, and stores the resulting string in s. We use this to gather string inputs. (requires <string> library) #include <iostream> #include <string> using namespace std; int main () { string inputstring; int inputint; cout << "Enter a number: "; cin >> inputint; cout << "Input was: " << inputint << endl; cout << "Enter a string: "; getline(cin, inputstring); cout << "Input was: " << inputstring << endl; Input: 32 world Output: Enter a number: 32 Input was: 32 Enter a string: Input was:

CStrings C strings are null-terminated char s[10] = "HOWAREYOU"; H O W A R E Y O U \0 Operation What it does strlen(s) Returns the length of s, not counting \0. strcpy(t,s) strncpy(t,s,n) strcat(t,s) Copies the string s to t. (Notes: t=s won t do the job. Also, strcpy doesn t do the size check for you. You must make sure there s enough space in t yourself.) Copies the first n characters of s to t. (Note: No size check.) Appends s to the end of t. (Notes: No size check. t += s won t do the job.) #include <cstring> strcmp(t,s) Compares t and s. Returns 0 if they are equal, something greater than 0 if t > s, and something less than 0 if t < s. (Note: t == s or t < s won t do the job.)

Strings, chars, loops If-else statements symbol Meaning > Greater than >= Greater than or equal to < Less than <= Less than or equal to == Equal to!= Not equal to && AND OR

Strings, chars, loops Switch statements switch (expression) { case constant1: group-of-statements-1; break; case constant2: group-of-statements-2; break;... default: default-group-of-statements; Switch example switch (x) { case 1: cout << "x is 1"; break; case 2: cout << "x is 2"; break; default: cout << "value of x unknown"; If-else equivalent if (x == 1) { cout << "x is 1"; else if (x == 2) { cout << "x is 2"; else { cout << "value of x unknown";

Strings, chars, loops Loops let you repeat the same or similar task multiple times. Three primitive loops in C++: while, do-while, and for. while loop do-while loop while (condition) 2 body; 1 1. Evaluate the condition. If true, 2. run the body. Go back to 1, If false, exit the while loop. do { 1 body; 2 while (condition); Don t forget the ; here. 1. Execute the body. 2. Evaluate the condition If true, Go back to 1, If false, exit the while loop. Notice: The body in do-while loop will be executed once no matter what.

Strings, chars, loops for loop 1 2 for (initialization; condition; update) body; 3 1. Execute initialization. 2. Evaluate the condition. If true, 3. Run the body. 4. Do the update. Go back to 2. If false, exit the for loop. 4

functions, reference, scope function declaration (function prototype/signature) function body (function implementation) function call A reference variable is an alias, or put simple, another name for an already existing variable. <type>& <name>

arrays Declare an array <type> <name>[size] int a[5] = {1, 2, 3, 5, 7; int a[] = {1, 2, 3, 5, 7; Out-of-boundary access not allowed! void fibo10(int fib[]); void fibo10(int fib[], int n);

Pointers Pointers store memory addresses and are assigned a type corresponding to the type of the variable that they point to. <type>* <name> // declares a pointer of the given <type> and calls it <name>. int* ptrage; bool* ptrvalid; char* ptrname; To initialize pointers int age = 40; int* prtage = &age; or int* ptrage; ptrage = &age; 16 1000 1001 1002 1003 1004 1005 1006 int* prtage = &age;

Pointers and Arrays int arr[100]; arr is actually a pointer(int*) Special for arr, the pointee can t change. In order to get the value of arr[1] arr[1] *(arr+1)

Pointer Arithmetic #include <iostream> using namespace std; int main(){ int arr[100]; int var = 100; for (int i = 0; i < 100; i++) arr[i] = i; cout << arr+1 << endl; cout << arr+2 << endl; arr is pointing to the integer. A integer is of 4 bytes on this platform.

Pointers and Arrays You can treat an array variable like a pointer well, it is a pointer. Therefore, the following are equivalent: Recall Pass by value Pass by reference Pass by pointer int findfirst(const string a[], int n, string target); int findfirst(const string* a, int n, string target); int foo(int n); int foo(int &n); int foo(int a[]); int foo(int* a);

Pointer to pointer int** var; int** int* int address address value #include <iostream> using namespace std; int main() { int var; int *ptr; int **pptr; var = 3000; ptr = &var; pptr = &ptr; cout << "Value of var = " << var << endl; cout << "Value available at *ptr = " << *ptr << endl; cout << "Value available at **pptr = " << **pptr << endl;

Reference to Pointer int* &ptr; #include <iostream> using namespace std; int main() { int var1 = 30; int var2 = 50; int* ptr1 = &var1; int* &ptr2 = ptr1; cout << *ptr1 << endl; ptr2 = &var2; cout << *ptr1 << endl; var1 30 var2 50 (ptr2) ptr1

Struct Structs are objects in C++ that represent "data structures", or variables, functions, etc. that are organized under a categorizing identifier. Data Members are variable components of a given struct; they can be of any variable type. struct <structname> { <member1_type> <member1_name>; <member2_type> <member2_name>; //...etc. ; // Remember the semicolon! struct Student { string name; int id; string email; char grade; ;

Pointers to Structures student *p; You can refer to a member of the structure pointed by p by first dereferencing it and using the dot operator. (*p).name Or p->name This one works only if p is a pointer.

const const int a1 = 3; const int* a2 int const * a3; int * const a4 Int const * const a5 For member functions in class int Cat::age() const { /* code */ Ban age() in class Cat from beging anything which can attempt to alter any member variables in the object.

Credit to 2 previous CS31 TAs This slide is finished with reference from: Andrew Forney http://web.cs.ucla.edu/~forns/ Brian Choi http://netlab.cs.ucla.edu/~schoi/cs31/

Thanks!