Introduction to Computer and Program Design. Lesson 8 C++ James C.C. Cheng Department of Computer Science National Chiao Tung University

Similar documents
Standard I/O in C and C++

Object-Oriented Programming (1)

Introduction to Computer and Program Design. Lesson 6. File I/O. James C.C. Cheng Department of Computer Science National Chiao Tung University

Introduction to C++ Systems Programming

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

Streams - Object input and output in C++

std::cout << "Size of long = " << sizeof(long) << " bytes\n\n"; std::cout << "Size of char = " << sizeof(char) << " bytes\n";

Chapter 15 - C++ As A "Better C"

UNIT- 3 Introduction to C++

cs3157: c++ lecture #2 (mon-11-apr-2005) chronology of some programming languages... C++ vs Java identifiers.

CS3157: Advanced Programming. Outline

Module 11 The C++ I/O System

Character Set. The character set of C represents alphabet, digit or any symbol used to represent information. Digits 0, 1, 2, 3, 9

Introduction to Programming

This chapter introduces the notion of namespace. We also describe how to manage input and output with C++ commands via the terminal or files.

I BSc(IT) [ Batch] Semester II Core: Object Oriented Programming With C plus plus - 212A Multiple Choice Questions.

University of Technology. Laser & Optoelectronics Engineering Department. C++ Lab.

Chapter 12 - C++ Stream Input/Output

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

CprE 288 Introduction to Embedded Systems Exam 1 Review. 1

Piyush Kumar. input data. both cout and cin are data objects and are defined as classes ( type istream ) class

Preface to the Second Edition Preface to the First Edition Brief Contents Introduction to C++ p. 1 A Review of Structures p.

C OVERVIEW. C Overview. Goals speed portability allow access to features of the architecture speed

Introduction to C++ (Extensions to C)

Tokens, Expressions and Control Structures

Appendix. Grammar. A.1 Introduction. A.2 Keywords. There is no worse danger for a teacher than to teach words instead of things.

CS2141 Software Development using C/C++ Stream I/O

CS201 Some Important Definitions

C OVERVIEW BASIC C PROGRAM STRUCTURE. C Overview. Basic C Program Structure

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

Short Notes of CS201

EEE145 Computer Programming

Expressions and Precedence. Last updated 12/10/18

Basic Types, Variables, Literals, Constants

CS201 - Introduction to Programming Glossary By

basic_fstream<chart, traits> / \ basic_ifstream<chart, traits> basic_ofstream<chart, traits>

Outline. 1 Function calls and parameter passing. 2 Pointers, arrays, and references. 5 Declarations, scope, and lifetimes 6 I/O

2.1. Chapter 2: Parts of a C++ Program. Parts of a C++ Program. Introduction to C++ Parts of a C++ Program

Computers Programming Course 6. Iulian Năstac

Objects and streams and files CS427: Elements of Software Engineering

Fig: iostream class hierarchy

Convenient way to deal large quantities of data. Store data permanently (until file is deleted).

By the end of this section you should: Understand what the variables are and why they are used. Use C++ built in data types to create program

PHY4321 Summary Notes

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

CS201 Solved MCQs.

Lecture 9. Introduction

Chapter 2: Introduction to C++

Object Oriented Programming Using C++ UNIT-3 I/O Streams

CS

CS242 COMPUTER PROGRAMMING

C++ Basics. Data Processing Course, I. Hrivnacova, IPN Orsay

INFO-I308 Laboratory Session #2

Chapter 2: Special Characters. Parts of a C++ Program. Introduction to C++ Displays output on the computer screen

BITG 1233: Introduction to C++

OBJECT ORIENTED PROGRAMMING

School of Information Technology and Computer Science CSCI192 - Spring Session Revision

CSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010

CSCI 171 Chapter Outlines

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

Programming. C++ Basics

UEE1303(1070) S 12 Object-Oriented Programming in C++

The C++ Language. Arizona State University 1

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++

Programming, numerics and optimization

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

CSE 303: Concepts and Tools for Software Development

C++ Programming Lecture 10 File Processing

PROGRAMMING IN C++ KAUSIK DATTA 18-Oct-2017

Engineering Problem Solving with C++, Etter/Ingber

c++ keywords: ( all lowercase ) Note: cin and cout are NOT keywords.

Chapter 21 - C++ Stream Input/Output

Variables. Data Types.

A flow chart is a graphical or symbolic representation of a process.

C++ Programming Basics

APPENDIX A : KEYWORDS... 2 APPENDIX B : OPERATORS... 3 APPENDIX C : OPERATOR PRECEDENCE... 4 APPENDIX D : ESCAPE SEQUENCES... 5

C Language Part 1 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee

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

For Teacher's Use Only Q No Total Q No Q No

LECTURE 02 INTRODUCTION TO C++

CS201 Latest Solved MCQs

Distributed Real-Time Control Systems. Lecture 17 C++ Programming Intro to C++ Objects and Classes

