SlideShare a Scribd company logo
Object Oriented
Programming using C++
By Mohamed Gamal
© Mohamed Gamal 2024
The topics of today’s lecture:
Agenda
Object Oriented Programming (OOP) using C++ - Lecture 5
The this Pointer
– The member functions of every object have
access to a sort of magic pointer named
this, which points to the object itself.
– Thus, any member function can find out
the address of the object of which it is a
member.
#include <iostream>
using namespace std;
class where
{
private:
char charray[10]; //occupies 10 bytes
public:
void reveal() {
cout << "nMy object's address is " << this;
}
};
int main()
{
where w1, w2, w3; //make three objects
w1.reveal(); //see where they are
w2.reveal();
w3.reveal();
return 0;
}
Example 1
this Pointer
#include <iostream>
using namespace std;
class what {
private:
int alpha;
public:
void tester() {
this->alpha = 11; //same as alpha = 11;
cout << this->alpha; //same as cout << alpha;
}
};
int main() {
what w;
w.tester();
return 0;
}
Example 2
this Pointer
#include <iostream>
using namespace std;
class alpha
{
private:
int data;
public:
alpha() : data(0)
{ }
alpha(int d) : data(d)
{ }
void display() {
cout << data;
}
alpha& operator = (alpha &a) //overloaded = operator
{
data = a.data; //not done automatically
cout << "nAssignment operator invoked";
return *this; //return copy of this alpha object
}
};
int main()
{
alpha a1(37);
alpha a2, a3;
a3 = a2 = a1; //invoke overloaded =, twice
cout << "na2 = "; a2.display(); //display a2
cout << "na3 = "; a3.display(); //display a3
return 0;
}
Example 3
this Pointer
and
= overloaded operator
Object Oriented Programming (OOP) using C++ - Lecture 5
Object Oriented Programming (OOP) using C++ - Lecture 5
Templates and
Exceptions
– Templates make it possible to use one
function or class to handle many different
data types.
– Exceptions provide a convenient, uniform
way to handle errors that occur within
classes.
– The template concept can be used in two
different ways:
▪ with functions
▪ with classes.
Function Template Example Scenario
– The following function returns an absolute value for an integer
number:
int abs(int n) {
return (n < 0) ? -n : n;
}
– To calculate the absolute value for each different data type requires
rewriting the same function for each data type.
– The solution for this problem is the function template.
Object Oriented Programming (OOP) using C++ - Lecture 5
#include <iostream>
using namespace std;
template <class T> //function template
T abs(T n) {
return (n < 0) ? -n : n;
}
int main()
{
int int1 = 5;
int int2 = -6;
long lon1 = 70000L;
long lon2 = -80000L;
double dub1 = 9.95;
double dub2 = -10.15;
//calls instantiate functions
cout << "nabs(" << int1 << ") = " << abs(int1); //abs(int)
cout << "nabs(" << int2 << ") = " << abs(int2); //abs(int)
cout << "nabs(" << lon1 << ") = " << abs(lon1); //abs(long)
cout << "nabs(" << lon2 << ") = " << abs(lon2); //abs(long)
cout << "nabs(" << dub1 << ") = " << abs(dub1); //abs(double)
cout << "nabs(" << dub2 << ") = " << abs(dub2); //abs(double)
return 0;
}
Example 1
Function Template
#include <iostream>
using namespace std;
//function returns index number of item, or -1 if not found
template <class atype>
int find(atype *array, atype value, int size)
{
for (int j = 0; j < size; j++)
if (array[j] == value)
return j;
return -1;
}
char chrArr[] = { 1, 3, 5, 9, 11, 13 }; //array
char ch = 5; //value to find
int intArr[] = { 1, 3, 5, 9, 11, 13 };
int in = 6;
long lonArr[] = { 1L, 3L, 5L, 9L, 11L, 13L };
long lo = 11L;
double dubArr[] = { 1.0, 3.0, 5.0, 9.0, 11.0, 13.0 };
double db = 4.0;
int main()
{
cout << "n 5 in chrArray, index = " << find(chrArr, ch, 6);
cout << "n 6 in intArray, index = " << find(intArr, in, 6);
cout << "n11 in lonArray, index = " << find(lonArr, lo, 6);
cout << "n 4 in dubArray, index = " << find(dubArr, db, 6);
return 0;
}
Example 2
Function Template
#include <iostream>
using namespace std;
const int MAX = 100; //size of array
template <class Type>
class Stack
{
private:
Type st[MAX]; //stack: array of any type
int top; //number of top of stack
public:
Stack() //constructor
{
top = -1;
}
void push(Type var) //put number on stack
{
st[++top] = var;
}
Type pop() //take number off stack
{
return st[top--];
}
};
int main()
{
Stack<float> s1; //s1 is object of class Stack<float>
s1.push(1111.1F); //push 3 floats, pop 3 floats
s1.push(2222.2F);
s1.push(3333.3F);
cout << "1: " << s1.pop() << endl;
cout << "2: " << s1.pop() << endl;
cout << "3: " << s1.pop() << endl;
Stack<long> s2; //s2 is object of class Stack<long>
s2.push(123123123L); //push 3 longs, pop 3 longs
s2.push(234234234L);
s2.push(345345345L);
cout << "1: " << s2.pop() << endl;
cout << "2: " << s2.pop() << endl;
cout << "3: " << s2.pop() << endl;
return 0;
}
Example 3
Function Template
#include <iostream>
using namespace std;
const int LEN = 80; //maximum length of names
class employee //employee class
{
private:
char name[LEN]; //employee name
unsigned long number; //employee number
public:
friend istream & operator >> (istream &s, employee &e);
friend ostream & operator << (ostream &s, employee &e);
};
istream & operator >> (istream &s, employee &e)
{
cout << "n Enter last name: ";
cin >> e.name;
cout << " Enter number: ";
cin >> e.number;
return s;
}
ostream & operator << (ostream &s, employee &e)
{
cout << "n Name : " << e.name;
cout << "n Number : " << e.number;
return s;
}
template<class TYPE> //struct "link<TYPE>"
struct link //one element of list
{
TYPE data; //data item
link* next; //pointer to next link
};
template<class TYPE> //class "linklist<TYPE>"
class linklist //a list of links
{
private:
link<TYPE> *first; //pointer to first link
public:
linklist() //no-argument constructor
{
first = NULL; //no first link
}
void additem(TYPE d); //add data item (one link)
void display(); //display all links
};
template<class TYPE>
void linklist<TYPE>::additem(TYPE d) //add data item
{
link<TYPE> *newlink = new link<TYPE>; //make a new link
newlink->data = d; //give it data
newlink->next = first; //it points to next link
first = newlink; //now first points to this
}
template<class TYPE>
void linklist<TYPE>::display() //display all links
{
link<TYPE> *current = first; //set ptr to first link
while (current != NULL) //quit on last link
{
cout << endl << current->data; //display data
current = current->next; //move to next link
}
}
int main()
{ //lemp is object of
linklist<employee> lemp; //class "linklist<employee>”
employee emptemp; //temporary employee storage
char ans; //user's response
do
{
cin >> emptemp; //get employee data from user
lemp.additem(emptemp); //add it to linked list ‘lemp’
cout << "nAdd another (y/n)? ";
cin >> ans;
} while (ans != 'n'); //when user is done,
lemp.display(); //display entire linked list
return 0;
}
Linked List Class
Using
Templates
Example
Object Oriented Programming (OOP) using C++ - Lecture 5
Exceptions
– Exception are used to handle errors in the objects.
– Consider a member function detects an error, and then informs the application that an
error has occurred.
– This is called throwing an exception.
– In the application, a separate section of code to is installed to handle
the error.
– This code is called an exception handler or catch block; it catches the exceptions thrown by
the member function.
– Any code in the application that uses objects of the class is enclosed in
a try block.
– Errors generated in the try block will be caught in the catch block.
Object Oriented Programming (OOP) using C++ - Lecture 5
#include <iostream>
#include <stdexcept>
using namespace std;
int main() {
try {
int numerator, denominator;
cout << "Enter numerator: ";
cin >> numerator;
cout << "Enter denominator: ";
cin >> denominator;
if (denominator == 0) {
throw runtime_error("Division by zero is not allowed.");
}
double result = static_cast<double>(numerator) / denominator;
cout << "Result: " << result << endl;
}
catch (const exception &ex) {
cerr << "An exception occurred: " << ex.what() << endl;
}
return 0;
}
Example 1
Basic Example
#include <iostream>
using namespace std;
const int MAX = 3; //stack holds 3 integers
class Stack
{
private:
int st[MAX]; //stack: array of integers
int top; //index of top of stack
public:
class Full { }; //exception class
class Empty { }; //exception class
Stack() : top(-1)
{ }
void push(int var) //put number on stack
{
if (top >= MAX - 1) //if stack full,
throw Full(); //throw Full exception
st[++top] = var;
}
int pop() //take number off stack
{
if (top < 0) //if stack empty,
throw Empty(); //throw Empty exception
return st[top--];
}
};
int main()
{
Stack s1;
try {
s1.push(11);
s1.push(22);
s1.push(33);
// s1.push(44); //oops: stack full
cout << "1: " << s1.pop() << endl;
cout << "2: " << s1.pop() << endl;
cout << "3: " << s1.pop() << endl;
// cout << "4: " << s1.pop() << endl; //oops: stack empty
}
catch (Stack::Full) {
cout << "Exception: Stack Full" << endl;
}
catch (Stack::Empty) {
cout << "Exception: Stack Empty" << endl;
}
return 0;
}
Example 2
Exceptions
#include <iostream>
using namespace std;
class Distance //English Distance class
{
private:
int feet;
float inches;
public:
class InchesEx { }; //exception class
Distance() : feet(0), inches(0.0)
{ }
Distance(int ft, float in) //constructor (two args)
{
if (in >= 12.0) //if inches too big,
throw InchesEx(); //throw exception
feet = ft;
inches = in;
}
void getdist() //get length from user
{
cout << "nEnter feet : ";
cin >> feet;
cout << "Enter inches : ";
cin >> inches;
if (inches >= 12.0) //if inches too big,
throw InchesEx(); //throw exception
}
void showdist() {
cout << feet << "' - " << inches << '“’;
}
};
int main()
{
try {
Distance dist1(17, 3.5); //2-arg constructor
Distance dist2; //no-arg constructor
dist2.getdist(); //get distance from user
//display distances
cout << "ndist1 = ";
dist1.showdist();
cout << "ndist2 = ";
dist2.showdist();
}
catch (Distance::InchesEx) {
cout << "nInitialization error: inches value is too large.";
}
return 0;
}
Example 3
Exceptions
#include <iostream>
#include <string>
using namespace std;
class Distance
{
private:
int feet;
float inches;
public:
class InchesEx //exception class
{
public:
string origin; //for name of routine
float iValue; //for faulty inches value
InchesEx(string orig, float inch) //2-arg constructor
{
origin = orig; //store string
iValue = inch; //store inches
}
};
Distance() : feet(0), inches(0.0)
{ }
Distance(int ft, float in)
{
if (in >= 12.0)
throw InchesEx("2-arg constructor", in);
feet = ft;
inches = in;
}
void getdist() //get length from user
{
cout << "nEnter feet: ";
cin >> feet;
cout << "Enter inches: ";
cin >> inches;
if (inches >= 12.0)
throw InchesEx("getdist() function", inches);
}
void showdist() //display distance
{
cout << feet << "' - " << inches << '“’;
}
};
int main()
{
try {
Distance dist1(17, 3.5); //2-arg constructor
Distance dist2; //no-arg constructor
dist2.getdist(); //get value
//display distances
cout << "ndist1 = ";
dist1.showdist();
cout << "ndist2 = ";
dist2.showdist();
}
catch (Distance::InchesEx ix) {
cout << "Initialization error in " << ix.origin << endl;
cout << "Inches value of " << ix.iValue << " is too large.";
}
return 0;
}
Example 4
Exceptions origin and
value
End of lecture 5
ThankYou!

