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)

C++ practical
C++ practicalC++ practical
C++ practical
Rahul juneja
 
Advance C++notes
Advance C++notesAdvance C++notes
Advance C++notes
Rajiv Gupta
 
C++ process new
C++ process newC++ process new
C++ process new
敬倫 林
 
Object Oriented Programming using C++: C++ Templates.pptx
Object Oriented Programming using C++: C++ Templates.pptxObject Oriented Programming using C++: C++ Templates.pptx
Object Oriented Programming using C++: C++ Templates.pptx
RashidFaridChishti
 
OOP_EXPLAINED_example_of_cod_and_explainations.pdf
OOP_EXPLAINED_example_of_cod_and_explainations.pdfOOP_EXPLAINED_example_of_cod_and_explainations.pdf
OOP_EXPLAINED_example_of_cod_and_explainations.pdf
DerekDixmanChakowela
 
Ds lab handouts
Ds lab handoutsDs lab handouts
Ds lab handouts
Ayesha Bhatti
 
CS225_Prelecture_Notes 2nd
CS225_Prelecture_Notes 2ndCS225_Prelecture_Notes 2nd
CS225_Prelecture_Notes 2nd
Edward Chen
 
Classes
ClassesClasses
Classes
Swarup Boro
 
Object Oriented Design and Programming Unit-04
Object Oriented Design and Programming Unit-04Object Oriented Design and Programming Unit-04
Object Oriented Design and Programming Unit-04
Sivakumar M
 
Templates exception handling
Templates exception handlingTemplates exception handling
Templates exception handling
sanya6900
 
C++ aptitude
C++ aptitudeC++ aptitude
C++ aptitude
chetan_p211
 
C++ How to Program 10th Edition Deitel Solutions Manual
C++ How to Program 10th Edition Deitel Solutions ManualC++ How to Program 10th Edition Deitel Solutions Manual
C++ How to Program 10th Edition Deitel Solutions Manual
leletydanni
 
Object Oriented Programming (OOP) using C++ - Lecture 2
Object Oriented Programming (OOP) using C++ - Lecture 2Object Oriented Programming (OOP) using C++ - Lecture 2
Object Oriented Programming (OOP) using C++ - Lecture 2
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
class and objects
class and objectsclass and objects
class and objects
Payel Guria
 
how to reuse code
how to reuse codehow to reuse code
how to reuse code
jleed1
 
Object orinted programming lecture| Overlaoded Functions
Object orinted programming lecture| Overlaoded FunctionsObject orinted programming lecture| Overlaoded Functions
Object orinted programming lecture| Overlaoded Functions
cenaj3443
 
Chp 3 C++ for newbies, learn fast and earn fast
Chp 3 C++ for newbies, learn fast and earn fastChp 3 C++ for newbies, learn fast and earn fast
Chp 3 C++ for newbies, learn fast and earn fast
nhbinaaa112
 
Object Oriented Programming (OOP) using C++ - Lecture 1
Object Oriented Programming (OOP) using C++ - Lecture 1Object Oriented Programming (OOP) using C++ - Lecture 1
Object Oriented Programming (OOP) using C++ - Lecture 1
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
Stacks
StacksStacks
Stacks
Malainine Zaid
 
C++ theory
C++ theoryC++ theory
C++ theory
Shyam Khant
 
Advance C++notes
Advance C++notesAdvance C++notes
Advance C++notes
Rajiv Gupta
 
C++ process new
C++ process newC++ process new
C++ process new
敬倫 林
 
Object Oriented Programming using C++: C++ Templates.pptx
Object Oriented Programming using C++: C++ Templates.pptxObject Oriented Programming using C++: C++ Templates.pptx
Object Oriented Programming using C++: C++ Templates.pptx
RashidFaridChishti
 
OOP_EXPLAINED_example_of_cod_and_explainations.pdf
OOP_EXPLAINED_example_of_cod_and_explainations.pdfOOP_EXPLAINED_example_of_cod_and_explainations.pdf
OOP_EXPLAINED_example_of_cod_and_explainations.pdf
DerekDixmanChakowela
 
