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 4
#include <iostream>
#include <cstring> //for strcpy(), etc
using namespace std;
class String
{
private:
char *str; //pointer to string
public:
String(char *s) //constructor, one arg
{
int length = strlen(s); //length of string argument
str = new char[length + 1]; //get memory
strcpy(str, s); //copy argument to it
}
~String() //destructor
{
cout << "Deleting str.n";
delete[] str; //release memory
}
void display() //display the String
{
cout << str << endl;
}
};
int main()
{
String s1 = "Who knows nothing doubts nothing.";
cout << "s1 = "; //display string
s1.display();
return 0;
}
A String class using
new and delete
#include <iostream>
using namespace std;
class Distance
{
private:
int feet;
float inches;
public:
void getdist() {
cout << "nEnter feet: "; cin >> feet;
cout << "Enter inches: "; cin >> inches;
}
void showdist() {
cout << feet << "' - " << inches << '"';
}
};
int main()
{
Distance dist; //define a named Distance object
dist.getdist(); //access object members
dist.showdist(); // with dot operator
Distance* distptr; //pointer to Distance
distptr = new Distance; //points to new Distance object
distptr->getdist(); //access object members
distptr->showdist(); // with -> operator
return 0;
}
Pointer to objects
// ok but inelegant
(*distptr).getdist();
// create Distance object (access with dot)
Distance& dist = *(new Distance);
Object Oriented Programming (OOP) using C++ - Lecture 4
#include <iostream>
using namespace std;
struct link //one element of list
{
int data; //data item
link *next; //pointer to next link
};
class linklist //a list of links
{
private:
link *first; //pointer to first link
public:
linklist() //no-argument constructor
{
first = NULL; //no first link
}
void additem(int d); //add data item (one link)
void display(); //display all links
};
void linklist::additem(int d) //add data item
{
link *newlink = new link; //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
}
void linklist::display() //display all links
{
link *current = first; //set ptr to first link
while (current != NULL) //quit on last link
{
cout << current -> data << endl; //print data
current = current -> next; //move to next link
}
}
int main()
{
linklist li; //make linked list
//add four items to list
li.additem(25);
li.additem(36);
li.additem(49);
li.additem(64);
li.display(); //display entire list
return 0;
}
Linked List
Object Oriented Programming (OOP) using C++ - Lecture 4
Object Oriented Programming (OOP) using C++ - Lecture 4
Virtual Functions
– Virtual means existing in appearance but not in reality.
– When virtual functions are used, a program that appears to be calling a
function of one class may in reality be calling a function of a different
class.
– Polymorphism means different forms.
#include <iostream>
using namespace std;
class Base //base class
{
public:
void show() {
cout << "Base Class.n";
}
};
class Derv1 : public Base //derived class 1
{
public:
void show() {
cout << "Derv1 Classn";
}
};
class Derv2 : public Base //derived class 2
{
public:
void show() {
cout << "Derv2 Classn";
}
};
int main()
{
Derv1 dv1; //object of derived class 1
Derv2 dv2; //object of derived class 2
Base *ptr; //pointer to base class
ptr = &dv1; //put address of dv1 in pointer
ptr -> show(); //execute show()
ptr = &dv2; //put address of dv2 in pointer
ptr -> show(); //execute show()
return 0;
}
Example 1
Normal Member Functions
Accessed with Pointers
Object Oriented Programming (OOP) using C++ - Lecture 4
#include <iostream>
using namespace std;
class Base //base class
{
public:
//virtual function
virtual void show() {
cout << "Base Classn";
}
};
class Derv1 : public Base //derived class 1
{
public:
void show() {
cout << "Derv1 Classn";
}
};
class Derv2 : public Base //derived class 2
{
public:
void show() {
cout << "Derv2 Classn";
}
};
int main()
{
Derv1 dv1; //object of derived class 1
Derv2 dv2; //object of derived class 2
Base *ptr; //pointer to base class
ptr = &dv1; //put address of dv1 in pointer
ptr -> show(); //execute show()
ptr = &dv2; //put address of dv2 in pointer
ptr -> show(); //execute show()
return 0;
}
Example 2
Virtual Member Functions
Accessed with Pointers
The same function call ptr -> show();
executes different functions, depending
on the contents of ptr.
Late/Dynamic Binding
– Which version of show() does the compiler call?
– In fact the compiler doesn’t know what to do, so it arranges for the decision to
be deferred until the program is running.
– At runtime, when it is known what class is pointed to by ptr, the appropriate
version of draw will be called. This is called late binding or dynamic binding.
– Choosing functions in the normal way, during compilation, is called early
binding or static binding.
– <
– Late binding requires some overhead but provides increased power and
flexibility.
Abstract Classes and Pure Virtual Functions
– When we will never want to instantiate objects of a base class, we call
it an abstract class.
– Such a class exists only to act as a parent of derived classes that will be
used to instantiate objects.
– It may also provide an interface for the class hierarchy.
– How can we can mark a class as abstract? By placing at least one pure
virtual function in the base class.
– A pure virtual function is one with the expression =0 added to the
declaration.
#include <iostream>
using namespace std;
class Base //base class
{
public:
virtual void show() = 0; //pure virtual function
};
class Derv1 : public Base //derived class 1
{
public:
void show() {
cout << "Derv1 Classn";
}
};
class Derv2 : public Base //derived class 2
{
public:
void show() {
cout << "Derv2 Classn";
}
};
int main()
{
// Base bad; //can’t make object from abstract class
Derv1 dv1; //object of derived class 1
Derv2 dv2; //object of derived class 2
Base *ptr; //pointer to base class
ptr = &dv1; //put address of dv1 in pointer
ptr-> show(); //execute show()
ptr = &dv2; //put address of dv2 in pointer
ptr -> show(); //execute show()
return 0;
}
Example 1
Pure Virtual
Function
Abstract Class
=0 expression
#include <iostream>
using namespace std;
class person //person class
{
protected:
char name[40];
public:
void getName() {
cout << " Enter name: "; cin >> name;
}
void putName() {
cout << "Name: " << name << endl;
}
virtual void getData() = 0; //pure virtual func
virtual bool isOutstanding() = 0; //pure virtual func
};
class student : public person //student class
{
private:
float gpa; //grade point average
public:
void getData() //get student data from user
{
person::getName();
cout << " Enter student's GPA: "; cin >> gpa;
}
bool isOutstanding() {
return (gpa > 3.5) ? true : false;
}
};
class professor : public person //professor class
{
private:
int numPubs; //number of papers published
public:
void getData() //get professor data from user
{
person::getName();
cout << " Enter number of professor's publications: ";
cin >> numPubs;
}
bool isOutstanding() {
return (numPubs > 100) ? true : false;
}
};
int main()
{
person *persPtr[100]; //array of pointers to persons
int n = 0; //number of persons on list
char choice;
do {
cout << "Enter student or professor (s/p): ";
cin >> choice;
if (choice == 's') //put new student
persPtr[n] = new student; // in array
else //put new professor
persPtr[n] = new professor; // in array
persPtr[n++] -> getData(); //get data for person
cout << " Enter another (y/n)? "; //do another person?
cin >> choice;
} while (choice == 'y'); //cycle until not ‘y’
//print names of all persons, and say if outstanding
for (int j = 0; j < n; j++)
{
persPtr[j] -> putName();
if (persPtr[j] -> isOutstanding())
cout << " This person is outstanding!n";
}
return 0;
}
Example 2
Pure Virtual
Function
Abstract Class
=0 expression
Object Oriented Programming (OOP) using C++ - Lecture 4
Friend Function
– A friend function is a function which operates on private data from
objects of two different classes.
– The function will take objects of the two classes as arguments and
operate on their private data.
#include <iostream>
using namespace std;
class beta; //needed for frifunc declaration
class alpha
{
private:
int data;
public:
alpha() : data(3)
{ }
friend int frifunc(alpha, beta); //friend function
};
class beta
{
private:
int data;
public:
beta() : data(7)
{ }
friend int frifunc(alpha, beta); //friend function
};
int frifunc(alpha a, beta b) //function definition
{
return (a.data + b.data);
}
int main()
{
alpha aa;
beta bb;
cout << frifunc(aa, bb) << endl; //call the function
return 0;
}
Example 1
Friend Function
#include <iostream>
using namespace std;
class Distance //English Distance class
{
private:
int feet;
float inches;
public:
Distance() : feet(0), inches(0.0)
{ }
Distance(float fltfeet) //convert float to Distance
{
feet = static_cast<int>(fltfeet); //feet is integer part
inches = 12 * (fltfeet - feet); //inches is what's left
}
Distance(int ft, float in) //constructor (two args)
{
feet = ft; inches = in;
}
void showdist() //display distance
{
cout << feet << "' - " << inches << '“’;
}
Distance operator + (Distance);
};
//add this distance to d2
Distance Distance::operator + (Distance d2) //return the sum
{
int f = feet + d2.feet; //add the feet
float i = inches + d2.inches; //add the inches
if (i >= 12.0) //if total exceeds 12.0
{
i -= 12.0;
f++;
}
return Distance(f, i); //return new Distance with sum
}
int main()
{
Distance d1 = 2.5; //constructor converts
Distance d2 = 1.25; //float feet to Distance
Distance d3;
cout << "nd1 = "; d1.showdist();
cout << "nd2 = "; d2.showdist();
d3 = d1 + 10.0; //distance + float: OK (Distance(float fltfeet) ctor)
cout << "nd3 = "; d3.showdist();
// d3 = 10.0 + d1; //float + Distance: ERROR
// cout << "nd3 = "; d3.showdist();
return 0;
}
Example 2
Without Friend
Function
#include <iostream>
using namespace std;
class Distance
{
private:
int feet;
float inches;
public:
Distance() { //constructor no args
feet = 0; inches = 0.0;
}
Distance(float fltfeet) //constructor (one arg)
{ //convert float to Distance
feet = int(fltfeet); //feet is integer part
inches = 12 * (fltfeet - feet); //inches is what's left
}
Distance(int ft, float in) //constructor (two args)
{
feet = ft; inches = in;
}
void showdist() {
cout << feet << "' - " << inches << '“’;
}
friend Distance operator + (Distance, Distance); //friend
};
Distance operator + (Distance d1, Distance d2) //add d1 to d2
{
int f = d1.feet + d2.feet; //add the feet
float i = d1.inches + d2.inches; //add the inches
if (i >= 12.0) //if inches exceeds 12.0,
{
i -= 12.0;
f++;
}
return Distance(f, i); //return new Distance with sum
}
int main()
{
Distance d1 = 2.5; //constructor converts
Distance d2 = 1.25; //float-feet to Distance
Distance d3;
cout << "nd1 = "; d1.showdist();
cout << "nd2 = "; d2.showdist();
d3 = d1 + 10.0; //distance + float: OK
cout << "nd3 = "; d3.showdist();
d3 = 10.0 + d1; //float + Distance: OK
cout << "nd3 = "; d3.showdist();
return 0;
}
Example 3
Friend Function
A fix for the pervious
example
#include <iostream>
using namespace std;
//class beta;
class alpha
{
private:
int data1;
public:
alpha() : data1(99)
{ }
friend class beta; //beta is a friend class
//friend beta; // same (requires top definition)
};
class beta
{ //all member functions can access private alpha data
public:
void func1(alpha a) { cout << "ndata1 = " << a.data1; }
void func2(alpha a) { cout << "ndata1 = " << a.data1; }
};
int main()
{
alpha a;
beta b;
b.func1(a);
b.func2(a);
return 0;
}
Friend Classes
Example
Friend Class
End of lecture 4
ThankYou!

