Download presentation
Presentation is loading. Please wait.
Published byAron Austin Modified over 9 years ago
1
Final Review Spring, 2015
2
Overall Assessment –Lecture Course Continuous assessment 40% Attendance 10% Homework questions 10% Course projects 20% Final examination 60% 2:30pm-4:30pm, Jul. 01, Wed, A201 Close book English Answer in Chinese is allowed Digital dictionary is allowed 2
3
Question Types in Final Exam Single choice (20’) Output analysis (20’) Error correction (20’) Concept explanation (20’) Program design (20’) 3
4
Overall Assessment –Lab Course Continuous assessment 30% Attendance 10% Course projects 20% Final examination 70% 2:00pm-5:00pm, Jul. 03, Fri., B401 Open book On site programming 4
5
Overview 5 Fundamental of Class/ObjectChapters 9, 10 Pointers and Dynamic Mem.Chapter 11 Operator OverloadingChapter 14 Inheritance, PolymorphismChapter 15 TemplateChapter 12 File Input/OutputChapter 13 Exception HandlingChapter 16 STLChapters 22, 23
6
Fundamental of Class/Object
7
Key Concepts OOP Entity, Object, Class State/property: data field / variable Behavior: function Immutable Classes/Objects Static Members Destructors Constructor, Copy Constructor Friend Functions/Classes 7
8
8 Defining Class Constructor Name and return value! Called by the system NOT you! Default constructor: unavailable if?? Initialization of variables Declaration + Implementation Inline declaration
9
9 Creating objects With/without arguments Anonymous objects Array of objects Object data field Initializer
10
10 Access Object Access members by Object name Object pointer “this” pointer Memberwise copy Data encapsulation Accessibility keyword Getter and setter
11
Static Members Concepts Instance( 实例 ) Instance variable/function vs. static variable/function 11 To declare: static type var_name;//In declaration static type functionName(parameters){} To initialize: type ClassName::var_name = 0; //re-declare it with initial value in implementation To access/call: (ClassName::)var_name… ClassName::functionName(arguments); Can a static function call an instance function?
12
Constant Member Functions 12 class Point{ public: int GetX() const; int GetY() const; void SetPt (int, int); void OffsetPt (int, int); private: int xVal, yVal; }; --The function that won’t change the object’s data members. --Part of the function signature! --Overloading?
13
Destructors Concept Opposite of constructor 13 ~Circle() { numberOfObjects--; } Notes: 1.No return value, no parameters So, no overloading 2.A default destructor is available if No destructor is explicitly defined 3.A destructor is useful if some resource, e.g. memory is allocated dynamically by an object
14
Copy Constructor 14 ClassName(ClassName &); (1)Explicit object initialization (2)Copy of temporary object for parameter (3)Copy of temporary object for return value Shallow Copy vs. Deep Copy
15
Friendship Friend function Friend class 15 class Name{ … friend class FriendName; friend type funcName(); … }; 1.Where to declare? In “public” or “private” part. 2.Where to implement? Inside or outside the definition of the class
16
Pointers and Dynamic Memory Allocation
17
17 Pointer dataType * pointerName; 30 30606 ptr …… 30606 32820 Pointer ’ s name Pointer ’ s addr. Pointer ’ s value Value Pointed
18
18 Pointer vs. Array vs. Reference Array name --> constant pointer *(city+1) city[1] Pointer itself is a variable Reference is just an alias, not an “independent” variable
19
19 Strings C-string vs. C++ string class Character array vs. character pointer char city[7] = "Dallas"; char city[] = {'D', 'a', 'l', 'l', 'a', 's', '\0' }; char *pCity = "Dallas"; String functions strcpy, strcmp, strlen, … *(pcity)*(pcity+1)*(pcity+2)*(pcity+3)*(pcity+4)*(pcity+5)*(pcity+6) Pointer of constant! #include
20
Operator Overloading
21
Key Concepts Operator function Operator overloading As member As friend Functor (function object) 21
22
bool Rational::operator< (Rational &secondRational){ long n = numerator * secondRational.getDenominator() – denominator * secondRational.getNumerator(); if (n < 0) return true; else return false; } Overloading as Member 22 A member function of Rational class.Parameter: usually pass-by-reference (can by value) one for a binary operator (The other one the object of the function) keyword Rational Rational::operator+(Rational &secondRational){ return this->add(secondRational); }
23
Notes The left operand is fixed to be the operating object automatically c1 = c2 + c3 ; c1 = c2.operator+(c3); The number of parameters is determined by the operator itself You cannot change it Overloading does not change the operator precedence (优先级) and associativity (结合性) The (return) type of the operator function can be defined by you Usually the same class type to be operational in complex operation 23
24
Overloading ++ and -- 24 r1++ ++r1 Rational Rational::operator++() { numerator += denominator; return *this; } Rational Rational::operator++(){ Rational temp(numerator, denominator); numerator += denominator; return temp; } (int dummy){ 哑元参数,the value is never used; It must be “int”.
25
Overloading as Friend 25 friend ostream &operator<<(ostream &, Rational &); friend istream &operator>>(istream &, Rational &); ostream &operator<<(ostream &str, Rational &rational){ str << rational.numerator << " / " << rational.denominator; return str; } Other operators can also be overloaded as friends!
26
Object Conversion Rational::operator double() { return 1.0 * getNumerator() / getDenominator(); } 26 Rational r1(1, 4); double d = r1 + 5.1; cout << "r1 + 5.1 is " << d << endl;
27
Functor 27 class Comparer{ public: Comparer(int val = 60):vs(val){} int operator()(int); private: int vs; }; int main(){ int a[3] = {100,54,76}; Comparer cmp(70); cout<<countArray(a, 3, cmp); } int Comparer::operator()(int v){ return v>=vs; } int countArray(int a[], int s, Comparer x){ int num =0; for(int i =0; i<s; i++) if(x(a[i])) num++; return num; }
28
Inheritance and Polymorphism
29
Key Concepts Inheritance Function redefining, function overloading Polymorphism Virtual function, abstract function, abstract class Dynamic casting Upcasting, downcasting 29
30
30 Class Inheritance Syntax: B A 基类 父类 超类 Base Parent Super-Class 派生类 子类 Derived-Class Child class DerivedClass : acckeyword BaseClass{…}; class A: public B{ public: … private: … }; B A
31
31 Accessibility after Inheritance Accessibility in BaseInheritanceAccessibility in Derived public protected private ╳ public protected private ╳ public private protectedprivate ╳
32
Constructor/Destructor in Inheritance The constructors of a base class are not inherited Calling base class constructors No-Arg Constructor in Base Class Constructor and Destructor Chaining 32 Circle::Circle(double radius, string color, bool filled) :GeometricObject(color, filled) { this->radius = radius; } class A: public B{ … }; class ME: public A, public C{... D d; }; Invoking order of constructors: B, A, C, D, ME Invoking order of destructors: in reverse order
33
33 Redefining vs. Overloading Overloading( 重载 )Redefining( 重定义 ) Similarity More than one function The same name Difference Different signature (parameter list) Maybe different type (return type) The same signature The same type To provide various choices To shield/hide the original function circle1.GeometricObject::toString();
34
Polymorphism Dynamic binding Counterpart: static binding Two elements Virtual function Pointer of base class 34 int main(){ HM * hm = new HM(); hm->show(); delete hm; hm = new CN(); hm->show(); delete hm; hm = new CT(); hm->show(); delete hm; } Human Chinese Cantonese Polymorphism ( 多态 ) Upcasting and Downcasting
35
35 Virtual Function If a function is defined virtual in a base class, it is automatically virtual in all its derived classes class C { public: virtual string toString() { return "class C"; } }; class B: public C { string toString() { return "class B"; } };
36
Abstract Class and Abstract Function Abstract function: pure virtual function Abstract class: a class with abstract functions 36 virtual double getArea() = 0; virtual double getPerimeter() = 0; Why we need it?
37
Exception Handling
38
Key Concepts Exception Naive Exception Handling C++ Exception Handling Exception Classes: standard vs. custom Throw list 38
39
Template for try-throw-catch try { Code to try; throw …; More code to try; }catch (type1 e1){ Code to process the exception; } catch (type2 e2){ Code to process the exception; throw; } 39 int quotient(int num1, int num2){ if (num2 == 0) throw num1; return num1 / num2; } int main(){ //… try{ int result = quotient(num1, num2); //… } catch (int){ //… } //… } The rest code may NOT be executed! Advantages of C++ Exception Handling? When to use it? Multiple catches. The order? ?
40
Exception Propagation and Rethrow 40
41
Exception Specification throw list No throw list Empty throw list 41 returnType functionName(parameterList) throw (exceptionList); returnType functionName(parameterList) throw (); returnType functionName(parameterList); Undeclared Exceptions?
42
Template
43
Key Concepts Function template Class template 43
44
Function Template 44 template T1 funTemp { … } template T1 funTemp(T1 v1, T2 v2){ … T3 a; … }
45
Function Template Overloading 45 (a) template TYPE max(TYPE x, TYPE y); (c) template TYPE max(TYPE x[], int n); (b) template TYPE max(TYPE x, TYPE y, TYPE z); (d) double max(int x, double y); Sequence of matching: (1)The common function with matching parameter list (no type conversion); (2)The matching function template (no type conversion); (3)The common function with matching parameter list after implicit type conversion; (4) Otherwise, compiling error. Example: (4)max(array1, 5); (5)max(2.1, 4.5) (6)max(‘B’, 9) Example: (1)max(1, 1.2); (2)max(2, 3); (3)max(3, 4, 5);
46
Class Template 46 template class Stack{ public: Stack(); bool empty(); T peek(); T push(T value); T pop(); int getSize(); private: T elements[cpt]; int size; }; template Stack ::Stack(){ size = 0; } template T Stack ::push(T value){ return elements[size++] = value; } template T Stack ::pop(){ return elements[--size]; }
47
Template and Inheritance 47 Class template Nontemplate class (Common class) Specialization template class Node{/* … */}; template class Element : public Node {/* … */}; class Set : public Node {/* … */};
48
File Input/Output
49
49 File Opening and Closing “ifstream”, “ofstream”, “fstream” open() and close() File name Absolute path Relative path File open modes ios:in, ios::out, ios::binary, … Combinations Testing stream status eof(), fail(), bad(), good(), clear()
50
50 Text File I/O “ >” get(), put() getline()
51
51 Binary File I/O Binary file vs. text file read(), write() Type casting: reinterpret_cast Random access File pointers ios::beg, ios::end, ios::cur seekp(), seekg()
52
That’s all! Q&A Session: Lab session of this Week Thanks! Good Luck!
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.