CS225_Prelecture_Notes 2nd
CS225_Prelecture_Notes 2ndCS225_Prelecture_Notes 2nd
CS225_Prelecture_Notes 2nd
Edward Chen
 
Object Oriented Design and Programming Unit-04
Object Oriented Design and Programming Unit-04Object Oriented Design and Programming Unit-04
Object Oriented Design and Programming Unit-04
Sivakumar M
 
Templates exception handling
Templates exception handlingTemplates exception handling
Templates exception handling
sanya6900
 
C++ How to Program 10th Edition Deitel Solutions Manual
C++ How to Program 10th Edition Deitel Solutions ManualC++ How to Program 10th Edition Deitel Solutions Manual
C++ How to Program 10th Edition Deitel Solutions Manual
leletydanni
 
class and objects
class and objectsclass and objects
class and objects
Payel Guria
 
how to reuse code
how to reuse codehow to reuse code
how to reuse code
jleed1
 
Object orinted programming lecture| Overlaoded Functions
Object orinted programming lecture| Overlaoded FunctionsObject orinted programming lecture| Overlaoded Functions
Object orinted programming lecture| Overlaoded Functions
cenaj3443
 
Chp 3 C++ for newbies, learn fast and earn fast
Chp 3 C++ for newbies, learn fast and earn fastChp 3 C++ for newbies, learn fast and earn fast
Chp 3 C++ for newbies, learn fast and earn fast
nhbinaaa112
 

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

How to install CS50 Library (Step-by-step guide)
How to install CS50 Library (Step-by-step guide)How to install CS50 Library (Step-by-step guide)
How to install CS50 Library (Step-by-step guide)
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
Understanding Singular Value Decomposition (SVD)
Understanding Singular Value Decomposition (SVD)Understanding Singular Value Decomposition (SVD)
Understanding Singular Value Decomposition (SVD)
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
Introduction to Linux OS (Part 2) - Tutorial
Introduction to Linux OS (Part 2) - TutorialIntroduction to Linux OS (Part 2) - Tutorial
Introduction to Linux OS (Part 2) - Tutorial
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
Introduction to Linux OS (Part 1) - Tutorial
Introduction to Linux OS (Part 1) - TutorialIntroduction to Linux OS (Part 1) - Tutorial
Introduction to Linux OS (Part 1) - Tutorial
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
How to use tmux in Linux - A basic tutorial
How to use tmux in Linux - A basic tutorialHow to use tmux in Linux - A basic tutorial
How to use tmux in Linux - A basic tutorial
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
Getting started with neural networks (NNs)
Getting started with neural networks (NNs)Getting started with neural networks (NNs)
Getting started with neural networks (NNs)
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
Understanding K-Nearest Neighbor (KNN) Algorithm
Understanding K-Nearest Neighbor (KNN) AlgorithmUnderstanding K-Nearest Neighbor (KNN) Algorithm
Understanding K-Nearest Neighbor (KNN) Algorithm
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
Understanding Convolutional Neural Networks (CNN)
Understanding Convolutional Neural Networks (CNN)Understanding Convolutional Neural Networks (CNN)
Understanding Convolutional Neural Networks (CNN)
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
Luhn's algorithm to validate Egyptian ID numbers
Luhn's algorithm to validate Egyptian ID numbersLuhn's algorithm to validate Egyptian ID numbers
Luhn's algorithm to validate Egyptian ID numbers
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
Difference between Mean and Weighted Mean
Difference between Mean and Weighted MeanDifference between Mean and Weighted Mean
Difference between Mean and Weighted Mean
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
Complier Design - Operations on Languages, RE, Finite Automata
Complier Design - Operations on Languages, RE, Finite AutomataComplier Design - Operations on Languages, RE, Finite Automata
Complier Design - Operations on Languages, RE, Finite Automata
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
Introduction to Operating System - Lecture 2
Introduction to Operating System - Lecture 2Introduction to Operating System - Lecture 2
Introduction to Operating System - Lecture 2
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
Introduction to Operating System - Lecture 1
Introduction to Operating System - Lecture 1Introduction to Operating System - Lecture 1
Introduction to Operating System - Lecture 1
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
Introduction to Operating System - Lecture 3
Introduction to Operating System - Lecture 3Introduction to Operating System - Lecture 3
Introduction to Operating System - Lecture 3
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
Introduction to Freelancing - Quick Guide
Introduction to Freelancing - Quick GuideIntroduction to Freelancing - Quick Guide
Introduction to Freelancing - Quick Guide
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
Introduction to Python Prog. - Lecture 1
Introduction to Python Prog. - Lecture 1Introduction to Python Prog. - Lecture 1
Introduction to Python Prog. - Lecture 1
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
Introduction to Python Prog. - Lecture 3
Introduction to Python Prog. - Lecture 3Introduction to Python Prog. - Lecture 3
Introduction to Python Prog. - Lecture 3
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
Introduction to Python Prog. - Lecture 2
Introduction to Python Prog. - Lecture 2Introduction to Python Prog. - Lecture 2
Introduction to Python Prog. - Lecture 2
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
Introduction to C Programming -Lecture 1
Introduction to C Programming -Lecture 1Introduction to C Programming -Lecture 1
Introduction to C Programming -Lecture 1
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
Introduction to C Programming -Lecture 2
Introduction to C Programming -Lecture 2Introduction to C Programming -Lecture 2
Introduction to C Programming -Lecture 2
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
Ad