More Related Content

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

Example for Abstract Class and Interface.pdf
Example for Abstract Class and Interface.pdfExample for Abstract Class and Interface.pdf
Example for Abstract Class and Interface.pdf
rajaratna4
 
Chapter 2 OOP using C++ (Introduction).pptx
Chapter 2 OOP using C++ (Introduction).pptxChapter 2 OOP using C++ (Introduction).pptx
Chapter 2 OOP using C++ (Introduction).pptx
FiraolGadissa
 
polymorphism in c++ with Full Explanation.
polymorphism in c++ with Full Explanation.polymorphism in c++ with Full Explanation.
polymorphism in c++ with Full Explanation.
UdayGumre
 
Oops concept
Oops conceptOops concept
Oops concept
baabtra.com - No. 1 supplier of quality freshers
 
OOPS Basics With Example
OOPS Basics With ExampleOOPS Basics With Example
OOPS Basics With Example
Thooyavan Venkatachalam
 
Lecture5
Lecture5Lecture5
Lecture5
ravifeelings
 
labwork practice on inhetitance-1.pptx
labwork  practice on  inhetitance-1.pptxlabwork  practice on  inhetitance-1.pptx
labwork practice on inhetitance-1.pptx
soniasharmafdp
 
Object oriented programming 2
Object oriented programming 2Object oriented programming 2
Object oriented programming 2
Aadil Ansari
 