PIC10B/1 Winter 2014 Exam I Study Guide

Fast Introduction to Object Oriented Programming and C++

W3101: Programming Languages C++ Ramana Isukapalli

CHAPTER 1.2 INTRODUCTION TO C++ PROGRAMMING. Dr. Shady Yehia Elmashad

Fundamental Data Types. CSE 130: Introduction to Programming in C Stony Brook University

6.096 Introduction to C++ January (IAP) 2009

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

Classes in C++98 and C++11

This tutorial adopts a simple and practical approach to describe the concepts of C++.

LEXICAL 2 CONVENTIONS

Come and join us at WebLyceum

CHAPTER 1 Introduction to Computers and Programming CHAPTER 2 Introduction to C++ ( Hexadecimal 0xF4 and Octal literals 031) cout Object

Reference Parameters A reference parameter is an alias for its corresponding argument in the function call. Use the ampersand (&) to indicate that

Fundamentals of Programming Session 25

Lesson 4 struct and memory management

C Programming. Course Outline. C Programming. Code: MBD101. Duration: 10 Hours. Prerequisites:

Tutorial-2a: First steps with C++ programming

Transcription:

Introduction to Computer and Program Design Lesson 8 C++ James C.C. Cheng Department of Computer Science National Chiao Tung University

Textbooks l C++ Primer, 5ed By Stanley B. Lippman, Josée Lajoie, Barbara E. Moo Publisher: Addison Wesley Features: Introduction to OOP C++11 2

A simple C++ program l What are the differences between C and C++? #include <iostream> // for cin & cout using namespace std; // for cin & cout int main() // function definition { // block begin int x = 0; // object declaration cin >> x; // object input x *= 1 + 2 * 3 / 4; // arithmetical expression cout << x << endl; // object output return 0; // function return } // block end 3

C/C++ Operators - 1, 2 Precedence Operator Description Associativity 1(highest) :: Scope resolution (C++ only) Left-to-right ++ Suffix increment -- Suffix decrement () Function call [] Array subscripting. Element selection by reference 2 -> Element selection through pointer typeid() const_cast dynamic_cast Run-time type information (C++ only) Type cast (C++ only) Type cast (C++ only) reinterpret_casttype cast (C++ only) static_cast Type cast (C++ only) 4

C/C++ Operators - 3 Precedence Operator Description Associativity ++ Prefix increment Right-to-left 3 -- Prefix decrement + Unary plus - Unary minus Logical NOT ~ Bitwise NOT (type) Type cast * Indirection (dereference) & Address-of sizeof Size-of new, new[] Dynamic memory allocation (C++ only) delete, delete[] Dynamic memory deallocation (C++ only) sizeof Get the number of arguments (C+11) alignof noexecpt Get the number of bytes for memory alignment (C++11) Does the expression throw an exception? (C++11) 5

C/C++ Operators 4-7 Precedence Operator Description Associativity 4 5 6 7.* Pointer to member (C++ only) ->* Pointer to member (C++ only) * Multiplication / Division % Modulo (remainder) + Addition - Subtraction << Bitwise left shift >> Bitwise right shift Left-to-right 6

C/C++ Operators 8-14 Precedence Operator Description Associativity < Less than Left-to-right 8 <= Less than or equal to > Greater than >= Greater than or equal to 9 == Equal to = Not equal to 10 & Bitwise AND 11 ^ Bitwise XOR (exclusive or) 12 Bitwise OR (inclusive or) 13 && Logical AND 14 Logical OR 7

C/C++ Operators 15-18 Precedence Operator Description Associativity 15?: Ternary conditional (see?:) Right-to-left = Direct assignment += Assignment by sum -= Assignment by difference *= Assignment by product /= Assignment by quotient 16 %= Assignment by remainder <<= Assignment by bitwise left shift >>= Assignment by bitwise right shift 17 &= ^= Assignment by bitwise AND Assignment by bitwise XOR = Assignment by bitwise OR throw Throw operator (exceptions throwing, C++ only) 18, Comma Left-to-right 8

Function overloading l Multiple function with the name but different parameter Ex: int F1(void); int F2(); void F3(void); void F3(int); // In C++, OK, but error in C int F4(int, int, char); or int F4(int x, int y, char c); 9

