Final Revision
Spring, 2011
Overall Assessment
Continuous assessment 20% Attendance 10% Assignments 10%
Final examination 80% Close book English
Answer in Chinese is allowed Digital dictionary is allowed
2
Question Types in Final Exam
Multiple choice (40’) Output analysis (20’) Mistake identification (10’) Fill-in-the-blank (Program completion) (10’) Program design (20’)
3
Overview
4
Fundamental of Class/Object Chapter 9, 10
Inheritance, Polymorphism Chapter 11
Operator Overloading Chapter 13
Exception Handling Chapter 14
Template Chapter 15
STL Chapters 19, 20
File Input/Output Chapter 12
Fundamental of Class/Object
Key Concepts
OOP Entity, Object, Class
State/property: data field / variable Behavior: function
Immutable Classes/Objects Static Members Destructors Copy Constructor Friend Functions/Classes
6
7
Defining Class
Constructor Name and return value! Called by the system NOT you! Default constructor: unavailable if??
Initialization of variables Declaration + Implementation Inline declaration
8
Creating objects
With/without arguments Anonymous objects Array of objects Object data field
Initializer
9
Access Object
Access members by Object name Object pointer
“this” pointer
Memberwise copy Data encapsulation
Accessibility keyword Getter and setter
Immutable Class
The object that cannot be changed after creation
10
1. Define data fields as private2. Don’t provide mutators3. No accessor functions that return a reference/pointer to a mutable
member!
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?
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?
Destructors
Concept Opposite of constructor
13
~Circle() { numberOfObjects--; }
~Circle() { numberOfObjects--; }
Notes:1. No return value, no parameters
So, no overloading2. A default destructor is available if
No destructor is explicitly defined3. A destructor is useful if some resource, e.g.
memory is allocated dynamically by an object
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
person1: Person
id = 111
birthDate
111
Memory : BirthDate
year = 1970 month = 5 day = 3 reference
Friendship
Friend function Friend class
15
class Name{ … friend class FriendName; friend type funcName(); …};
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
Inheritance and Polymorphism
Key Concepts
Inheritance Function redefining, function overloading
Polymorphism Virtual function, abstract function, abstract class
Dynamic casting
17
18
Class Inheritance
Syntax:
B
A
基类 父类 超类Base Parent Super-Class派生类 子类Derived-Class Child
class DerivedClass : acckeyword BaseClass{…};class DerivedClass : acckeyword BaseClass{…};
class A: public B{public:…private:…};
class A: public B{public:…private:…};
BA
19
Accessibility after Inheritance
Accessibility in Base Inheritance Accessibility in Derived
public
public
public
protected protected
private ╳public
protected
protected
protected protected
private ╳public
private
private
protected private
private ╳
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
20
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;};
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
Invoking order of constructors: B, A, C, D, ME
Invoking order of destructors: in reverse order
21
Redefining vs. Overloading
Overloading( 重载 ) Redefining( 重定义 )
Similarity More than one functionThe same name
Difference Different signature
(parameter list)Maybe different type
(return type)
The same signatureThe same type
To provide various choices
To shield/hide the original function
circle1.GeometricObject::toString();
Polymorphism
Dynamic binding Counterpart: static binding
Two elements Virtual function Pointer of base class
22
int main(){ HM * hm = new HM(); hm->show(); delete hm; hm = new CN(); hm->show(); delete hm; hm = new CT(); hm->show(); delete hm;}
int main(){ HM * hm = new HM(); hm->show(); delete hm; hm = new CN(); hm->show(); delete hm; hm = new CT(); hm->show(); delete hm;}
HumanChineseCantonese
HumanChineseCantonese
Polymorphism
( 多态 )
Polymorphism
( 多态 )
Upcasting and Downcasting
23
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 C { public: virtual string toString() { return "class C"; } };
class B: public C { string toString() { return "class B"; } };
class B: public C { string toString() { return "class B"; } };
Abstract Class and Abstract Function
Abstract function: pure virtual function Abstract class: a class with abstract functions
24
virtual double getArea() = 0; virtual double getPerimeter() = 0;
Why we need it?
Operator Overloading
Key Concepts
Operator function Operator overloading
As member As friend
26
bool Rational::operator< (Rational &secondRational){long n = numerator * secondRational.getDenominator() –
denominator * secondRational.getNumerator();if (n < 0) return true; else return false;
}
Overloading as Member
27
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);}
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
28
Overloading ++ and --
29
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”.
Overloading as Friend
30
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!
Object Conversion
Rational::operator double()
{
return 1.0 * getNumerator() / getDenominator();
}
31
Rational r1(1, 4);
double d = r1 + 5.1;
cout << "r1 + 5.1 is " << d << endl;
Exception Handling
Key Concepts
Exception Naive Exception Handling C++ Exception Handling Exception Classes: standard vs. custom Throw list
33
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;}
34
int quotient(int num1, int num2){ if (num2 == 0) throw num1; return num1 / num2;}int main(){ //… try{ int result = quotient(num1, num2); //… } catch (int){ //… } //…}
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!The rest code may NOT be executed!
Advantages of C++ Exception Handling?When to use it?
Multiple catches. The order?
Multiple catches. The order?
??
Exception Propagation and Rethrow
int main() { ... try { ... invoke function1; statement1; } catch (Exception1 &ex1) { Process ex1; } statement2; }
function1 { ... try { ... invoke function2; statement3; } catch (Exception2 &ex2) { Process ex2; } statement4; }
function2 { ... try { ... invoke function3; statement5; } catch (Exception3 &ex3) { Process ex3; } statement6; }
Exception thrown in function3
Call Stack
main main
function1
main
function1
main
function1
function2 function2
function3
Invocation
Exception
35
Exception Specification
throw list
No throw list Empty throw list
36
returnType functionName(parameterList) throw (exceptionList);
returnType functionName(parameterList) throw (exceptionList);
returnType functionName(parameterList) throw ();returnType functionName(parameterList) throw ();
returnType functionName(parameterList);returnType functionName(parameterList);
Undeclared Exceptions?
Template
Key Concepts
Function template Class template
38
Function Template
39
template <typename T1, typename T2, typename T3>T1 funTemp<T1 v1, T2 v2, T3 v3>{ …}
template <typename T1, typename T2, typename T3>T1 funTemp<T1 v1, T2 v2>{ … T3 a; …}
Function Template Overloading
40
(a) template <class TYPE> TYPE max(TYPE x, TYPE y);
(c) template <class TYPE> TYPE max(TYPE x[], int n);
(b) template <class TYPE> 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);
Class Template
41
template<typename T=int , int cpty>class Stack{public: Stack(); bool empty(); T peek(); T push(T value); T pop(); int getSize();private: T elements[cpt]; int size;};
template<typename T>Stack<T>::Stack(){ size = 0;}template<typename T>T Stack<T>::push(T value){ return elements[size++] = value;}
template<typename T>T Stack<T>::pop(){ return elements[--size];}
Template and Inheritance
42
Class template Nontemplate class (Common class)
Specialization
template<typename str> class Node{/* … */};template<typename thestr> class Element : public Node<thestr>{/* … */};
class Set : public Node<int>{/* … */};
STL
Key Concepts
STL STL iterator STL container
Three types STL algorithm
44
Need to know --Definitions --Features
File Input/Output
46
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()
47
Text File I/O
“<<“, “>>” get(), put() getline()
48
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()
That’s all!
Question & Answer Session:2:30~5:00pm, Jun 16 (Thu)
Room: Lab 401
Good Luck!