Overloading
OverloadingOverloading
Overloading
poonamchopra7975
 
classes & objects.ppt
classes & objects.pptclasses & objects.ppt
classes & objects.ppt
BArulmozhi
 
Object Oriented Programming using C++: Ch09 Inheritance.pptx
Object Oriented Programming using C++: Ch09 Inheritance.pptxObject Oriented Programming using C++: Ch09 Inheritance.pptx
Object Oriented Programming using C++: Ch09 Inheritance.pptx
RashidFaridChishti
 
Lecture 2, c++(complete reference,herbet sheidt)chapter-12
Lecture 2, c++(complete reference,herbet sheidt)chapter-12Lecture 2, c++(complete reference,herbet sheidt)chapter-12
Lecture 2, c++(complete reference,herbet sheidt)chapter-12
Abu Saleh
 
OO-like C Programming: Struct Inheritance and Virtual Function
OO-like C Programming: Struct Inheritance and Virtual FunctionOO-like C Programming: Struct Inheritance and Virtual Function
OO-like C Programming: Struct Inheritance and Virtual Function
Yu-Sheng (Yosen) Chen
 
OOP Lab Report.docx
OOP Lab Report.docxOOP Lab Report.docx
OOP Lab Report.docx
ArafatSahinAfridi
 
Chapter27 polymorphism-virtual-function-abstract-class
Chapter27 polymorphism-virtual-function-abstract-classChapter27 polymorphism-virtual-function-abstract-class
Chapter27 polymorphism-virtual-function-abstract-class
Deepak Singh
 