Recently uploaded (20)

Integrating Survey123 and R&H Data Using FME
Integrating Survey123 and R&H Data Using FMEIntegrating Survey123 and R&H Data Using FME
Integrating Survey123 and R&H Data Using FME
Safe Software
 
Best Inbound Call Tracking Software for Small Businesses
Best Inbound Call Tracking Software for Small BusinessesBest Inbound Call Tracking Software for Small Businesses
Best Inbound Call Tracking Software for Small Businesses
TheTelephony
 
dp-700 exam questions sample docume .pdf
dp-700 exam questions sample docume .pdfdp-700 exam questions sample docume .pdf
dp-700 exam questions sample docume .pdf
pravkumarbiz
 
Build Smarter, Deliver Faster with Choreo - An AI Native Internal Developer P...
Build Smarter, Deliver Faster with Choreo - An AI Native Internal Developer P...Build Smarter, Deliver Faster with Choreo - An AI Native Internal Developer P...
Build Smarter, Deliver Faster with Choreo - An AI Native Internal Developer P...
WSO2
 
Meet You in the Middle: 1000x Performance for Parquet Queries on PB-Scale Dat...
Meet You in the Middle: 1000x Performance for Parquet Queries on PB-Scale Dat...Meet You in the Middle: 1000x Performance for Parquet Queries on PB-Scale Dat...
Meet You in the Middle: 1000x Performance for Parquet Queries on PB-Scale Dat...
Alluxio, Inc.
 
Migrating to Azure Cosmos DB the Right Way
Migrating to Azure Cosmos DB the Right WayMigrating to Azure Cosmos DB the Right Way
Migrating to Azure Cosmos DB the Right Way
Alexander (Alex) Komyagin
 
Code and No-Code Journeys: The Coverage Overlook
Code and No-Code Journeys: The Coverage OverlookCode and No-Code Journeys: The Coverage Overlook
Code and No-Code Journeys: The Coverage Overlook
Applitools
 
How Insurance Policy Administration Streamlines Policy Lifecycle for Agile Op...
How Insurance Policy Administration Streamlines Policy Lifecycle for Agile Op...How Insurance Policy Administration Streamlines Policy Lifecycle for Agile Op...
How Insurance Policy Administration Streamlines Policy Lifecycle for Agile Op...
Insurance Tech Services
 
FME for Climate Data: Turning Big Data into Actionable Insights
FME for Climate Data: Turning Big Data into Actionable InsightsFME for Climate Data: Turning Big Data into Actionable Insights
FME for Climate Data: Turning Big Data into Actionable Insights
Safe Software
 