Function definition l Default argument Only in C++ A default argument is a value given in the declaration that the compiler automatically inserts if you don t provide a value in the function call. A default argument cannot be placed before non-default argument The declaration of a default argument either in global function declaration or in function definition. Local function declaration can has its own default argument list. void F1(int a, int b =10, int c = 2){ cout << a << ", " << b << ", " << c << endl; int main(){ F1(1, 2, 3); // a = 1; b= 2; c =3 F1(1); // a = 1; b= 10; c =2 void F1(int a, int b =20, int c = 30); // Local decl. F1(1); // a = 1; b= 20; c =30 F1(1,,3); // Compiler error } 10

Function definition l Default argument void F2(int a, int b =10, int c){ } // Compiler error void F3(int a, int b =10, int c=5){ } // Compiler error void F1(int a, int b, int c); int main(){ F1(1); // Compiler error: default argument missing void F1(int a, int b =10, int c = 2){ cout << a << ", " << b << ", " << c << endl; void F1(int a, int b = 1, int c = 2); int main(){ F1(1); void F1(int a, int b=4, int c=4) // Compiler error: redefinition { cout << a << ", " << b << ", " << c << endl; } 11

Standard Output in C++ l Std IO C and C++ #include <cstdio> int main(){ int x = 10; double y = 1.23456789; char *s = "Hello world"; printf("%d, %0.8f, %s\n", x, y, s); #include <iostream> int main(){ int x = 10; double y = 1.23456789; char *s = "Hello world"; std::cout.precision(9); std::cout << x << ", "; std::cout << y << ", "; std::cout << s << std::endl; 12

Standard Output in C++ Namespace std::cout << x ; Scope operator Left object Insertion operator (a binary operator) l It means that put the x into the stdout l cout is an object that represents the stdout Right object l To save typing, we can use the using namespace command. std::cout.precision(9); Object Member method Member-selection operator 13

Standard Output in C++ l The manipulators of cout int x =255; std::cout << std::oct ; std::cout << x << std::endl; // 377 std::cout << std::dec ; std::cout << x << std::endl; // 255 std::cout << std::showbase << std::hex << x << std::endl;//0xff std::cout << std::uppercase << x << std::endl ; // 0xFF std::cout << std::noshowbase; std::cout.width(10); std::cout << std::dec << x << std::endl; // 255 std::cout.width(10); std::cout << std::right << x << std::endl; // 255 std::cout.width(10); std::cout << std::left << x << "" << std::endl; // 255 float y = 123.56789; std::cout.precision(5); std::cout << y << std::endl; //123.57 14

Standard Output in C++ l The list of manipulators boolalpha - Insert or extract bool objects as "true" or "false". noboolalpha - Insert or extract bool objects as numeric values. fixed - Insert floating-point values in fixed format. scientific - Insert floating-point values in scientific format. internal - Internal-justify. left - Left-justify. right - Right-justify. dec - Insert or extract integer values in decimal format. hex - Insert or extract integer values in hexadecimal (base 16) format. oct - Insert or extract values in octal (base 8) format. 15

Standard Output in C++ l The list of manipulators noshowbase - Do not prefix value with its base. showbase - Prefix value with its base. noshowpoint - Do not show decimal point if not necessary. showpoint - Always show decimal point when inserting floating-point values. noshowpos - Don't insert plus sign (+) if number >= 0. showpos - Do insert plus sign (+) if number >=0. noskipws - Do not skip initial white space on extracting. skipws - Skip initial white space on extracting. nouppercase - Don't replace lowercase letters by uppercase equivalents. uppercase - Replace lowercase letters by uppercase equivalents. unitbuf - Flush buffer after an insert. nounitbuf - Don't flush buffer after each insert. 16

Standard Output in C++ l ios::flags setf(long) and unsetf(long), to set and unset the flag. Using flags() to recover all setting int x =255; long OrgFlag = std::cout.flags(); // Record the origin setting std::cout.unsetf( ios::dec ); // unset std::cout.setf( ios::oct ); std::cout << x << std::endl; // 0377 std::cout.unsetf( ios::oct ); // unset std::cout.setf( ios::dec ); std::cout << x << std::endl; // 255 std::cout.unsetf( ios::dec ); // unset std::cout.setf( ios::hex ios::showbase ios::uppercase ); std::cout << x << std::endl; // 0xFF std::cout.flags( OrgFlag ); std::cout << x << std::endl; // Recover the flag 17

Standard Input in C++ l std::cin with the extraction operator, >> cin is an object that represents the stdin char c1=0, c2 =0, c3=0; std::cin >> c1 >> c2; std::cout << c1 << ", " << c2 << std::endl; std::cin >> c3; std::cout << c3 << std::endl; Notice that the delimit characters are white space keys.

Standard Input in C++ l std::cin and EOF Ctrl+D in UNIX Ctrl+Z in Windows #include <iostream> int main(){ int x = 10; while( (std::cin >> x).eof() ) std::cout << x << std::endl; std::cout << "END" << std::endl;

Standard Input in C++ l Abnormal input All wrong input must be remove before the next input the fail state of cin must be reset after stdin buffer cleared #include <iostream> using namespace std; int main(){ int x = 10; while((cin >> x).eof()){ if(cin.fail()){ // Abnormal input std::cin.clear(); // Clear the fail state while(cin.get()='\n' && cin.eof()); // Clearing else{ // Normal input cout << x << endl; cout << "END" << endl;

Memory management in C++ l malloc and free in C #include <cstdlib> // for malloc, calloc, realloc, and free #include <cstring> // for memset, memcpy, memmove, and memcmp #include <iostream> using namespace std; int main(){ size_t n = 0; cin >> n; // Dynamic memory allocation without initialization int *pi = (int *)malloc( sizeof(int) * n); memset(pi, 0, sizeof(int) * n); // Dynamic memory allocation with zero initialization double *pd = (double *)calloc(n, sizeof(double) * n); // Deallocation free(pi); free(pd); 21

Memory management in C++ l new and delete in C #include <cstdlib> // for malloc, calloc, realloc, and free #include <cstring> // for memset, memcpy, memmove, and memcmp #include <iostream> using namespace std; int main(){ size_t n = 0; cin >> n; int *pi = new int[n]; memset(pi, 0, sizeof(int) * n); double *pd = new double[n]; memset(pd, 0, sizeof(double) * n); // Deallocation delete [] pi; delete [] pd; 22

Dynamic memory allocation l Case study: recording the weights and heights (dynamic memory alloc) size_t n = 0; cout << "n="; cin >> n; getchar(); // n=? // Memory allocation, watch the array pointer declaration float (*A)[2] = new float[n][2]; int i=0; for(i=0; i<n; ++i){ // Data input. cout << "W H: "; cin >> A[i][0] >> A[i][1]; qsort(a, n, sizeof(float) * 2, cmpw ); // By weight for(i=0; i<n; ++i) cout << A[i][0] << ":" << A[i][1] << ", "; cout << endl; qsort(a, n, sizeof(float) * 2, cmph ); // By height for(i=0; i<n; ++i) cout << A[i][0] << ":" << A[i][1] << ", "; cout << endl; delete [] A; 23

Struct l To design a custom data type l To group multiple relevant data l Heterogeneous array struct Student{ char name[8]; float w, h; }; void InputStudent(Student* px) { cin >> px->name >> px->w >> px->h; getchar(); void PrintStudent (const struct Student* px){ cout << "Name:" << px->name << ", "; cout << "w:" << px->w << ", "; cout << "h:" << px->h << endl; 24

Struct l Initialization Initializer list Student x = {0}; Student y = {"James", 75.2f, 175.6f}; // Notice the order struct Student{ char name[8]; float w, h; }; Uniform initialization C++11 and GCC Visual C++ 2010, 2012 not support Student x{0}; Student y{"james", 75.2f, 175.6f}; // Notice the order 25

File I/O in C++ l fstream, a class of File I/O its usage is similar to cin and cout #include <fstream> #include <iostream> using namespace std; int main(){ fstream file("test.txt", ios::out); // Open for writing for(int i=0; i<10; ++i) file << "LINE" << i << endl; file.close(); // Don't forget to close file.open("test.txt", ios::in); // Open for read while(file.eof()){ char buf[255] = {0}; file >> buf; cout << buf << endl; file.close(); // Don't forget to close } 26

File I/O in C++ l Opening mode ios::app, appending to the end of file. ios::ate, to seek to the end of file. ios::binary, binary mode ios::in, read mode. ios::out, write mode. ios::trunc, to delete contents of an existing file. 27

File I/O in C++ l Input (read) / Output (write) istream& fstream::read(char* buf, streamsize size ); ostream& fstream::write(const *char buf, streamsize size ); buf : Storage location for data size: Item size in bytes. fstream file("test.txt", ios::out); int A[3] = { 1, 2, 3}; file.write((const char*)a, sizeof(a)); file.close(); int B[3] = {0}; file.open("test.txt", ios::in); file.read((char *)B, sizeof(b)); cout << B[0] << endl; cout << B[1] << endl; cout << B[2] << endl; file.close();

File I/O in C++ l Stream I/O Other Stream I/O functions: streampos fstream::tellg(); Ø Get position of get pointer streampos fstream::tellp(); Ø Get position of put pointer istream& fstream::seekg(streamoff off, ios_base::seekdir dir ); Ø Sets the position of the get pointer Ø dir = ios_base::beg beginning of the stream buffer ios_base::cur current position in the stream buffer ios_base::end end of the stream buffer Ø notice that the eof or other error state must be cleared before seekg() or seekp() ostream& fstream::seekp(streamoff off, ios_base::seekdir dir ); Ø Sets the position of the put pointer bool fstream::eof ( ) const; Ø Returns true if the cursor is at the end of file

References l Syntax: typename &alias = object name; l A reference is just an alias of an object. int x = 10; int &refx = x; ++refx; cout<<x<<endl; // 11 A reference must be some object s alias A const reference can refer a constant const int &r = 123; cout << r << endl // 123; r = 456; // Error const int x = 10; r = x; // Error int &r1; // Error int &r2 = 123; // Error int x = 10, y = 20; int &r = x; cout << r < endl; // 10 int &r = y; cout << r < endl; // 20

References l Why we need references? Multiple output of function void Swap( int *pa, int pb ) { int t = *pa; *pa = *pb; *pb= t; } // Too complicated... int x= 10, y = 20; Swap(&x, &y); printf("%d, %d\n", x, y); // 20, 10 OK void Swap( int &a, int &b ) { int t = a; a = b; b= t; } // Very simple... int x= 10, y = 20; Swap(x, y); printf("%d, %d\n", x, y); // 20, 10 OK // Call by name (or reference): // passing the parameter by alias name 31

References l Type cast of references Be careful of the size of object float x = -0.0f; int &rx = (int &)x; cout << hex << x << endl; // 80000000 char y = 0; int &ry = (int &)y; ry = 257; // Runtime error

References l Reference cannot be reset to refer other object. int x = 10, y = 20; int &r = x; cout << r << endl; // 10 r = y; cout << x << ", " << y << endl; // 20, 20 r = (int &)y; cout << x << ", " << y << endl; // 20, 20 r = 30; cout << x << ", " << y << endl; // 30, 20 l There is no straight method to reset a reference

References l Reference and Array void printarray(int (&A)[10]){ for(int i=0; i<10; ++i) cout << A[i] << endl; int main(){ int M = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; printarray(m); } void printarray(int (&A)[] ){ // Error Unknown bound for(int i=0; i<10; ++i) cout << A[i] << endl; void printarray(int &A[10] ){ // Error 10 integer references? for(int i=0; i<10; ++i) cout << A[i] << endl; void printarray(int &A ){ // Error Only one integer reference for(int i=0; i<10; ++i) cout << A[i] << endl;

Class l Only in C++ l As the same as struct, class also can contains member functions l Actually, the usage of class is the same as struct s besides the default member access privilege and initializer. struct: public class: private class Student{ char name[8]; float weight, height; float bmi(); }; float Student::bmi(){ float h = height / 100.0f; return w / (h * h); Student x; x.w = 80; // Error w is a private member x.bmi(); // Error bmi() is a private member 35

Class l There are three member access privileges private: Accessed by member functions, friend functions, and friend classes protected: Accessed by inherited classes, member functions, friend functions, and friend classes public: Accssed by derivative objects, inherited classes, member functions, friend functions and friend classes l To access a private member data, you should design a public function 36

Class l DO NOT declare member variable as public Just private or protected. l To access a private member data, you should design a public function class Student{ private: char *name; float weight, height; public: void setheight (float _h){height= _h; } void setweight (float _w){weight= _w; void setname(const char *_name) {strcpy(name, _name); float getheight () const { return height; float getweight () const { return weight; const char* getname() const{ return name; float bmi(); }; float Student::bmi(){ float h = height / 100.0f; return weight / (h * h); 37

this pointer l Questions: Why setheight(float _h) can pass _h to x.height or y.height? Why bmi() can calculate x's bmi or y's bmi? void Student::setHeight(float _h) { height= _h; } float Student::bmi(){ float h = height / 100.0f; return weight / (h * h); Student x, y; x.setweight(70); x.setheight(170); cout << x.bmi() << endl; y.setheight(75); y.setheight(170); cout << y.bmi() << endl; 38

this pointer l The answer is, your code will be changed by the compiler: void Student::setHeight(float _h) { height= _h; } float Student::bmi(){ float h = height / 100.0f; return weight / (h * h); void Student::setHeight( Student *this, float _h) {this->height= _h; } float Student::bmi(Student *this){ float h = this->height / 100.0f; return this->weight / (h * h); The added pointer, this, is used to represent the members owner. 39

this pointer l Certainly, the member function calling also be changed by compiler: Student x, y; x.setweight(70); x.setheight(170); cout << x.bmi() << endl; y.setheight(75); y.setheight(170); cout << y.bmi() << endl; Student x, y; x.setweight(&x, 70); x.setheight(&x, 170); cout << x.bmi(&x) << endl; y.setheight(&y, 75); y.setheight(&y, 170); cout << y.bmi(&y) << endl; 40

this pointer l "this" is an reserved key word. l Therefore, you cannot naming any object as "this" l In any non-static member functions, you can use this pointer to indicate the other member. void Student::setHeight( Student *this, float _h) // error {this->height= _h; } // OK float Student::bmi(Student *this){// error float h = this->height / 100.0f; // OK return this->weight / (h * h); // OK 41

constant methods l You should design the member function as a constant method, if all member data won't be changed in the function. l put const key word before { class Student{... float getheight () const ; float getweight () const ; const char* getname() const; float bmi() const; }; float Student::getHeight() const {return height;} float Student:: getweight () const {return weight;} const char* Student:: getname() const{return name;} float Student::bmi() const{ float h = height / 100.0f; return weight / (h * h); 42

constant methods l However, the following member functions cannot be constant member methods: Any member variable is modified in the function body Any non-constant member function is called in the function body Static member function 43

constant methods l this pointer in the constant method float Student::getHeight(const Student* this) const {return this->height;} float Student::getWeight (const Student* this) const {return this->weight;} const char* Student::getName(const Student* this)const {return this->name;} float Student::bmi(const Student* this) const{ float h = this->height / 100.0f; return this->weight / (h * h); const Typename* p; The memory space pointed by p is read-only. But p can be modified. Considering these five pointers: const int *p; int const *p; int * const p; const int const *p; const int *const p; 44

Static members l When a class member is static, only one memory location is allocated All members of the class share a single storage location for a static data member of that same class When you create a non-static variable within a function, a new variable is created every time you call that function When you create a static variable, the variable maintains its memory address and previous value for the life of the program 45

Static members l Static member variable must be instantiated Class declaration class Student { static float bmim, bmif; public: static float StandBmiM(); static float StandBmiF(); static float setstandbmim( float v); static float setstandbmif( float v); }; 46

Static members l Static member variable must be instantiated Implementation // Static variables memory allocation float Student::bmiM = 22.0f; float Student::bmiF = 19.0f; // Static member functions implementation float Student::StandBmiM() { return bmim; float Student::StandBmiF() { return bmif; float Student::setStandBmiM (float v) { bmim = v; float Student::setStandBmiF(float v) { bmif = v; } Notice that there is no static keyword in the function implentation 47

Static members l A static member does not belong to any object è a common member it called class variables, class fields, or class-wide fields int main(){ Student Lin, Chen; cout << Lin.StandBmiF() << endl; // 19.0 cout << Chen.StandBmiF() << endl; // 19.0 cout << Student::StandBmiF() << endl; // 19.0 // You can use the static memebr by the scope operator. l No this pointer in the static member function float Student::setStandBmiM (float v) { this->bmim = v; } // Error The static member function doesn t has this pointer 48

Static members l Other non-static member function also can use the static members Class declaration Implementation class Student { private: int g; // gender... static float bmim, bmif; public:... void getgender()const; int setgender(int _g); float StandBmi() const; float bmidiff() const; }; void getgender()const{return g; int setgender(int _g){g = _g; float Student::StandBmi() const{ if( g == 0) return bmif; else return bmim; float Student::bmiDiff() const { return bmi() - StandBmi(); l But, DO NOT use this pointer to access the static members float Student::StandBmi() const { if( this->g == 0) return this->bmif; else return this->bmim; } // Error 49

const static members l Unchangeable static member data They are read-only They must be assigned a initial value in the class declaration They do not need memory allocation Class declaration class Student { const static float bmim = 22.0; const static float bmif = 19.0; public: static float StandBmiM(); static float StandBmiF(); static float setstandbmim( float v); static float setstandbmif( float v); }; 50

const static members Implementation // Static variables memory allocation float Student::bmiM = 22.0f; // Error float Student::bmiF = 19.0f; // Error // Static member functions implementation float Student::StandBmiM() { return bmim; float Student::StandBmiF() { return bmif; float Student::setStandBmiM (float v) { bmim = v; } // Error bmim is unchangeable float Student::setStandBmiF(float v) { bmif = v; } // Error bmif is unchangeable 51

Constructors and Destructor l Constructor, ctor A member function is automatically invocated after object is created Its name is the same as the type name No return type The number of parameters >= 0 You can design many ctors with different parameters for a datatype l Destructor, dtor A member function is automatically invocated before object is deleted The name of dtor is ~typename It has no return type It has no any parameter It is unique 52

Constructors l Default constructor: ctor without any argument class Student{ char name[8]; float weight, height; public: // ctor Student (); }; Student::Student(){ weight = height = 0.0f; memset(name, 0, sizeof(char) * 8); Student x; cout << x.getname() << ": "; cout << x.getweight() << ", " << x.getheight() << endl; 53

Constructors l Default constructor class Student{ char name[8]; float weight, height; public: Student (); Student (float _w, float _h, const char* _name); };... Student::Student(float _w, float _h, const char* _name){ weight = _w; height = _h; if(_name = NULL) strcpy(name, _name); else memset(name, 0, sizeof(char) * 8); Student x(70.5f, 175.5f, "James"); cout << x.getname() << ": "; cout << x.getweight() << ", " << x.getheight() << endl; 54

Constructors l In C++11, we can use initializer list or uniform initialization to call ctor Visual C++ 2010 and 2012 not support class Student{ char name[8]; float weight, height; public: // ctors Student (); Student (float _w, float _h, const char* _name); }; Student x = {70.5f, 175.5f, "James"}; // Initializer list, Only in GCC C++11 Student y{65.5f, 180.5f, "Lin"}; // Uniform initialization, Only in GCC C++11 cout << x.getname() << ": "; cout << x.getweight() << ", " << x.getheight() << endl; cout << y.getname() << ": "; cout << y.getweight() << ", " << y.getheight() << endl; // That is the main difference between class and struct 55

Constructors l Initialization list of ctor class Student{ Only single object can be char name[8]; initialized in the initialization list. float weight, height; public: Student (); Student (float _w, float _h, const char* _name); };... Student::Student(float _w, float _h, const char* _name) : weight(_w), height(_h) // Notice the order { if(_name = NULL) strcpy(name, _name); // For array else memset(name, 0, sizeof(char) * 8); Student x(70.5f, 175.5f, "James"); cout << x.getname() << ": "; cout << x.getweight() << ", " << x.getheight() << endl; 56

Constructors l Better default ctor class Student{ char name[8]; float weight, height; public: Student(float _w = 0, float _h = 0, const char* _name = NULL); };... Student::Student(float _w, float _h, const char* _name) : weight(_w), height(_h) // Notice the order { if(_name = NULL) strcpy(name, _name); // For array else memset(name, 0, sizeof(char) * 8); Student x; cout << x.getname() << ": "; cout << x.getweight() << ", " << x.getheight() << endl; 57

Constructors l Dynamic member and ctor class Student{ char *name; float weight, height; public: Student(float _w=0, float _h=0, const char* _name=null); }; Student::Student(float _w, float _h, const char* _name) : name(null), weight(_w), height(_h) // Notice the order { setname(_name); void Student::setName (const char* _name){ if(name) delete [] name; // delete the previous new name = NULL; if(_name = NULL){ name = new char[strlen(_name) + 1]; strcpy(name, _name); } // Where should you do the last delete[]? 58

Destructor l Destructor, dtor In most case, dtor is needed to be designed only when there is a dynamic member in the class class Student{ char *name; float weight, height; public: Student(float _w = 0, float _h = 0, const char* _name = NULL); ~Student(); }; Student::~Student(){ if(name) delete [] name; 59

Copy constructor l You must design the copy ctor if there is a dynamic member in the class class Student{ char *name; float weight, height; public: Student(float _w = 0, float _h = 0, const char* _name = NULL); Student(const Student& x); ~Student(); }; Student::Student(const Student& ) { setname(x.name); } // Private access is allowed 60

EX: Stack l Stack, a LIFO(Last-In-First-Out) data structure. l ADT: class Stack{ private: int* data; int top, n; public: Stack(int _n = 10); Stack(const Stack& s); ~Stack(); int maxsize(); int size(); bool isempty(); bool isfull(); void push(int x); int pop(); void out(); }; 61

EX: Stack l Member function definitions: // ctor Stack::Stack(int _n): data(null), top(-1), n(_n){ if(n > 0){ data = new int[n]; memset(data, 0, sizeof(int) * n); // Copy ctor Stack::Stack(const Stack& s): data(null), top(s.top), n(s.n){ if(n > 0){ data = new int[n]; for(int i=0; i<n; ++i) data[i] = s.data[i]; // memcpy is not recommended } //dtor Stack::~Stack(){ if(data) delete [] data; 62

EX: Stack l Member function definitions: // properties int Stack::maxsize(){return n; int Stack::size(){return top+1; bool Stack::isEmpty() { return top<0 ; bool Stack::isFull() { return top == n-1; 63

EX: Stack l Member function definitions: void Stack::push(int x){ if(isfull()) data[++top] = x; int Stack::pop() { if(isempty()) return data[top--]; return 0; void Stack::out() { cout << "STACK N = " << size() << ": "; for(int i=top; i >= 0; ){ cout << data[i--]; if(i >= 0) cout << ", "; cout << endl; 64

Namespace l Only in C++ l Given a group name, namespace groups constants, variables, functions, enums, structs, unions, and classes. no semicolon namespace boy { Student p; bool IsTooFat(){ return p.bmi() >= 24.0f; namespace girl { Student p; bool IsTooFat(){ return p.bmi() >= 22.0f; } 65

Namespace l Using the scope operator :: to access the members in a namespace boy::p.setweight(60.0f); boy::p.setheight(165.0f); cout << boy::p.getweight() << ", "; cout << boy::p.getheight() << ": "; cout << boy::p.bmi() << ", "; cout << boy::istoofat() << endl; girl::p.setweight(60.0f); girl::p.setheight(165.0f); cout << girl::p.getweight() << ", "; cout << girl::p.getheight() << ": "; cout << girl::p.bmi() << ", "; cout << girl::istoofat() << endl; 66

Namespace l Keyword: using To save typing, the keyword using allows the objects in a namespace to be used without the namespace-name. boy::p.setheight(60.0f); using namespace boy; p.setweight(165.0f); cout << p.getweight() <<, ; cout << p.getheight() << : ; cout << p.bmi() <<, ; cout << IsTooFat() << endl; using namespace girl; p.setheight(60.0f); // Error Ambiguous Notice that there is no way to turn off using 67

Namespace l Local using using boy::istoofat; // Notice DO NOT add "()" boy::p.setweight(60.0f); boy::p.setheight(165.0f); cout << boy::p.getweight() << ", "; cout << boy::p.getheight() << ": "; cout << boy::p.bmi() << ", "; cout << IsTooFat() << endl; using girl::istoofat; girl::p.setweight(60.0f); girl::p.setheight(165.0f); cout << girl::p.getweight() << ", "; cout << girl::p.getheight() << ": "; cout << girl::p.bmi() << ", "; cout << IsTooFat() << endl; // Error Ambiguous 68

Namespace l Local using Local using is more prior than using namespace using namespace boy; p.setweight(60.0f); p.setheight(165.0f); cout << p.getweight() << ", "; cout << p.getheight() << ": "; cout << p.bmi() << ", "; cout << IsTooFat() << endl; // OK boy's using girl::p; using girl::istoofat; p.setweight(60.0f); p.setheight(165.0f); cout << p.getweight() << ", "; cout << p.getheight() << ": "; cout << p.bmi() << ", "; cout << IsTooFat() << endl; // OK Girl's 69

Namespace l Local using using boy::istoofat; // Notice DO NOT add "()" boy::p.setweight(60.0f); boy::p.setheight(165.0f); cout << boy::p.getweight() << ", "; cout << boy::p.getheight() << ": "; cout << boy::p.bmi() << ", "; cout << IsTooFat() << endl; // OK boy's { using girl::istoofat; girl::p.setweight(60.0f); girl::p.setheight(165.0f); cout << girl::p.getweight() << ", "; cout << girl::p.getheight() << ": "; cout << girl::p.bmi() << ", "; cout << IsTooFat() << endl; // OK Girl's boy::p.setweight(60.0f); boy::p.setheight(165.0f); cout << boy::p.getweight() << ", "; cout << boy::p.getheight() << ": "; cout << boy::p.bmi() << ", "; cout << IsTooFat() << end; // OK boy's 70

Namespace l using namespace local using using namespace boy; p.setweight(60.0f); boy::p.setheight(165.0f); cout << p.getweight() << ", "; cout << p.getheight() << ": "; cout << p.bmi() << ", "; cout << IsTooFat() << endl; // OK boy's { using namespace girl; p.setweight(60.0f); // Error Ambiguous 71

Namespace l Only objects in an namespace can be joined to local using int x = 0; using girl; using girl::; using girl::x; // Error // Error // Error 72

Namespace l global namespace Student p; int main(){ p.setweight(60.0f); // Global's p p.setheight(165.0f); cout << boy::p.getweight() << ", "; // boy'p using namespace boy; cout << p.getheight() << ": "; // Amibiguous cout << boy::p.bmi() << ", "; // Boy's cout << IsTooFat() << endl; // Boy's Student p; int main(){ p.setweight(60.0f); // Global's p p.setheight(165.0f); cout << boy::p.getweight() << ", "; // boy'p using boy::p; cout << p.getheight() << ": "; // Boy's cout << ::p.bmi() << ", "; // Global's cout << IsTooFat() << endl; // Error 73

Namespace l global namespace Student p; int main(){ p.setweight(60.0f); // Global's p p.setheight(165.0f); { using boy::p; cout << p.getweight() << ", "; // boy'p cout << ::p.getheight() << ": "; // global's cout << p.bmi() << ", "; // Global's cout << boy::istoofat() << endl; // Error 74

Nested Namespace namespace Normal{ namespace boy { Student p; bool IsTooFat(){ return p.bmi() >= 24.0f; namespace girl { Student p; bool IsTooFat(){ return p.bmi() >= 22.0f; namespace Model{ namespace boy { Student p; bool IsTooFat(){ return p.bmi() >= 21.0f; namespace girl { Student p; bool IsTooFat(){ return p.bmi() >= 20.0f; } 75

Nested Namespace Normal::girl::p.setWeight(58.0f); Normal::girl::p.setHeight(165.0f); cout << Normal::girl::p.getWeight() << ", "; cout << Normal::girl::p.getHeight() << ": "; cout << Normal::girl::p.bmi() << ", "; cout << Normal::girl::IsTooFat() << endl; Model::girl::p.setWeight(58.0f); Model::girl::p.setHeight(165.0f); cout << Model::girl::p.getWeight() << ", "; cout << Model::girl::p.getHeight() << ": "; cout << Model::girl::p.bmi() << ", "; cout << Model::girl::IsTooFat() << endl; 76

Nested Namespace using namespace Normal::girl; p.setweight(58.0f); // Normal::girl::p p.setheight(165.0f); cout << p.getweight() << ", "; cout << p.getheight() << ": "; cout << p.bmi() << ", "; cout << IsTooFat() << endl; using Model::girl::p; using Model::girl::IsTooFat; p.setweight(58.0f); // Model::girl::p p.setheight(165.0f); cout << p.getweight() << ", "; cout << p.getheight() << ": "; cout << p.bmi() << ", "; cout << IsTooFat() << endl; // Model::girl::IsTooFat 77