Object Oriented Programming (OOP) using C++ - Lecture 3
Object Oriented Programming (OOP) using C++ - Lecture 3Object Oriented Programming (OOP) using C++ - Lecture 3
Object Oriented Programming (OOP) using C++ - Lecture 3
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
OOC MODULE1.pptx
OOC MODULE1.pptxOOC MODULE1.pptx
OOC MODULE1.pptx
1HK19CS090MOHAMMEDSA
 
Inheritance.pptx
Inheritance.pptxInheritance.pptx
Inheritance.pptx
RutujaTandalwade
 
Oop Presentation
Oop PresentationOop Presentation
Oop Presentation
Ganesh Samarthyam
 
C# for C++ programmers
C# for C++ programmersC# for C++ programmers
C# for C++ programmers
Mark Whitaker
 
Example for Abstract Class and Interface.pdf
Example for Abstract Class and Interface.pdfExample for Abstract Class and Interface.pdf
Example for Abstract Class and Interface.pdf
rajaratna4
 
Chapter 2 OOP using C++ (Introduction).pptx
Chapter 2 OOP using C++ (Introduction).pptxChapter 2 OOP using C++ (Introduction).pptx
Chapter 2 OOP using C++ (Introduction).pptx
FiraolGadissa
 
polymorphism in c++ with Full Explanation.
polymorphism in c++ with Full Explanation.polymorphism in c++ with Full Explanation.
polymorphism in c++ with Full Explanation.
UdayGumre
 
labwork practice on inhetitance-1.pptx
labwork  practice on  inhetitance-1.pptxlabwork  practice on  inhetitance-1.pptx
labwork practice on inhetitance-1.pptx
soniasharmafdp
 
Object oriented programming 2
Object oriented programming 2Object oriented programming 2
Object oriented programming 2
Aadil Ansari
 
classes & objects.ppt
classes & objects.pptclasses & objects.ppt
classes & objects.ppt
BArulmozhi
 
Object Oriented Programming using C++: Ch09 Inheritance.pptx
Object Oriented Programming using C++: Ch09 Inheritance.pptxObject Oriented Programming using C++: Ch09 Inheritance.pptx
Object Oriented Programming using C++: Ch09 Inheritance.pptx
RashidFaridChishti
 
Lecture 2, c++(complete reference,herbet sheidt)chapter-12
Lecture 2, c++(complete reference,herbet sheidt)chapter-12Lecture 2, c++(complete reference,herbet sheidt)chapter-12
Lecture 2, c++(complete reference,herbet sheidt)chapter-12
Abu Saleh
 
OO-like C Programming: Struct Inheritance and Virtual Function
OO-like C Programming: Struct Inheritance and Virtual FunctionOO-like C Programming: Struct Inheritance and Virtual Function
OO-like C Programming: Struct Inheritance and Virtual Function
Yu-Sheng (Yosen) Chen
 
Chapter27 polymorphism-virtual-function-abstract-class
Chapter27 polymorphism-virtual-function-abstract-classChapter27 polymorphism-virtual-function-abstract-class
Chapter27 polymorphism-virtual-function-abstract-class
Deepak Singh
 
C# for C++ programmers
C# for C++ programmersC# for C++ programmers
C# for C++ programmers
Mark Whitaker
 

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
 
Object Oriented Programming (OOP) using C++ - Lecture 5
Object Oriented Programming (OOP) using C++ - Lecture 5Object Oriented Programming (OOP) using C++ - Lecture 5
Object Oriented Programming (OOP) using C++ - Lecture 5
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
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
 
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
 
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
 