More Related Content

Similar to Object Oriented Programming (OOP) using C++ - Lecture 5 (20)

PDF
C++ Nested loops, matrix and fuctions.pdf
yamew16788
 
PPT
Link list
Malainine Zaid
 
PDF
OOP_EXPLAINED_example_of_cod_and_explainations.pdf
DerekDixmanChakowela
 
PPTX
Function C++
Shahzad Afridi
 
DOCX
Tugas praktikukm pemrograman c++
Dendi Riadi
 
PDF
Functions And Header Files In C++ | Bjarne stroustrup
SyedHaroonShah4
 
PPTX
Object Oriented Design and Programming Unit-04
Sivakumar M
 
PDF
C++ boot camp part 1/2
Jesse Talavera-Greenberg
 
PDF
C++ Boot Camp Part 1
Jesse Talavera-Greenberg
 
PDF
Back to the Future with TypeScript
Aleš Najmann
 
PDF
Object Oriented Programming (OOP) using C++ - Lecture 1
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
PDF
C++ Topic 1.pdf from Yangon Technological University
ShweEainLinn2
 
PPTX
RTTI and Namespaces.pptx ppt of c++ programming language
ankeshshri
 
PPTX
Oops presentation
sushamaGavarskar1
 
DOCX
Arrry structure Stacks in data structure
lodhran-hayat
 