Software Engineering Process, Notation & Tools Introduction - Part 4
Software Engineering Process, Notation & Tools Introduction - Part 4Software Engineering Process, Notation & Tools Introduction - Part 4
Software Engineering Process, Notation & Tools Introduction - Part 4
Gaurav Sharma
 
OpenTelemetry 101 Cloud Native Barcelona
OpenTelemetry 101 Cloud Native BarcelonaOpenTelemetry 101 Cloud Native Barcelona
OpenTelemetry 101 Cloud Native Barcelona
Imma Valls Bernaus
 
Automating Map Production With FME and Python
Automating Map Production With FME and PythonAutomating Map Production With FME and Python
Automating Map Production With FME and Python
Safe Software
 
Bonk coin airdrop_ Everything You Need to Know.pdf
Bonk coin airdrop_ Everything You Need to Know.pdfBonk coin airdrop_ Everything You Need to Know.pdf
Bonk coin airdrop_ Everything You Need to Know.pdf
Herond Labs
 
Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...
Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...
Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...
BradBedford3
 
FME as an Orchestration Tool - Peak of Data & AI 2025
FME as an Orchestration Tool - Peak of Data & AI 2025FME as an Orchestration Tool - Peak of Data & AI 2025
FME as an Orchestration Tool - Peak of Data & AI 2025
Safe Software
 
Plooma is a writing platform to plan, write, and shape books your way
Plooma is a writing platform to plan, write, and shape books your wayPlooma is a writing platform to plan, write, and shape books your way
Plooma is a writing platform to plan, write, and shape books your way
Plooma
 
AI and Deep Learning with NVIDIA Technologies
AI and Deep Learning with NVIDIA TechnologiesAI and Deep Learning with NVIDIA Technologies
AI and Deep Learning with NVIDIA Technologies
SandeepKS52
 
From Chaos to Clarity - Designing (AI-Ready) APIs with APIOps Cycles
From Chaos to Clarity - Designing (AI-Ready) APIs with APIOps CyclesFrom Chaos to Clarity - Designing (AI-Ready) APIs with APIOps Cycles
From Chaos to Clarity - Designing (AI-Ready) APIs with APIOps Cycles
Marjukka Niinioja
 
The Future of Open Source Reporting Best Alternatives to Jaspersoft.pdf
The Future of Open Source Reporting Best Alternatives to Jaspersoft.pdfThe Future of Open Source Reporting Best Alternatives to Jaspersoft.pdf
The Future of Open Source Reporting Best Alternatives to Jaspersoft.pdf
Varsha Nayak
 
IBM Rational Unified Process For Software Engineering - Introduction
IBM Rational Unified Process For Software Engineering - IntroductionIBM Rational Unified Process For Software Engineering - Introduction
IBM Rational Unified Process For Software Engineering - Introduction
Gaurav Sharma
 
Integrating Survey123 and R&H Data Using FME
Integrating Survey123 and R&H Data Using FMEIntegrating Survey123 and R&H Data Using FME
Integrating Survey123 and R&H Data Using FME
Safe Software
 
Best Inbound Call Tracking Software for Small Businesses
Best Inbound Call Tracking Software for Small BusinessesBest Inbound Call Tracking Software for Small Businesses
Best Inbound Call Tracking Software for Small Businesses
TheTelephony
 
dp-700 exam questions sample docume .pdf
dp-700 exam questions sample docume .pdfdp-700 exam questions sample docume .pdf
dp-700 exam questions sample docume .pdf
pravkumarbiz
 
Build Smarter, Deliver Faster with Choreo - An AI Native Internal Developer P...
Build Smarter, Deliver Faster with Choreo - An AI Native Internal Developer P...Build Smarter, Deliver Faster with Choreo - An AI Native Internal Developer P...
Build Smarter, Deliver Faster with Choreo - An AI Native Internal Developer P...
WSO2
 
