Lec12 (Topic 7 Advanced Topic)
Lec12 (Topic 7 Advanced Topic)
Advanced Topic
Overview
12.1 Function Template
12.2 Class Template
12.3 Vectors
12.4 Friend Functions
12.5 Exception Handling
12.1
Function Template
Introduction
• Template allows us to write generic functions or classes
(called function template, class template) that accept any
data type as parameters or attributes.
and the type parameter T may be used in place of ordinary data types within the
function definition.
The word typename here means any type.
A template may have several type parameters:
int main() {
Define a class template Pair that have 2 Pair<int> p1;
attributes of the same type. p1.set (3,5);
p1.print();
template <typename T> Pair<string> p2;
class Pair { p2.set ("Peter",
T a; "Jackson");
T b; p2.print();
public: Pair<char> p3;
void set (T a, T b) { p3.set ('P','J');
this->a = a; p3.print();
this->b = b; return 0;
} }
void print() const {
cout << "(" << a << "," Output:
<< b << ")\n"; (3,5)
} (Peter,Jackson)
}; (P,J)
Multiple Type Parameters
int main() {
Class template that can have different Pair<int,char> p1;
types of attributes p1.set (1, 'A');
p1.print();
template <typename T, typename U> Pair<char,string> p2;
class Pair { p2.set ('B',"Boy");
T a; p2.print();
U b; Pair<int,int> p3;
public: p3.set (99,99);
void set (T a, U b) { p3.print();
this->a = a; return 0;
this->b = b; }
}
void print() const {
cout << "(" << a << "," Output:
<< b << ")\n"; (1,A)
} (B,Boy)
}; (99,99)
12.3
Vectors
Vectors
• Vectors are like arrays that can change size as
your program runs
• Vectors, like arrays, have a base type
• To declare an empty vector with base type int:
vector<int> v;
• <int> identifies vector as a template class
• You can use any base type in a template class:
vector<string> v;
Initializing vector Elements
• Elements are added to a vector using the member
function push_back
• push_back adds an element in the next available position
• Example: vector<double> sample;
sample.push_back(0.0);
sample.push_back(1.1);
sample.push_back(2.2);
Accessing vector Elements
• Vectors elements are indexed starting with 0
• [ ]'s are used to read or change the value of an item:
v[i] = 42;
#include <vector>
class Parrot {
public:
void tellSecret (Human h) {
cout << h.secret; // ERROR
} Error. Non-member
}; cannot access private
member.
Example: Friend Class
// Friend class solution int main() {
class Human { Human h("I have 2 gf:P\n");
friend class Parrot; Parrot b;
string secret; b.tellSecret(h);
public: return 0;
Human (string secret) }
: secret(secret) {}
}; Output:
class Parrot { I have 2 gf:P
public:
void tellSecret (Human h) {
cout << h.secret; // Fine
} Fine. Friend class can
}; access private member.
12.5
Exception Handling
Exception
When a program is executed, unexpected situation may occur. Such
a situation is called an exception
In other word: Exception is a runtime error caused by some
abnormal conditions
Example:
• division by zero
• failure of new operator to obtain a requested amount of memory
Format: try {
// Code that may generate
// exceptions
}
try, throw, and catch blocks
throw statement:
-Use keyword throw in try block to signal that abnormal
condition or error has occurred.
-If the throw statement is executed, the codes in the try
block that appear after the throw statement won't be
executed.
Format: try {
...
throw <object>;
...
}
“<object>” is to be replaced with type of object to be thrown.
try, throw, and catch blocks
catch block:
-Write the code that catches the thrown exception in
catch block. This is the exception handler.
-Unhandled/Uncaught thrown exception will terminate the
program.
Format: try {
...
throw <object>;
...
}
// No code between try and catch
catch (<Type of Exception>) {
error handling code;
}
Example 1: try, throw, and catch blocks
int main() {
double x, y;
cin >> x >> y;
try {
if (y == 0)
throw y;
double result = x / y; Output1:No exception
cout << "Result = " << result; 1 2
} Result = 0.5
catch (double a) {
cout << "Cannot divide by zero\n";
} Output2:With exception
} 1 0
Cannot divide by zero
Example 2: try, throw, and catch blocks
double divide (double x, double y)
{ If there is an exception,
if (y == 0) throw it
throw y;
return x / y; Put code that may
} generate error in try
int main() { block
double x, y;
cin >> x >> y; If there is no exception,
try { resume execution
double result = divide (x, y);
cout << "Result = " << result;
} If there is an exception of
catch (double a) { type double,
cout << "Cannot divide by zero\ catch it
n";
}
}
double divide (double x, double y) { Output1:No exception
if (y == 0) 1 2
throw y; Result = 0.5
return x / y;
}
int main() { Output2:With exception
double x, y; 1 0
cin >> x >> y; Cannot divide by zero
try {
double result = divide (x, y);
cout << "Result = " << result;
}
catch (double a) { The type of the object
cout << "Cannot divide by zero\ being thrown must
n"; match the type of the
} parameter in the catch
} block
double divide (double x, double y) { Output1:No exception
if (y == 0) 1 2
throw y; Result = 0.5
return x / y;
}
int main() { Output2:With exception
double x, y; 1 0
cin >> x >> y; Cannot divide by zero
try {
double result = divide (x, y);
cout << "Result = " << result;
}
catch (double a) { When an exception is
cout << "Cannot divide by zero\n"; thrown, the codes that
} appear after the throw
} statement won't be
executed
Multiple catch Blocks
Some times, we might have many different exceptions for a small
block of code
Only one catch block will be executed for an exception. The catch
block that first matches the exception type would be chosen
Multiple catch Blocks
void func (int n) { int main () {
try { func (1);
if (n == 1) throw 11; // int func (3);
if (n == 3) throw 3.5; // double func (4);
cout << "n is not 1 or 3\n"; }
}
catch (double a) { // Won't catch int Output:
cout << "Catch double " << a << endl; Catch int 11
} Catch double 3.5
catch (int a) { // First match int n is not 1 or 3
cout << "Catch int " << a << endl;
}
catch (int a) { // 2nd int, never executed
cout << "Hello\n"; No implicit
} conversion of
} exception type in
catch argument
Exception Matching
• To catch every possible exception type, use ellipsis "…"
try {
}
catch (...) { // catches all exceptions
}