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

PDF
22 scheme OOPs with C++ BCS306B_module2.pdfmodule2.pdf
PPTX
Templates
PPTX
Namespaces
PPTX
Lecture 3, c++(complete reference,herbet sheidt)chapter-13
PPT
2.overview of c++ ________lecture2
PDF
C++ aptitude
PPTX
CSE107JAN2023_KMS_Intrnjononolo+CPP.pptx
PPTX
FUNCTIONS, CLASSES AND OBJECTS.pptx
22 scheme OOPs with C++ BCS306B_module2.pdfmodule2.pdf
Templates
Namespaces
Lecture 3, c++(complete reference,herbet sheidt)chapter-13
2.overview of c++ ________lecture2
C++ aptitude
CSE107JAN2023_KMS_Intrnjononolo+CPP.pptx
FUNCTIONS, CLASSES AND OBJECTS.pptx

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

PDF
C++ Nested loops, matrix and fuctions.pdf
PPT
Link list
PDF
OOP_EXPLAINED_example_of_cod_and_explainations.pdf
PPTX
Function C++
DOCX
Tugas praktikukm pemrograman c++
PDF
Functions And Header Files In C++ | Bjarne stroustrup
PPTX
Object Oriented Design and Programming Unit-04
PDF
C++ boot camp part 1/2
PDF
C++ Boot Camp Part 1
PDF
Back to the Future with TypeScript
PDF
Object Oriented Programming (OOP) using C++ - Lecture 1
PDF
C++ Topic 1.pdf from Yangon Technological University
PPTX
RTTI and Namespaces.pptx ppt of c++ programming language
PPTX
Oops presentation
DOCX
Arrry structure Stacks in data structure
ZIP
PPT
Fp201 unit5 1
PPTX
Lecture 9_Classes.pptx
PDF
Object Oriented Programming (OOP) using C++ - Lecture 4
PDF
C++aptitude questions and answers
C++ Nested loops, matrix and fuctions.pdf
Link list
OOP_EXPLAINED_example_of_cod_and_explainations.pdf
Function C++
Tugas praktikukm pemrograman c++
Functions And Header Files In C++ | Bjarne stroustrup
Object Oriented Design and Programming Unit-04
C++ boot camp part 1/2
C++ Boot Camp Part 1
Back to the Future with TypeScript
Object Oriented Programming (OOP) using C++ - Lecture 1
C++ Topic 1.pdf from Yangon Technological University
RTTI and Namespaces.pptx ppt of c++ programming language
Oops presentation
Arrry structure Stacks in data structure
Fp201 unit5 1
Lecture 9_Classes.pptx
Object Oriented Programming (OOP) using C++ - Lecture 4
C++aptitude questions and answers
Ad

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

PDF
PDF
PDF
PDF
Understanding Convolutional Neural Networks (CNN)
PDF
PDF
Complier Design - Operations on Languages, RE, Finite Automata
PDF
Object Oriented Programming (OOP) using C++ - Lecture 2
PDF
Object Oriented Programming (OOP) using C++ - Lecture 3
Understanding Convolutional Neural Networks (CNN)
Complier Design - Operations on Languages, RE, Finite Automata
Object Oriented Programming (OOP) using C++ - Lecture 2
Object Oriented Programming (OOP) using C++ - Lecture 3
Ad

Recently uploaded (20)

PDF
Comprehensive Salesforce Implementation Services.pdf
PPTX
AIRLINE PRICE API | FLIGHT API COST |
PDF
Best Practices for Rolling Out Competency Management Software.pdf
DOCX
The Future of Smart Factories Why Embedded Analytics Leads the Way
PDF
The Future of Smart Factories Why Embedded Analytics Leads the Way
PDF
ShowUs: Pharo Stream Deck (ESUG 2025, Gdansk)
PDF
How to Migrate SBCGlobal Email to Yahoo Easily
PDF
Become an Agentblazer Champion Challenge Kickoff
PDF
Multi-factor Authentication (MFA) requirement for Microsoft 365 Admin Center_...
PPTX
Safe Confined Space Entry Monitoring_ Singapore Experts.pptx
PDF
How to Choose the Most Effective Social Media Agency in Bangalore.pdf
PDF
Jenkins: An open-source automation server powering CI/CD Automation
PPT
Introduction Database Management System for Course Database
PDF
Build Multi-agent using Agent Development Kit
PPTX
Hire Expert Blazor Developers | Scalable Solutions by OnestopDA
PPTX
Materi_Pemrograman_Komputer-Looping.pptx
DOCX
The Five Best AI Cover Tools in 2025.docx
PDF
Teaching Reproducibility and Embracing Variability: From Floating-Point Exper...
PPTX
Materi-Enum-and-Record-Data-Type (1).pptx
PPTX
Benefits of DCCM for Genesys Contact Center
Comprehensive Salesforce Implementation Services.pdf
AIRLINE PRICE API | FLIGHT API COST |
Best Practices for Rolling Out Competency Management Software.pdf
The Future of Smart Factories Why Embedded Analytics Leads the Way
The Future of Smart Factories Why Embedded Analytics Leads the Way
ShowUs: Pharo Stream Deck (ESUG 2025, Gdansk)
How to Migrate SBCGlobal Email to Yahoo Easily
Become an Agentblazer Champion Challenge Kickoff
Multi-factor Authentication (MFA) requirement for Microsoft 365 Admin Center_...
Safe Confined Space Entry Monitoring_ Singapore Experts.pptx
How to Choose the Most Effective Social Media Agency in Bangalore.pdf
Jenkins: An open-source automation server powering CI/CD Automation
Introduction Database Management System for Course Database
Build Multi-agent using Agent Development Kit
Hire Expert Blazor Developers | Scalable Solutions by OnestopDA
Materi_Pemrograman_Komputer-Looping.pptx
The Five Best AI Cover Tools in 2025.docx
Teaching Reproducibility and Embracing Variability: From Floating-Point Exper...
Materi-Enum-and-Record-Data-Type (1).pptx
Benefits of DCCM for Genesys Contact Center

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!