Meet You in the Middle: 1000x Performance for Parquet Queries on PB-Scale Dat...
Meet You in the Middle: 1000x Performance for Parquet Queries on PB-Scale Dat...Meet You in the Middle: 1000x Performance for Parquet Queries on PB-Scale Dat...
Meet You in the Middle: 1000x Performance for Parquet Queries on PB-Scale Dat...
Alluxio, Inc.
 
Code and No-Code Journeys: The Coverage Overlook
Code and No-Code Journeys: The Coverage OverlookCode and No-Code Journeys: The Coverage Overlook
Code and No-Code Journeys: The Coverage Overlook
Applitools
 
How Insurance Policy Administration Streamlines Policy Lifecycle for Agile Op...
How Insurance Policy Administration Streamlines Policy Lifecycle for Agile Op...How Insurance Policy Administration Streamlines Policy Lifecycle for Agile Op...
How Insurance Policy Administration Streamlines Policy Lifecycle for Agile Op...
Insurance Tech Services
 
FME for Climate Data: Turning Big Data into Actionable Insights
FME for Climate Data: Turning Big Data into Actionable InsightsFME for Climate Data: Turning Big Data into Actionable Insights
FME for Climate Data: Turning Big Data into Actionable Insights
Safe Software
 
Software Engineering Process, Notation & Tools Introduction - Part 4
Software Engineering Process, Notation & Tools Introduction - Part 4Software Engineering Process, Notation & Tools Introduction - Part 4
Software Engineering Process, Notation & Tools Introduction - Part 4
Gaurav Sharma
 
OpenTelemetry 101 Cloud Native Barcelona
OpenTelemetry 101 Cloud Native BarcelonaOpenTelemetry 101 Cloud Native Barcelona
OpenTelemetry 101 Cloud Native Barcelona
Imma Valls Bernaus
 
Automating Map Production With FME and Python
Automating Map Production With FME and PythonAutomating Map Production With FME and Python
Automating Map Production With FME and Python
Safe Software
 
Bonk coin airdrop_ Everything You Need to Know.pdf
Bonk coin airdrop_ Everything You Need to Know.pdfBonk coin airdrop_ Everything You Need to Know.pdf
Bonk coin airdrop_ Everything You Need to Know.pdf
Herond Labs
 
Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...
Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...
Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...
BradBedford3
 
FME as an Orchestration Tool - Peak of Data & AI 2025
FME as an Orchestration Tool - Peak of Data & AI 2025FME as an Orchestration Tool - Peak of Data & AI 2025
FME as an Orchestration Tool - Peak of Data & AI 2025
Safe Software
 
Plooma is a writing platform to plan, write, and shape books your way
Plooma is a writing platform to plan, write, and shape books your wayPlooma is a writing platform to plan, write, and shape books your way
Plooma is a writing platform to plan, write, and shape books your way
Plooma
 
AI and Deep Learning with NVIDIA Technologies
AI and Deep Learning with NVIDIA TechnologiesAI and Deep Learning with NVIDIA Technologies
AI and Deep Learning with NVIDIA Technologies
SandeepKS52
 
From Chaos to Clarity - Designing (AI-Ready) APIs with APIOps Cycles
From Chaos to Clarity - Designing (AI-Ready) APIs with APIOps CyclesFrom Chaos to Clarity - Designing (AI-Ready) APIs with APIOps Cycles
From Chaos to Clarity - Designing (AI-Ready) APIs with APIOps Cycles
Marjukka Niinioja
 
The Future of Open Source Reporting Best Alternatives to Jaspersoft.pdf
The Future of Open Source Reporting Best Alternatives to Jaspersoft.pdfThe Future of Open Source Reporting Best Alternatives to Jaspersoft.pdf
The Future of Open Source Reporting Best Alternatives to Jaspersoft.pdf
Varsha Nayak
 
IBM Rational Unified Process For Software Engineering - Introduction
IBM Rational Unified Process For Software Engineering - IntroductionIBM Rational Unified Process For Software Engineering - Introduction
IBM Rational Unified Process For Software Engineering - Introduction
Gaurav Sharma
 
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!