ZIP
Day 1
Pat Zearfoss
 
PPT
Fp201 unit5 1
rohassanie
 
PPTX
Lecture 9_Classes.pptx
NelyJay
 
PDF
Object Oriented Programming (OOP) using C++ - Lecture 4
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
PDF
C++aptitude questions and answers
sheibansari
 
C++ Nested loops, matrix and fuctions.pdf
yamew16788
 
Link list
Malainine Zaid
 
OOP_EXPLAINED_example_of_cod_and_explainations.pdf
DerekDixmanChakowela
 
Function C++
Shahzad Afridi
 
Tugas praktikukm pemrograman c++
Dendi Riadi
 
Functions And Header Files In C++ | Bjarne stroustrup
SyedHaroonShah4
 
Object Oriented Design and Programming Unit-04
Sivakumar M
 
C++ boot camp part 1/2
Jesse Talavera-Greenberg
 
C++ Boot Camp Part 1
Jesse Talavera-Greenberg
 
Back to the Future with TypeScript
Aleš Najmann
 
Object Oriented Programming (OOP) using C++ - Lecture 1
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
C++ Topic 1.pdf from Yangon Technological University
ShweEainLinn2
 
RTTI and Namespaces.pptx ppt of c++ programming language
ankeshshri
 
Oops presentation
sushamaGavarskar1
 
