KEMBAR78
Object Oriented Programming (OOP) using C++ - Lecture 5 | PDF
Object Oriented
Programming using C++
By Mohamed Gamal
ยฉ Mohamed Gamal 2024
The topics of todayโ€™s lecture:
Agenda
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
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.
#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
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.
#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!

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

  • 1.
    Object Oriented Programming usingC++ By Mohamed Gamal ยฉ Mohamed Gamal 2024
  • 2.
    The topics oftodayโ€™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 namespacestd; 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 namespacestd; 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 namespacestd; 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 โ€“ Templatesmake 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 ExampleScenario โ€“ 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 namespacestd; 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 namespacestd; //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 namespacestd; 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 namespacestd; 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 areused 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> usingnamespace 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 namespacestd; 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 namespacestd; 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> usingnamespace 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 lecture5 ThankYou!