Ad

Recently uploaded (20)

Porting Qt 5 QML Modules to Qt 6 Webinar
Porting Qt 5 QML Modules to Qt 6 WebinarPorting Qt 5 QML Modules to Qt 6 Webinar
Porting Qt 5 QML Modules to Qt 6 Webinar
ICS
 
Key AI Technologies Used by Indian Artificial Intelligence Companies
Key AI Technologies Used by Indian Artificial Intelligence CompaniesKey AI Technologies Used by Indian Artificial Intelligence Companies
Key AI Technologies Used by Indian Artificial Intelligence Companies
Mypcot Infotech
 
Shell Skill Tree - LabEx Certification (LabEx)
Shell Skill Tree - LabEx Certification (LabEx)Shell Skill Tree - LabEx Certification (LabEx)
Shell Skill Tree - LabEx Certification (LabEx)
VICTOR MAESTRE RAMIREZ
 
Async-ronizing Success at Wix - Patterns for Seamless Microservices - Devoxx ...
Async-ronizing Success at Wix - Patterns for Seamless Microservices - Devoxx ...Async-ronizing Success at Wix - Patterns for Seamless Microservices - Devoxx ...
Async-ronizing Success at Wix - Patterns for Seamless Microservices - Devoxx ...
Natan Silnitsky
 
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
 
wAIred_RabobankIgniteSession_12062025.pptx
wAIred_RabobankIgniteSession_12062025.pptxwAIred_RabobankIgniteSession_12062025.pptx
wAIred_RabobankIgniteSession_12062025.pptx
SimonedeGijt
 
IMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptx
IMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptxIMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptx
IMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptx
usmanch7829
 
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
 
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
 
Providing Better Biodiversity Through Better Data
Providing Better Biodiversity Through Better DataProviding Better Biodiversity Through Better Data
Providing Better Biodiversity Through Better Data
Safe Software
 
Marketo & Dynamics can be Most Excellent to Each Other – The Sequel
Marketo & Dynamics can be Most Excellent to Each Other – The SequelMarketo & Dynamics can be Most Excellent to Each Other – The Sequel
Marketo & Dynamics can be Most Excellent to Each Other – The Sequel
BradBedford3
 
Neuralink Templateeeeeeeeeeeeeeeeeeeeeeeeee
Neuralink TemplateeeeeeeeeeeeeeeeeeeeeeeeeeNeuralink Templateeeeeeeeeeeeeeeeeeeeeeeeee
Neuralink Templateeeeeeeeeeeeeeeeeeeeeeeeee
alexandernoetzold
 
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
 
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
 
Essentials of Resource Planning in a Downturn
Essentials of Resource Planning in a DownturnEssentials of Resource Planning in a Downturn
Essentials of Resource Planning in a Downturn
OnePlan Solutions
 
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
 
Top 5 Task Management Software to Boost Productivity in 2025
Top 5 Task Management Software to Boost Productivity in 2025Top 5 Task Management Software to Boost Productivity in 2025
Top 5 Task Management Software to Boost Productivity in 2025
Orangescrum
 
Wondershare PDFelement Pro 11.4.20.3548 Crack Free Download
Wondershare PDFelement Pro 11.4.20.3548 Crack Free DownloadWondershare PDFelement Pro 11.4.20.3548 Crack Free Download
Wondershare PDFelement Pro 11.4.20.3548 Crack Free Download
Puppy jhon
 
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
 
Revolutionize Your Insurance Workflow with Claims Management Software
Revolutionize Your Insurance Workflow with Claims Management SoftwareRevolutionize Your Insurance Workflow with Claims Management Software
Revolutionize Your Insurance Workflow with Claims Management Software
Insurance Tech Services
 
Porting Qt 5 QML Modules to Qt 6 Webinar
Porting Qt 5 QML Modules to Qt 6 WebinarPorting Qt 5 QML Modules to Qt 6 Webinar
Porting Qt 5 QML Modules to Qt 6 Webinar
ICS
 
Key AI Technologies Used by Indian Artificial Intelligence Companies
Key AI Technologies Used by Indian Artificial Intelligence CompaniesKey AI Technologies Used by Indian Artificial Intelligence Companies
Key AI Technologies Used by Indian Artificial Intelligence Companies
Mypcot Infotech
 
Shell Skill Tree - LabEx Certification (LabEx)
Shell Skill Tree - LabEx Certification (LabEx)Shell Skill Tree - LabEx Certification (LabEx)
Shell Skill Tree - LabEx Certification (LabEx)
VICTOR MAESTRE RAMIREZ
 