Arrry structure Stacks in data structure
lodhran-hayat
 
Fp201 unit5 1
rohassanie
 
Lecture 9_Classes.pptx
NelyJay
 
Object Oriented Programming (OOP) using C++ - Lecture 4
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
C++aptitude questions and answers
sheibansari
 

More from Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt (20)

PDF
How to install CS50 Library (Step-by-step guide)
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
PDF
Understanding Singular Value Decomposition (SVD)
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
PDF
Understanding K-Nearest Neighbor (KNN) Algorithm
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
PDF
Understanding Convolutional Neural Networks (CNN)
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
PDF
Luhn's algorithm to validate Egyptian ID numbers
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
PDF
Complier Design - Operations on Languages, RE, Finite Automata
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
PDF
Object Oriented Programming (OOP) using C++ - Lecture 2
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
PDF
Object Oriented Programming (OOP) using C++ - Lecture 3
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
Understanding Convolutional Neural Networks (CNN)
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
Complier Design - Operations on Languages, RE, Finite Automata
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
Object Oriented Programming (OOP) using C++ - Lecture 2
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
Object Oriented Programming (OOP) using C++ - Lecture 3
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
Ad

Recently uploaded (20)

PPTX
The Role of a PHP Development Company in Modern Web Development
SEO Company for School in Delhi NCR
 
PDF
Executive Business Intelligence Dashboards
vandeslie24
 
PPTX
Hardware(Central Processing Unit ) CU and ALU
RizwanaKalsoom2
 
PPTX
How Odoo Became a Game-Changer for an IT Company in Manufacturing ERP
SatishKumar2651
 
PPTX
Revolutionizing Code Modernization with AI
KrzysztofKkol1
 
PDF
Efficient, Automated Claims Processing Software for Insurers
Insurance Tech Services
 
PDF
Mobile CMMS Solutions Empowering the Frontline Workforce
CryotosCMMSSoftware
 
PDF
Unlock Efficiency with Insurance Policy Administration Systems
Insurance Tech Services
 
PDF
Continouous failure - Why do we make our lives hard?
Papp Krisztián
 
PDF
vMix Pro 28.0.0.42 Download vMix Registration key Bundle
kulindacore
 
PDF
MiniTool Partition Wizard 12.8 Crack License Key LATEST
hashhshs786
 
PPT
MergeSortfbsjbjsfk sdfik k
RafishaikIT02044
 
PDF
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pdf
Varsha Nayak
 
PDF
Letasoft Sound Booster 1.12.0.538 Crack Download+ Product Key [Latest]
HyperPc soft
 
PDF
Beyond Binaries: Understanding Diversity and Allyship in a Global Workplace -...
Imma Valls Bernaus
 
PPTX
MailsDaddy Outlook OST to PST converter.pptx
abhishekdutt366
 
PDF
Alexander Marshalov - How to use AI Assistants with your Monitoring system Q2...
VictoriaMetrics
 
PPTX
3uTools Full Crack Free Version Download [Latest] 2025
muhammadgurbazkhan
 
PPTX
Migrating Millions of Users with Debezium, Apache Kafka, and an Acyclic Synch...
MD Sayem Ahmed
 
PPTX
Engineering the Java Web Application (MVC)
abhishekoza1981
 
The Role of a PHP Development Company in Modern Web Development
SEO Company for School in Delhi NCR
 
Executive Business Intelligence Dashboards
vandeslie24
 
Hardware(Central Processing Unit ) CU and ALU
RizwanaKalsoom2
 
How Odoo Became a Game-Changer for an IT Company in Manufacturing ERP
SatishKumar2651
 
Revolutionizing Code Modernization with AI
KrzysztofKkol1
 
Efficient, Automated Claims Processing Software for Insurers
Insurance Tech Services
 
Mobile CMMS Solutions Empowering the Frontline Workforce
CryotosCMMSSoftware
 
Unlock Efficiency with Insurance Policy Administration Systems
Insurance Tech Services
 
Continouous failure - Why do we make our lives hard?
Papp Krisztián
 
vMix Pro 28.0.0.42 Download vMix Registration key Bundle
kulindacore
 
MiniTool Partition Wizard 12.8 Crack License Key LATEST
hashhshs786
 
MergeSortfbsjbjsfk sdfik k
RafishaikIT02044
 
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pdf
Varsha Nayak
 
Letasoft Sound Booster 1.12.0.538 Crack Download+ Product Key [Latest]
HyperPc soft
 