Async-ronizing Success at Wix - Patterns for Seamless Microservices - Devoxx ...
Async-ronizing Success at Wix - Patterns for Seamless Microservices - Devoxx ...Async-ronizing Success at Wix - Patterns for Seamless Microservices - Devoxx ...
Async-ronizing Success at Wix - Patterns for Seamless Microservices - Devoxx ...
Natan Silnitsky
 
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
 
wAIred_RabobankIgniteSession_12062025.pptx
wAIred_RabobankIgniteSession_12062025.pptxwAIred_RabobankIgniteSession_12062025.pptx
wAIred_RabobankIgniteSession_12062025.pptx
SimonedeGijt
 
IMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptx
IMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptxIMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptx
IMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptx
usmanch7829
 
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
 
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
 
Providing Better Biodiversity Through Better Data
Providing Better Biodiversity Through Better DataProviding Better Biodiversity Through Better Data
Providing Better Biodiversity Through Better Data
Safe Software
 
Marketo & Dynamics can be Most Excellent to Each Other – The Sequel
Marketo & Dynamics can be Most Excellent to Each Other – The SequelMarketo & Dynamics can be Most Excellent to Each Other – The Sequel
Marketo & Dynamics can be Most Excellent to Each Other – The Sequel
BradBedford3
 
Neuralink Templateeeeeeeeeeeeeeeeeeeeeeeeee
Neuralink TemplateeeeeeeeeeeeeeeeeeeeeeeeeeNeuralink Templateeeeeeeeeeeeeeeeeeeeeeeeee
Neuralink Templateeeeeeeeeeeeeeeeeeeeeeeeee
alexandernoetzold
 
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
 
Essentials of Resource Planning in a Downturn
Essentials of Resource Planning in a DownturnEssentials of Resource Planning in a Downturn
Essentials of Resource Planning in a Downturn
OnePlan Solutions
 
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
 
Top 5 Task Management Software to Boost Productivity in 2025
Top 5 Task Management Software to Boost Productivity in 2025Top 5 Task Management Software to Boost Productivity in 2025
Top 5 Task Management Software to Boost Productivity in 2025
Orangescrum
 
Wondershare PDFelement Pro 11.4.20.3548 Crack Free Download
Wondershare PDFelement Pro 11.4.20.3548 Crack Free DownloadWondershare PDFelement Pro 11.4.20.3548 Crack Free Download
Wondershare PDFelement Pro 11.4.20.3548 Crack Free Download
Puppy jhon
 
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
 
Revolutionize Your Insurance Workflow with Claims Management Software
Revolutionize Your Insurance Workflow with Claims Management SoftwareRevolutionize Your Insurance Workflow with Claims Management Software
Revolutionize Your Insurance Workflow with Claims Management Software
Insurance Tech Services
 