Beyond Binaries: Understanding Diversity and Allyship in a Global Workplace -...
Imma Valls Bernaus
 
MailsDaddy Outlook OST to PST converter.pptx
abhishekdutt366
 
Alexander Marshalov - How to use AI Assistants with your Monitoring system Q2...
VictoriaMetrics
 
3uTools Full Crack Free Version Download [Latest] 2025
muhammadgurbazkhan
 
Migrating Millions of Users with Debezium, Apache Kafka, and an Acyclic Synch...
MD Sayem Ahmed
 
Engineering the Java Web Application (MVC)
abhishekoza1981
 
Ad

Object Oriented Programming (OOP) using C++ - Lecture 5

  • 1. Object Oriented Programming using C++ By Mohamed Gamal © Mohamed Gamal 2024
  • 2. The topics of today’s lecture: Agenda
  • 4. The this Pointer – The member functions of every object have access to a sort of magic pointer named this, which points to the object itself. – Thus, any member function can find out the address of the object of which it is a member.
  • 5. #include <iostream> using namespace std; class where { private: char charray[10]; //occupies 10 bytes public: void reveal() { cout << "nMy object's address is " << this; } }; int main() { where w1, w2, w3; //make three objects w1.reveal(); //see where they are w2.reveal(); w3.reveal(); return 0; } Example 1 this Pointer
  • 6. #include <iostream> using namespace std; class what { private: int alpha; public: void tester() { this->alpha = 11; //same as alpha = 11; cout << this->alpha; //same as cout << alpha; } }; int main() { what w; w.tester(); return 0; } Example 2 this Pointer
  • 7. #include <iostream> using namespace std; class alpha { private: int data; public: alpha() : data(0) { } alpha(int d) : data(d) { } void display() { cout << data; } alpha& operator = (alpha &a) //overloaded = operator { data = a.data; //not done automatically cout << "nAssignment operator invoked"; return *this; //return copy of this alpha object } }; int main() { alpha a1(37); alpha a2, a3; a3 = a2 = a1; //invoke overloaded =, twice cout << "na2 = "; a2.display(); //display a2 cout << "na3 = "; a3.display(); //display a3 return 0; } Example 3 this Pointer and = overloaded operator
  • 10. Templates and Exceptions – Templates make it possible to use one function or class to handle many different data types. – Exceptions provide a convenient, uniform way to handle errors that occur within classes. – The template concept can be used in two different ways: ▪ with functions ▪ with classes.
  • 11. Function Template Example Scenario – The following function returns an absolute value for an integer number: int abs(int n) { return (n < 0) ? -n : n; } – To calculate the absolute value for each different data type requires rewriting the same function for each data type. – The solution for this problem is the function template.
  • 13. #include <iostream> using namespace std; template <class T> //function template T abs(T n) { return (n < 0) ? -n : n; } int main() { int int1 = 5; int int2 = -6; long lon1 = 70000L; long lon2 = -80000L; double dub1 = 9.95; double dub2 = -10.15; //calls instantiate functions cout << "nabs(" << int1 << ") = " << abs(int1); //abs(int) cout << "nabs(" << int2 << ") = " << abs(int2); //abs(int) cout << "nabs(" << lon1 << ") = " << abs(lon1); //abs(long) cout << "nabs(" << lon2 << ") = " << abs(lon2); //abs(long) cout << "nabs(" << dub1 << ") = " << abs(dub1); //abs(double) cout << "nabs(" << dub2 << ") = " << abs(dub2); //abs(double) return 0; } Example 1 Function Template
  • 14. #include <iostream> using namespace std; //function returns index number of item, or -1 if not found template <class atype> int find(atype *array, atype value, int size) { for (int j = 0; j < size; j++) if (array[j] == value) return j; return -1; } char chrArr[] = { 1, 3, 5, 9, 11, 13 }; //array char ch = 5; //value to find int intArr[] = { 1, 3, 5, 9, 11, 13 }; int in = 6; long lonArr[] = { 1L, 3L, 5L, 9L, 11L, 13L }; long lo = 11L; double dubArr[] = { 1.0, 3.0, 5.0, 9.0, 11.0, 13.0 }; double db = 4.0; int main() { cout << "n 5 in chrArray, index = " << find(chrArr, ch, 6); cout << "n 6 in intArray, index = " << find(intArr, in, 6); cout << "n11 in lonArray, index = " << find(lonArr, lo, 6); cout << "n 4 in dubArray, index = " << find(dubArr, db, 6); return 0; } Example 2 Function Template
  • 15. #include <iostream> using namespace std; const int MAX = 100; //size of array template <class Type> class Stack { private: Type st[MAX]; //stack: array of any type int top; //number of top of stack public: Stack() //constructor { top = -1; } void push(Type var) //put number on stack { st[++top] = var; } Type pop() //take number off stack { return st[top--]; } }; int main() { Stack<float> s1; //s1 is object of class Stack<float> s1.push(1111.1F); //push 3 floats, pop 3 floats s1.push(2222.2F); s1.push(3333.3F); cout << "1: " << s1.pop() << endl; cout << "2: " << s1.pop() << endl; cout << "3: " << s1.pop() << endl; Stack<long> s2; //s2 is object of class Stack<long> s2.push(123123123L); //push 3 longs, pop 3 longs s2.push(234234234L); s2.push(345345345L); cout << "1: " << s2.pop() << endl; cout << "2: " << s2.pop() << endl; cout << "3: " << s2.pop() << endl; return 0; } Example 3 Function Template
  • 16. #include <iostream> using namespace std; const int LEN = 80; //maximum length of names class employee //employee class { private: char name[LEN]; //employee name unsigned long number; //employee number public: friend istream & operator >> (istream &s, employee &e); friend ostream & operator << (ostream &s, employee &e); }; istream & operator >> (istream &s, employee &e) { cout << "n Enter last name: "; cin >> e.name; cout << " Enter number: "; cin >> e.number; return s; } ostream & operator << (ostream &s, employee &e) { cout << "n Name : " << e.name; cout << "n Number : " << e.number; return s; } template<class TYPE> //struct "link<TYPE>" struct link //one element of list { TYPE data; //data item link* next; //pointer to next link }; template<class TYPE> //class "linklist<TYPE>" class linklist //a list of links { private: link<TYPE> *first; //pointer to first link public: linklist() //no-argument constructor { first = NULL; //no first link } void additem(TYPE d); //add data item (one link) void display(); //display all links }; template<class TYPE> void linklist<TYPE>::additem(TYPE d) //add data item { link<TYPE> *newlink = new link<TYPE>; //make a new link newlink->data = d; //give it data newlink->next = first; //it points to next link first = newlink; //now first points to this } template<class TYPE> void linklist<TYPE>::display() //display all links { link<TYPE> *current = first; //set ptr to first link while (current != NULL) //quit on last link { cout << endl << current->data; //display data current = current->next; //move to next link } } int main() { //lemp is object of linklist<employee> lemp; //class "linklist<employee>” employee emptemp; //temporary employee storage char ans; //user's response do { cin >> emptemp; //get employee data from user lemp.additem(emptemp); //add it to linked list ‘lemp’ cout << "nAdd another (y/n)? "; cin >> ans; } while (ans != 'n'); //when user is done, lemp.display(); //display entire linked list return 0; } Linked List Class Using Templates Example
  • 18. Exceptions – Exception are used to handle errors in the objects. – Consider a member function detects an error, and then informs the application that an error has occurred. – This is called throwing an exception. – In the application, a separate section of code to is installed to handle the error. – This code is called an exception handler or catch block; it catches the exceptions thrown by the member function. – Any code in the application that uses objects of the class is enclosed in a try block. – Errors generated in the try block will be caught in the catch block.
  • 20. #include <iostream> #include <stdexcept> using namespace std; int main() { try { int numerator, denominator; cout << "Enter numerator: "; cin >> numerator; cout << "Enter denominator: "; cin >> denominator; if (denominator == 0) { throw runtime_error("Division by zero is not allowed."); } double result = static_cast<double>(numerator) / denominator; cout << "Result: " << result << endl; } catch (const exception &ex) { cerr << "An exception occurred: " << ex.what() << endl; } return 0; } Example 1 Basic Example
  • 21. #include <iostream> using namespace std; const int MAX = 3; //stack holds 3 integers class Stack { private: int st[MAX]; //stack: array of integers int top; //index of top of stack public: class Full { }; //exception class class Empty { }; //exception class Stack() : top(-1) { } void push(int var) //put number on stack { if (top >= MAX - 1) //if stack full, throw Full(); //throw Full exception st[++top] = var; } int pop() //take number off stack { if (top < 0) //if stack empty, throw Empty(); //throw Empty exception return st[top--]; } }; int main() { Stack s1; try { s1.push(11); s1.push(22); s1.push(33); // s1.push(44); //oops: stack full cout << "1: " << s1.pop() << endl; cout << "2: " << s1.pop() << endl; cout << "3: " << s1.pop() << endl; // cout << "4: " << s1.pop() << endl; //oops: stack empty } catch (Stack::Full) { cout << "Exception: Stack Full" << endl; } catch (Stack::Empty) { cout << "Exception: Stack Empty" << endl; } return 0; } Example 2 Exceptions
  • 22. #include <iostream> using namespace std; class Distance //English Distance class { private: int feet; float inches; public: class InchesEx { }; //exception class Distance() : feet(0), inches(0.0) { } Distance(int ft, float in) //constructor (two args) { if (in >= 12.0) //if inches too big, throw InchesEx(); //throw exception feet = ft; inches = in; } void getdist() //get length from user { cout << "nEnter feet : "; cin >> feet; cout << "Enter inches : "; cin >> inches; if (inches >= 12.0) //if inches too big, throw InchesEx(); //throw exception } void showdist() { cout << feet << "' - " << inches << '“’; } }; int main() { try { Distance dist1(17, 3.5); //2-arg constructor Distance dist2; //no-arg constructor dist2.getdist(); //get distance from user //display distances cout << "ndist1 = "; dist1.showdist(); cout << "ndist2 = "; dist2.showdist(); } catch (Distance::InchesEx) { cout << "nInitialization error: inches value is too large."; } return 0; } Example 3 Exceptions
  • 23. #include <iostream> #include <string> using namespace std; class Distance { private: int feet; float inches; public: class InchesEx //exception class { public: string origin; //for name of routine float iValue; //for faulty inches value InchesEx(string orig, float inch) //2-arg constructor { origin = orig; //store string iValue = inch; //store inches } }; Distance() : feet(0), inches(0.0) { } Distance(int ft, float in) { if (in >= 12.0) throw InchesEx("2-arg constructor", in); feet = ft; inches = in; } void getdist() //get length from user { cout << "nEnter feet: "; cin >> feet; cout << "Enter inches: "; cin >> inches; if (inches >= 12.0) throw InchesEx("getdist() function", inches); } void showdist() //display distance { cout << feet << "' - " << inches << '“’; } }; int main() { try { Distance dist1(17, 3.5); //2-arg constructor Distance dist2; //no-arg constructor dist2.getdist(); //get value //display distances cout << "ndist1 = "; dist1.showdist(); cout << "ndist2 = "; dist2.showdist(); } catch (Distance::InchesEx ix) { cout << "Initialization error in " << ix.origin << endl; cout << "Inches value of " << ix.iValue << " is too large."; } return 0; } Example 4 Exceptions origin and value
  • 24. End of lecture 5 ThankYou!