Ad

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

  • 1. Object Oriented Programming using C++ By Mohamed Gamal © Mohamed Gamal 2024
  • 2. The topics of today’s lecture: Agenda
  • 4. #include <iostream> #include <cstring> //for strcpy(), etc using namespace std; class String { private: char *str; //pointer to string public: String(char *s) //constructor, one arg { int length = strlen(s); //length of string argument str = new char[length + 1]; //get memory strcpy(str, s); //copy argument to it } ~String() //destructor { cout << "Deleting str.n"; delete[] str; //release memory } void display() //display the String { cout << str << endl; } }; int main() { String s1 = "Who knows nothing doubts nothing."; cout << "s1 = "; //display string s1.display(); return 0; } A String class using new and delete
  • 5. #include <iostream> using namespace std; class Distance { private: int feet; float inches; public: void getdist() { cout << "nEnter feet: "; cin >> feet; cout << "Enter inches: "; cin >> inches; } void showdist() { cout << feet << "' - " << inches << '"'; } }; int main() { Distance dist; //define a named Distance object dist.getdist(); //access object members dist.showdist(); // with dot operator Distance* distptr; //pointer to Distance distptr = new Distance; //points to new Distance object distptr->getdist(); //access object members distptr->showdist(); // with -> operator return 0; } Pointer to objects // ok but inelegant (*distptr).getdist(); // create Distance object (access with dot) Distance& dist = *(new Distance);
  • 7. #include <iostream> using namespace std; struct link //one element of list { int data; //data item link *next; //pointer to next link }; class linklist //a list of links { private: link *first; //pointer to first link public: linklist() //no-argument constructor { first = NULL; //no first link } void additem(int d); //add data item (one link) void display(); //display all links }; void linklist::additem(int d) //add data item { link *newlink = new link; //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 } void linklist::display() //display all links { link *current = first; //set ptr to first link while (current != NULL) //quit on last link { cout << current -> data << endl; //print data current = current -> next; //move to next link } } int main() { linklist li; //make linked list //add four items to list li.additem(25); li.additem(36); li.additem(49); li.additem(64); li.display(); //display entire list return 0; } Linked List
  • 10. Virtual Functions – Virtual means existing in appearance but not in reality. – When virtual functions are used, a program that appears to be calling a function of one class may in reality be calling a function of a different class. – Polymorphism means different forms.
  • 11. #include <iostream> using namespace std; class Base //base class { public: void show() { cout << "Base Class.n"; } }; class Derv1 : public Base //derived class 1 { public: void show() { cout << "Derv1 Classn"; } }; class Derv2 : public Base //derived class 2 { public: void show() { cout << "Derv2 Classn"; } }; int main() { Derv1 dv1; //object of derived class 1 Derv2 dv2; //object of derived class 2 Base *ptr; //pointer to base class ptr = &dv1; //put address of dv1 in pointer ptr -> show(); //execute show() ptr = &dv2; //put address of dv2 in pointer ptr -> show(); //execute show() return 0; } Example 1 Normal Member Functions Accessed with Pointers
  • 13. #include <iostream> using namespace std; class Base //base class { public: //virtual function virtual void show() { cout << "Base Classn"; } }; class Derv1 : public Base //derived class 1 { public: void show() { cout << "Derv1 Classn"; } }; class Derv2 : public Base //derived class 2 { public: void show() { cout << "Derv2 Classn"; } }; int main() { Derv1 dv1; //object of derived class 1 Derv2 dv2; //object of derived class 2 Base *ptr; //pointer to base class ptr = &dv1; //put address of dv1 in pointer ptr -> show(); //execute show() ptr = &dv2; //put address of dv2 in pointer ptr -> show(); //execute show() return 0; } Example 2 Virtual Member Functions Accessed with Pointers The same function call ptr -> show(); executes different functions, depending on the contents of ptr.
  • 14. Late/Dynamic Binding – Which version of show() does the compiler call? – In fact the compiler doesn’t know what to do, so it arranges for the decision to be deferred until the program is running. – At runtime, when it is known what class is pointed to by ptr, the appropriate version of draw will be called. This is called late binding or dynamic binding. – Choosing functions in the normal way, during compilation, is called early binding or static binding. – < – Late binding requires some overhead but provides increased power and flexibility.
  • 15. Abstract Classes and Pure Virtual Functions – When we will never want to instantiate objects of a base class, we call it an abstract class. – Such a class exists only to act as a parent of derived classes that will be used to instantiate objects. – It may also provide an interface for the class hierarchy. – How can we can mark a class as abstract? By placing at least one pure virtual function in the base class. – A pure virtual function is one with the expression =0 added to the declaration.
  • 16. #include <iostream> using namespace std; class Base //base class { public: virtual void show() = 0; //pure virtual function }; class Derv1 : public Base //derived class 1 { public: void show() { cout << "Derv1 Classn"; } }; class Derv2 : public Base //derived class 2 { public: void show() { cout << "Derv2 Classn"; } }; int main() { // Base bad; //can’t make object from abstract class Derv1 dv1; //object of derived class 1 Derv2 dv2; //object of derived class 2 Base *ptr; //pointer to base class ptr = &dv1; //put address of dv1 in pointer ptr-> show(); //execute show() ptr = &dv2; //put address of dv2 in pointer ptr -> show(); //execute show() return 0; } Example 1 Pure Virtual Function Abstract Class =0 expression
  • 17. #include <iostream> using namespace std; class person //person class { protected: char name[40]; public: void getName() { cout << " Enter name: "; cin >> name; } void putName() { cout << "Name: " << name << endl; } virtual void getData() = 0; //pure virtual func virtual bool isOutstanding() = 0; //pure virtual func }; class student : public person //student class { private: float gpa; //grade point average public: void getData() //get student data from user { person::getName(); cout << " Enter student's GPA: "; cin >> gpa; } bool isOutstanding() { return (gpa > 3.5) ? true : false; } }; class professor : public person //professor class { private: int numPubs; //number of papers published public: void getData() //get professor data from user { person::getName(); cout << " Enter number of professor's publications: "; cin >> numPubs; } bool isOutstanding() { return (numPubs > 100) ? true : false; } }; int main() { person *persPtr[100]; //array of pointers to persons int n = 0; //number of persons on list char choice; do { cout << "Enter student or professor (s/p): "; cin >> choice; if (choice == 's') //put new student persPtr[n] = new student; // in array else //put new professor persPtr[n] = new professor; // in array persPtr[n++] -> getData(); //get data for person cout << " Enter another (y/n)? "; //do another person? cin >> choice; } while (choice == 'y'); //cycle until not ‘y’ //print names of all persons, and say if outstanding for (int j = 0; j < n; j++) { persPtr[j] -> putName(); if (persPtr[j] -> isOutstanding()) cout << " This person is outstanding!n"; } return 0; } Example 2 Pure Virtual Function Abstract Class =0 expression
  • 19. Friend Function – A friend function is a function which operates on private data from objects of two different classes. – The function will take objects of the two classes as arguments and operate on their private data.
  • 20. #include <iostream> using namespace std; class beta; //needed for frifunc declaration class alpha { private: int data; public: alpha() : data(3) { } friend int frifunc(alpha, beta); //friend function }; class beta { private: int data; public: beta() : data(7) { } friend int frifunc(alpha, beta); //friend function }; int frifunc(alpha a, beta b) //function definition { return (a.data + b.data); } int main() { alpha aa; beta bb; cout << frifunc(aa, bb) << endl; //call the function return 0; } Example 1 Friend Function
  • 21. #include <iostream> using namespace std; class Distance //English Distance class { private: int feet; float inches; public: Distance() : feet(0), inches(0.0) { } Distance(float fltfeet) //convert float to Distance { feet = static_cast<int>(fltfeet); //feet is integer part inches = 12 * (fltfeet - feet); //inches is what's left } Distance(int ft, float in) //constructor (two args) { feet = ft; inches = in; } void showdist() //display distance { cout << feet << "' - " << inches << '“’; } Distance operator + (Distance); }; //add this distance to d2 Distance Distance::operator + (Distance d2) //return the sum { int f = feet + d2.feet; //add the feet float i = inches + d2.inches; //add the inches if (i >= 12.0) //if total exceeds 12.0 { i -= 12.0; f++; } return Distance(f, i); //return new Distance with sum } int main() { Distance d1 = 2.5; //constructor converts Distance d2 = 1.25; //float feet to Distance Distance d3; cout << "nd1 = "; d1.showdist(); cout << "nd2 = "; d2.showdist(); d3 = d1 + 10.0; //distance + float: OK (Distance(float fltfeet) ctor) cout << "nd3 = "; d3.showdist(); // d3 = 10.0 + d1; //float + Distance: ERROR // cout << "nd3 = "; d3.showdist(); return 0; } Example 2 Without Friend Function
  • 22. #include <iostream> using namespace std; class Distance { private: int feet; float inches; public: Distance() { //constructor no args feet = 0; inches = 0.0; } Distance(float fltfeet) //constructor (one arg) { //convert float to Distance feet = int(fltfeet); //feet is integer part inches = 12 * (fltfeet - feet); //inches is what's left } Distance(int ft, float in) //constructor (two args) { feet = ft; inches = in; } void showdist() { cout << feet << "' - " << inches << '“’; } friend Distance operator + (Distance, Distance); //friend }; Distance operator + (Distance d1, Distance d2) //add d1 to d2 { int f = d1.feet + d2.feet; //add the feet float i = d1.inches + d2.inches; //add the inches if (i >= 12.0) //if inches exceeds 12.0, { i -= 12.0; f++; } return Distance(f, i); //return new Distance with sum } int main() { Distance d1 = 2.5; //constructor converts Distance d2 = 1.25; //float-feet to Distance Distance d3; cout << "nd1 = "; d1.showdist(); cout << "nd2 = "; d2.showdist(); d3 = d1 + 10.0; //distance + float: OK cout << "nd3 = "; d3.showdist(); d3 = 10.0 + d1; //float + Distance: OK cout << "nd3 = "; d3.showdist(); return 0; } Example 3 Friend Function A fix for the pervious example
  • 23. #include <iostream> using namespace std; //class beta; class alpha { private: int data1; public: alpha() : data1(99) { } friend class beta; //beta is a friend class //friend beta; // same (requires top definition) }; class beta { //all member functions can access private alpha data public: void func1(alpha a) { cout << "ndata1 = " << a.data1; } void func2(alpha a) { cout << "ndata1 = " << a.data1; } }; int main() { alpha a; beta b; b.func1(a); b.func2(a); return 0; } Friend Classes Example Friend Class
  • 24. End of lecture 4 ThankYou!