SlideShare a Scribd company logo
Object Oriented
Programming using C++
By Mohamed Gamal
© Mohamed Gamal 2024
Resources
• Text Book:
• Object Oriented Programming in C++
• 4th Edition
• By Robert Lafore
• 978-0672323089
• Sams Publisher
• Other Resources
Book Link
The topics of today’s lecture:
Agenda
Object Oriented Programming (OOP) using C++ - Lecture 1
History of C++
– C++ was developed by Bjarne Stroustrup at Bell Labs in the early 1980s as an
enhancement to C, incorporating object-oriented features.
– It became commercially available in 1985, with its first standard (C++98) published
in 1998.
– Subsequent updates (C++03, C++11, C++14, C++17, and C++20) added significant
features like templates, auto type, lambdas, and concepts, making it a powerful
tool for modern software development
– C++ continues to evolve with ongoing efforts for new standards.
– Its influence extends to languages like C#, Java, and Rust.C++
Object-Oriented Languages
– Some of the most popular Object-oriented Programming languages are:
▪ C++
▪ Java.
▪ smalltalk
▪ Eiffle.
▪ Ruby
▪ Delphi
First C++ Program
#include <iostream>
using namespace std;
int main() {
cout << "Welcome to C++!" << endl;
return 0;
}
cout is declared in this name space
Object Oriented Programming (OOP) using C++ - Lecture 1
#include <iostream>
using namespace std;
int main()
{
const int MAX = 20; //max characters in string
char str[MAX]; //string variable str
cout << "nEnter a string : ";
// cin >> setw(MAX) >> str; // space problem
cin.get(str, MAX); //put string in str (max 19 chars)
// no more than MAX chars
cout << "You entered: " << str;
cout << ", size: " << sizeof(str);
cout << endl;
return 0;
}
Arrays
– An array is a collection of variables of the same types.
#include <iostream>
using namespace std;
const int MAX = 2000; //max characters in string
char str[MAX]; //string variable str
int main()
{
cout << "nEnter a string : n";
cin.get(str, MAX, '$'); //terminate with $
cout << "You entered : n" << str << endl;
return 0;
}
Reading Multiple Lines
Structures
– A structure is a collection of variables of different types.
– The variables in a structure can be of different types:
• Some can be int, some can be float, and so on.
• The data items in a structure are called the members of the structure.
struct Car
{
int modelNumber;
int year; // manufacturing year
float price;
};
#include <iostream>
using namespace std;
struct Car
{
int modelnumber;
int year;
float price;
};
int main() {
Car car1;
car1.modelnumber = 301;
car1.year = 2019;
car1.price = 217500.00F;
//display structure members
cout << "Model: " << car1.modelnumber << endl;
cout << "Year: " << car1.year << endl;
cout << "Price $: " << car1.price << endl;
return 0;
}
#include <iostream>
using namespace std;
struct Car
{
int modelnumber;
int year;
float price;
};
int main() {
Car car1 = { 301, 2019, 217500.00F };
Car car2;
car2 = car1;
// display structure members
cout << "Model: " << car1.modelnumber << endl;
cout << "Year: " << car1.year << endl;
cout << "Price $: " << car1.price << endl;
cout << "Model: " << car2.modelnumber << endl;
cout << "Year: " << car2.year << endl;
cout << "Price $: " << car2.price << endl;
return 0;
}
Enumerations
– An enumeration is a list of all possible values, you must give a specific
name to every possible value.
– The first name in the list is given the value 0, the next name is given the
value 1, and so on.
#include <iostream>
using namespace std;
enum days_of_week { Sun, Mon, Tue, Wed, Thu, Fri, Sat };
enum pets { cat, dog, mice, canary, turtule };
int main() {
return 0;
}
Overloaded Functions
– The function overloading is in practice two functions have the same
name but their parameter lists are different (in type or in number).
#include <iostream>
using namespace std;
// Declarations
void repchar();
void repchar(char);
void repchar(char, int);
int main() {
repchar();
repchar('=');
repchar('+', 30);
return 0;
}
void repchar() // displays 45 asterisks
{
for (int j = 0; j < 45; j++) // always loops 45 times
cout << '*'; // always prints asterisk
cout << endl;
}
void repchar(char ch) // displays 45 copies of specified character
{
for (int j = 0; j < 45; j++) // always loops 45 times
cout << ch; // prints specified character
cout << endl;
}
// displays specified number of copies of specified character
void repchar(char ch, int n)
{
for (int j = 0; j < n; j++) // loops n times
cout << ch; // prints specified character
cout << endl;
}
Namespaces in C++
– Namespaces are used to organize code into logical groups and to prevent name collisions.
#include <iostream>
// Define a namespace called 'MathFunctions'
namespace MathFunctions {
double add(double a, double b) {
return a + b;
}
double subtract(double a, double b) {
return a - b;
}
}
// Define another namespace called 'Utils'
namespace Utils {
void printMessage(const std::string& message) {
std::cout << message << std::endl;
}
}
int main() {
// Use the functions defined in the MathFunctions namespace
double sum = MathFunctions::add(5.0, 3.0);
double difference = MathFunctions::subtract(5.0, 3.0);
// Print the results
std::cout << "Sum: " << sum << std::endl;
std::cout << "Difference: " << difference << std::endl;
// Use the function defined in the Utils namespace
Utils::printMessage("Hello, namespaces!");
return 0;
}
Object Oriented Programming (OOP) using C++ - Lecture 1
Objects
Introduction
– Object-oriented programming (OOP)
▪ The fundamental idea behind object-oriented languages is to combine into a
single unit both data and the functions that operate on that data. Such a unit
is called an object.
▪ An object’s functions, called member functions in C++, typically provide the
only way to access its data.
▪ If you want to read a data item in an object, you call a member function in
the object. It will access the data and return the value to you.
▪ You can’t access the data directly. The data is hidden, so it is safe from
accidental alteration.
Introduction
– Object-oriented programming (OOP)
▪ Encapsulation: encapsulates data (attributes) and functions (behavior) into
packages called classes.
▪ Information Hiding: implementation details are hidden within the classes
themselves.
– Classes
▪ Classes are the standard unit of programming
▪ Objects are instantiated (created) from the class
Structures and Classes
– The only formal difference between class and struct is that in a class the
members are private by default, while in a structure they are public by
default.
struct foo {
int data1;
void func();
};
class foo {
private:
int data1;
public:
void func();
};
Class
The Object-Oriented Paradigm
An Analogy
– You might want to think of
objects as departments—such as
sales, accounting, personnel, and
so on—in a company.
Characteristics of OOP
– Programs are divided into classes and functions.
– Data is hidden and cannot be accessed by external functions.
– Use of inheritance provides reusability of code.
– New functions and data items can be added easily.
– Data is given more important than functions.
– Data and function are tied together in a single unit known as class.
– Objects communicate each other by sending messages in the form of function.
Object Oriented Programming (OOP) using C++ - Lecture 1
Car Class Example
Class Objects
Car
Toyota
BMW
Mercedes
Data Hiding
– A key feature of object-oriented programming is data hiding, this means
that data is concealed within a class so that it cannot be accessed
mistakenly by functions outside the class.
– The primary mechanism for hiding data is to put it in a class and make it
private.
▪ Private data or functions can only be accessed from within the class.
▪ Public data or functions, on the other hand, are accessible from outside the class.
C++ Access Specifiers
Example
#include <iostream>
using namespace std;
class car
{
private:
int modelnumber;
int year;
float price;
public:
void setcar(int mn, int yr, float p)
{
modelnumber = mn;
year = yr;
price = p;
}
void showcar()
{
cout << "Model: " << modelnumber << endl;
cout << "Year: " << year << endl;
cout << "Price $: " << price << endl;
}
};
int main() {
car car1; //define object of class car
car1.setcar(301, 2020, 225500.00F); //call member function
car1.showcar(); //call member function
return 0;
}
Constructor
– It’s required that an object can initialize itself when it’s first created,
without requiring a separate call to a member function.
– Automatic initialization is carried out using a special member function
called a constructor.
– A constructor is a member function that is executed automatically
whenever an object is created.
– The constructor has the same name as the class, and no return type is
used for constructors.
(The term constructor is sometimes abbreviated ctor )
Constructor Example
#include <iostream>
using namespace std;
class Counter {
private:
unsigned int count;
public:
Counter() { //constructor – Or Counter() : count(0) {}
count = 0;
}
void inc_count() {
count++;
}
int get_count() {
return count;
}
};
int main() {
Counter c1; //define and initialize
cout << "c1 = " << c1.get_count() << endl; //display
c1.inc_count(); //increment c1
cout << "c1 = " << c1.get_count() << endl; //display again
return 0;
}
– The default constructor.
Destructor
– The destructor is a special member function that is called automatically
when an object is destroyed.
– A destructor has the same name as the constructor (which is the same as
the class name) but is preceded by a tilde symbol ( ~ ).
– Destructor does not have a return value and they take no arguments.
Destructor Example
#include <iostream>
using namespace std;
class Test {
public:
// Constructor
Test() { cout << "Constructor executed" << endl; }
// Destructor
~Test() { cout << "Destructor executed" << endl; }
};
int main()
{
Test t, t1, t2, t3;
return 0;
}
Overloaded Constructors
#include <iostream>
#include <string.h>
using namespace std;
class Person
{
private:
char name[80];
char gender[7];
int age;
public:
Person()
{
strcpy(name, "Mohamed");
strcpy(gender, "Male");
age = 25;
}
Person(char _name[])
{
strcpy(name, _name);
strcpy(gender, "Male");
age = 25;
}
Person(char _name[], char _gender[])
{
strcpy(name, _name);
strcpy(gender, _gender);
age = 25;
}
Person(char _name[], char _gender[], int _age)
{
strcpy(name, _name);
strcpy(gender, _gender);
age = _age;
}
~Person() {
cout << "Destructor executed." << endl;
}
void print()
{
cout << "Name: " << name << endl;
cout << "Gender: " << gender << endl;
cout << "Age: " << age << endl;
}
};
int main()
{
Person p1, p2("Hassan", "Male", 32);
p1.print();
p2.print();
return 0;
}
#include <iostream>
#include <string>
using namespace std;
class Car {
private:
string make;
double price;
int year;
public:
Car() : make(""), price(0.0), year(0)
{ }
Car(string carMake, double carPrice, int carYear)
{
make = carMake;
price = carPrice;
year = carYear;
}
void setDetails() {
cout << "Enter car make: ";
getline(cin, make);
cout << "Enter car price: ";
cin >> price;
cout << "Enter production year: ";
cin >> year;
}
void displayDetails() const {
cout << "Car Make (Company): " << make << endl;
cout << "Car Price: " << price << endl;
cout << "Car Year: " << year << endl;
}
};
int main() {
Car myCar;
// Get car details
myCar.setDetails();
// Show the car details
cout << "Car Details:n";
myCar.displayDetails();
return 0;
}
Example
Car Class
Static Class Data
– When a member variable is defined as static within a class,
– All the objects created from that class would have access to this variable.
– It would be the same variable for all of the created objects; they would
all see the same count.
#include <iostream>
using namespace std;
class foo
{
private:
static int count; // only one data item for all objects
public:
foo() { //increments count when object created
count++;
}
int getcount() { //returns count
return count;
}
};
int foo::count = 0; // definition of 'count'
int main()
{
foo f1, f2, f3; //create three objects
//each object sees the same value
cout << "count is " << f1.getcount() << endl;
cout << "count is " << f2.getcount() << endl;
cout << "count is " << f3.getcount() << endl;
return 0;
}
#include <iostream>
#include <cstring> //for strcpy()
using namespace std;
class part
{
private:
char partname[30]; //name of widget part
int partnumber; //ID number of widget part
double cost; //cost of part
public:
void setpart(char pname[], int pn, double c)
{
strcpy(partname, pname);
partnumber = pn;
cost = c;
}
void showpart() //display data
{
cout << "nName = " << partname;
cout << ", number = " << partnumber;
cout << ", cost = $" << cost;
}
};
int main()
{
part part1, part2;
part1.setpart("handle bolt", 4473, 217.55); //set parts
part2.setpart("start lever", 9924, 419.25);
cout << "nFirst part : "; //show parts
part1.showpart();
cout << "nSecond part : ";
part2.showpart();
return 0;
}
Complete Example
End of lecture 1
ThankYou!

More Related Content

What's hot (6)

functions of C++
functions of C++functions of C++
functions of C++
tarandeep_kaur
 
virtual function
virtual functionvirtual function
virtual function
VENNILAV6
 
Python decorators
Python decoratorsPython decorators
Python decorators
Alex Su
 
Virtual base class
Virtual base classVirtual base class
Virtual base class
Tech_MX
 
Normal forms
Normal formsNormal forms
Normal forms
Samuel Igbanogu
 
Assessment of spelling skills
Assessment of spelling skillsAssessment of spelling skills
Assessment of spelling skills
Tyler Pownall
 
virtual function
virtual functionvirtual function
virtual function
VENNILAV6
 
Python decorators
Python decoratorsPython decorators
Python decorators
Alex Su
 
Virtual base class
Virtual base classVirtual base class
Virtual base class
Tech_MX
 
Assessment of spelling skills
Assessment of spelling skillsAssessment of spelling skills
Assessment of spelling skills
Tyler Pownall
 

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

INTRODUCTION TO OBJECT ORIENTED PROGRAMMING.pptx
INTRODUCTION TO OBJECT ORIENTED PROGRAMMING.pptxINTRODUCTION TO OBJECT ORIENTED PROGRAMMING.pptx
INTRODUCTION TO OBJECT ORIENTED PROGRAMMING.pptx
DeepasCSE
 
OOC MODULE1.pptx
OOC MODULE1.pptxOOC MODULE1.pptx
OOC MODULE1.pptx
1HK19CS090MOHAMMEDSA
 
C++ tutorials
C++ tutorialsC++ tutorials
C++ tutorials
Divyanshu Dubey
 
OOPS (object oriented programming) unit 1
OOPS (object oriented programming) unit 1OOPS (object oriented programming) unit 1
OOPS (object oriented programming) unit 1
AnamikaDhoundiyal
 
Object Oriented Technologies
Object Oriented TechnologiesObject Oriented Technologies
Object Oriented Technologies
Umesh Nikam
 
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
 
C++ Langauage Training in Ambala ! BATRA COMPUTER CENTRE
C++  Langauage Training in Ambala ! BATRA COMPUTER CENTREC++  Langauage Training in Ambala ! BATRA COMPUTER CENTRE
C++ Langauage Training in Ambala ! BATRA COMPUTER CENTRE
jatin batra
 
c++ Unit I.pptx
c++ Unit I.pptxc++ Unit I.pptx
c++ Unit I.pptx
Kongunadu College of Engineering and Technology
 
C++ & Data Structure - Unit - first.pptx
C++ & Data Structure - Unit - first.pptxC++ & Data Structure - Unit - first.pptx
C++ & Data Structure - Unit - first.pptx
KONGUNADU COLLEGE OF ENGINEERING AND TECHNOLOGY
 
Oops lecture 1
Oops lecture 1Oops lecture 1
Oops lecture 1
rehan16091997
 
C++ programming
C++ programmingC++ programming
C++ programming
Emertxe Information Technologies Pvt Ltd
 
C++ - A powerful and system level language
C++ - A powerful and system level languageC++ - A powerful and system level language
C++ - A powerful and system level language
dhimananshu130803
 
CSC2161Programming_in_Cpp_Lecture4-OOP Classes and Objects[1].pptx
CSC2161Programming_in_Cpp_Lecture4-OOP Classes and Objects[1].pptxCSC2161Programming_in_Cpp_Lecture4-OOP Classes and Objects[1].pptx
CSC2161Programming_in_Cpp_Lecture4-OOP Classes and Objects[1].pptx
winebaldbanituze
 
c++ ppt.ppt
c++ ppt.pptc++ ppt.ppt
c++ ppt.ppt
FarazKhan89093
 
lecture02-cpp.ppt
lecture02-cpp.pptlecture02-cpp.ppt
lecture02-cpp.ppt
MZGINBarwary
 
lecture NOTES ON OOPS C++ ON CLASS AND OBJECTS
lecture NOTES ON OOPS C++  ON CLASS AND OBJECTSlecture NOTES ON OOPS C++  ON CLASS AND OBJECTS
lecture NOTES ON OOPS C++ ON CLASS AND OBJECTS
NagarathnaRajur2
 
lecture02-cpp.ppt
lecture02-cpp.pptlecture02-cpp.ppt
lecture02-cpp.ppt
DevliNeeraj
 
lecture02-cpp.ppt
lecture02-cpp.pptlecture02-cpp.ppt
lecture02-cpp.ppt
ssuser0c24d5
 
lecture02-cpp.ppt
lecture02-cpp.pptlecture02-cpp.ppt
lecture02-cpp.ppt
nilesh405711
 
lecture02-cpp.ppt
lecture02-cpp.pptlecture02-cpp.ppt
lecture02-cpp.ppt
YashpalYadav46
 
INTRODUCTION TO OBJECT ORIENTED PROGRAMMING.pptx
INTRODUCTION TO OBJECT ORIENTED PROGRAMMING.pptxINTRODUCTION TO OBJECT ORIENTED PROGRAMMING.pptx
INTRODUCTION TO OBJECT ORIENTED PROGRAMMING.pptx
DeepasCSE
 
OOPS (object oriented programming) unit 1
OOPS (object oriented programming) unit 1OOPS (object oriented programming) unit 1
OOPS (object oriented programming) unit 1
AnamikaDhoundiyal
 
Object Oriented Technologies
Object Oriented TechnologiesObject Oriented Technologies
Object Oriented Technologies
Umesh Nikam
 
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
 
C++ Langauage Training in Ambala ! BATRA COMPUTER CENTRE
C++  Langauage Training in Ambala ! BATRA COMPUTER CENTREC++  Langauage Training in Ambala ! BATRA COMPUTER CENTRE
C++ Langauage Training in Ambala ! BATRA COMPUTER CENTRE
jatin batra
 
C++ - A powerful and system level language
C++ - A powerful and system level languageC++ - A powerful and system level language
C++ - A powerful and system level language
dhimananshu130803
 
CSC2161Programming_in_Cpp_Lecture4-OOP Classes and Objects[1].pptx
CSC2161Programming_in_Cpp_Lecture4-OOP Classes and Objects[1].pptxCSC2161Programming_in_Cpp_Lecture4-OOP Classes and Objects[1].pptx
CSC2161Programming_in_Cpp_Lecture4-OOP Classes and Objects[1].pptx
winebaldbanituze
 
lecture NOTES ON OOPS C++ ON CLASS AND OBJECTS
lecture NOTES ON OOPS C++  ON CLASS AND OBJECTSlecture NOTES ON OOPS C++  ON CLASS AND OBJECTS
lecture NOTES ON OOPS C++ ON CLASS AND OBJECTS
NagarathnaRajur2
 
lecture02-cpp.ppt
lecture02-cpp.pptlecture02-cpp.ppt
lecture02-cpp.ppt
DevliNeeraj
 
Ad

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 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
 
Object Oriented Programming (OOP) using C++ - Lecture 4
Object Oriented Programming (OOP) using C++ - Lecture 4Object Oriented Programming (OOP) using C++ - Lecture 4
Object Oriented Programming (OOP) using C++ - Lecture 4
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
 
Ad

Recently uploaded (20)

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
 
Top 11 Fleet Management Software Providers in 2025 (2).pdf
Top 11 Fleet Management Software Providers in 2025 (2).pdfTop 11 Fleet Management Software Providers in 2025 (2).pdf
Top 11 Fleet Management Software Providers in 2025 (2).pdf
Trackobit
 
COBOL Programming with VSCode - IBM Certificate
COBOL Programming with VSCode - IBM CertificateCOBOL Programming with VSCode - IBM Certificate
COBOL Programming with VSCode - IBM Certificate
VICTOR MAESTRE RAMIREZ
 
Maximizing Business Value with AWS Consulting Services.pdf
Maximizing Business Value with AWS Consulting Services.pdfMaximizing Business Value with AWS Consulting Services.pdf
Maximizing Business Value with AWS Consulting Services.pdf
Elena Mia
 
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
 
Who will create the languages of the future?
Who will create the languages of the future?Who will create the languages of the future?
Who will create the languages of the future?
Jordi Cabot
 
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
 
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
 
Integration Ignited Redefining Event-Driven Architecture at Wix - EventCentric
Integration Ignited Redefining Event-Driven Architecture at Wix - EventCentricIntegration Ignited Redefining Event-Driven Architecture at Wix - EventCentric
Integration Ignited Redefining Event-Driven Architecture at Wix - EventCentric
Natan Silnitsky
 
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
 
14 Years of Developing nCine - An Open Source 2D Game Framework
14 Years of Developing nCine - An Open Source 2D Game Framework14 Years of Developing nCine - An Open Source 2D Game Framework
14 Years of Developing nCine - An Open Source 2D Game Framework
Angelo Theodorou
 
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
 
Neuralink Templateeeeeeeeeeeeeeeeeeeeeeeeee
Neuralink TemplateeeeeeeeeeeeeeeeeeeeeeeeeeNeuralink Templateeeeeeeeeeeeeeeeeeeeeeeeee
Neuralink Templateeeeeeeeeeeeeeeeeeeeeeeeee
alexandernoetzold
 
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
 
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
 
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
 
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
 
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
 
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
 
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
 
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
 
Top 11 Fleet Management Software Providers in 2025 (2).pdf
Top 11 Fleet Management Software Providers in 2025 (2).pdfTop 11 Fleet Management Software Providers in 2025 (2).pdf
Top 11 Fleet Management Software Providers in 2025 (2).pdf
Trackobit
 
COBOL Programming with VSCode - IBM Certificate
COBOL Programming with VSCode - IBM CertificateCOBOL Programming with VSCode - IBM Certificate
COBOL Programming with VSCode - IBM Certificate
VICTOR MAESTRE RAMIREZ
 
Maximizing Business Value with AWS Consulting Services.pdf
Maximizing Business Value with AWS Consulting Services.pdfMaximizing Business Value with AWS Consulting Services.pdf
Maximizing Business Value with AWS Consulting Services.pdf
Elena Mia
 
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
 
Who will create the languages of the future?
Who will create the languages of the future?Who will create the languages of the future?
Who will create the languages of the future?
Jordi Cabot
 
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
 
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
 
Integration Ignited Redefining Event-Driven Architecture at Wix - EventCentric
Integration Ignited Redefining Event-Driven Architecture at Wix - EventCentricIntegration Ignited Redefining Event-Driven Architecture at Wix - EventCentric
Integration Ignited Redefining Event-Driven Architecture at Wix - EventCentric
Natan Silnitsky
 
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
 
14 Years of Developing nCine - An Open Source 2D Game Framework
14 Years of Developing nCine - An Open Source 2D Game Framework14 Years of Developing nCine - An Open Source 2D Game Framework
14 Years of Developing nCine - An Open Source 2D Game Framework
Angelo Theodorou
 
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
 
Neuralink Templateeeeeeeeeeeeeeeeeeeeeeeeee
Neuralink TemplateeeeeeeeeeeeeeeeeeeeeeeeeeNeuralink Templateeeeeeeeeeeeeeeeeeeeeeeeee
Neuralink Templateeeeeeeeeeeeeeeeeeeeeeeeee
alexandernoetzold
 
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
 
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
 
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
 
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
 
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
 
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
 
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
 

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

  • 1. Object Oriented Programming using C++ By Mohamed Gamal © Mohamed Gamal 2024
  • 2. Resources • Text Book: • Object Oriented Programming in C++ • 4th Edition • By Robert Lafore • 978-0672323089 • Sams Publisher • Other Resources Book Link
  • 3. The topics of today’s lecture: Agenda
  • 5. History of C++ – C++ was developed by Bjarne Stroustrup at Bell Labs in the early 1980s as an enhancement to C, incorporating object-oriented features. – It became commercially available in 1985, with its first standard (C++98) published in 1998. – Subsequent updates (C++03, C++11, C++14, C++17, and C++20) added significant features like templates, auto type, lambdas, and concepts, making it a powerful tool for modern software development – C++ continues to evolve with ongoing efforts for new standards. – Its influence extends to languages like C#, Java, and Rust.C++
  • 6. Object-Oriented Languages – Some of the most popular Object-oriented Programming languages are: ▪ C++ ▪ Java. ▪ smalltalk ▪ Eiffle. ▪ Ruby ▪ Delphi
  • 7. First C++ Program #include <iostream> using namespace std; int main() { cout << "Welcome to C++!" << endl; return 0; } cout is declared in this name space
  • 9. #include <iostream> using namespace std; int main() { const int MAX = 20; //max characters in string char str[MAX]; //string variable str cout << "nEnter a string : "; // cin >> setw(MAX) >> str; // space problem cin.get(str, MAX); //put string in str (max 19 chars) // no more than MAX chars cout << "You entered: " << str; cout << ", size: " << sizeof(str); cout << endl; return 0; } Arrays – An array is a collection of variables of the same types.
  • 10. #include <iostream> using namespace std; const int MAX = 2000; //max characters in string char str[MAX]; //string variable str int main() { cout << "nEnter a string : n"; cin.get(str, MAX, '$'); //terminate with $ cout << "You entered : n" << str << endl; return 0; } Reading Multiple Lines
  • 11. Structures – A structure is a collection of variables of different types. – The variables in a structure can be of different types: • Some can be int, some can be float, and so on. • The data items in a structure are called the members of the structure. struct Car { int modelNumber; int year; // manufacturing year float price; };
  • 12. #include <iostream> using namespace std; struct Car { int modelnumber; int year; float price; }; int main() { Car car1; car1.modelnumber = 301; car1.year = 2019; car1.price = 217500.00F; //display structure members cout << "Model: " << car1.modelnumber << endl; cout << "Year: " << car1.year << endl; cout << "Price $: " << car1.price << endl; return 0; }
  • 13. #include <iostream> using namespace std; struct Car { int modelnumber; int year; float price; }; int main() { Car car1 = { 301, 2019, 217500.00F }; Car car2; car2 = car1; // display structure members cout << "Model: " << car1.modelnumber << endl; cout << "Year: " << car1.year << endl; cout << "Price $: " << car1.price << endl; cout << "Model: " << car2.modelnumber << endl; cout << "Year: " << car2.year << endl; cout << "Price $: " << car2.price << endl; return 0; }
  • 14. Enumerations – An enumeration is a list of all possible values, you must give a specific name to every possible value. – The first name in the list is given the value 0, the next name is given the value 1, and so on. #include <iostream> using namespace std; enum days_of_week { Sun, Mon, Tue, Wed, Thu, Fri, Sat }; enum pets { cat, dog, mice, canary, turtule }; int main() { return 0; }
  • 15. Overloaded Functions – The function overloading is in practice two functions have the same name but their parameter lists are different (in type or in number). #include <iostream> using namespace std; // Declarations void repchar(); void repchar(char); void repchar(char, int); int main() { repchar(); repchar('='); repchar('+', 30); return 0; }
  • 16. void repchar() // displays 45 asterisks { for (int j = 0; j < 45; j++) // always loops 45 times cout << '*'; // always prints asterisk cout << endl; } void repchar(char ch) // displays 45 copies of specified character { for (int j = 0; j < 45; j++) // always loops 45 times cout << ch; // prints specified character cout << endl; } // displays specified number of copies of specified character void repchar(char ch, int n) { for (int j = 0; j < n; j++) // loops n times cout << ch; // prints specified character cout << endl; }
  • 17. Namespaces in C++ – Namespaces are used to organize code into logical groups and to prevent name collisions. #include <iostream> // Define a namespace called 'MathFunctions' namespace MathFunctions { double add(double a, double b) { return a + b; } double subtract(double a, double b) { return a - b; } } // Define another namespace called 'Utils' namespace Utils { void printMessage(const std::string& message) { std::cout << message << std::endl; } } int main() { // Use the functions defined in the MathFunctions namespace double sum = MathFunctions::add(5.0, 3.0); double difference = MathFunctions::subtract(5.0, 3.0); // Print the results std::cout << "Sum: " << sum << std::endl; std::cout << "Difference: " << difference << std::endl; // Use the function defined in the Utils namespace Utils::printMessage("Hello, namespaces!"); return 0; }
  • 20. Introduction – Object-oriented programming (OOP) ▪ The fundamental idea behind object-oriented languages is to combine into a single unit both data and the functions that operate on that data. Such a unit is called an object. ▪ An object’s functions, called member functions in C++, typically provide the only way to access its data. ▪ If you want to read a data item in an object, you call a member function in the object. It will access the data and return the value to you. ▪ You can’t access the data directly. The data is hidden, so it is safe from accidental alteration.
  • 21. Introduction – Object-oriented programming (OOP) ▪ Encapsulation: encapsulates data (attributes) and functions (behavior) into packages called classes. ▪ Information Hiding: implementation details are hidden within the classes themselves. – Classes ▪ Classes are the standard unit of programming ▪ Objects are instantiated (created) from the class
  • 22. Structures and Classes – The only formal difference between class and struct is that in a class the members are private by default, while in a structure they are public by default. struct foo { int data1; void func(); }; class foo { private: int data1; public: void func(); };
  • 23. Class
  • 25. An Analogy – You might want to think of objects as departments—such as sales, accounting, personnel, and so on—in a company.
  • 26. Characteristics of OOP – Programs are divided into classes and functions. – Data is hidden and cannot be accessed by external functions. – Use of inheritance provides reusability of code. – New functions and data items can be added easily. – Data is given more important than functions. – Data and function are tied together in a single unit known as class. – Objects communicate each other by sending messages in the form of function.
  • 28. Car Class Example Class Objects Car Toyota BMW Mercedes
  • 29. Data Hiding – A key feature of object-oriented programming is data hiding, this means that data is concealed within a class so that it cannot be accessed mistakenly by functions outside the class. – The primary mechanism for hiding data is to put it in a class and make it private. ▪ Private data or functions can only be accessed from within the class. ▪ Public data or functions, on the other hand, are accessible from outside the class.
  • 31. Example #include <iostream> using namespace std; class car { private: int modelnumber; int year; float price; public: void setcar(int mn, int yr, float p) { modelnumber = mn; year = yr; price = p; }
  • 32. void showcar() { cout << "Model: " << modelnumber << endl; cout << "Year: " << year << endl; cout << "Price $: " << price << endl; } }; int main() { car car1; //define object of class car car1.setcar(301, 2020, 225500.00F); //call member function car1.showcar(); //call member function return 0; }
  • 33. Constructor – It’s required that an object can initialize itself when it’s first created, without requiring a separate call to a member function. – Automatic initialization is carried out using a special member function called a constructor. – A constructor is a member function that is executed automatically whenever an object is created. – The constructor has the same name as the class, and no return type is used for constructors. (The term constructor is sometimes abbreviated ctor )
  • 34. Constructor Example #include <iostream> using namespace std; class Counter { private: unsigned int count; public: Counter() { //constructor – Or Counter() : count(0) {} count = 0; } void inc_count() { count++; } int get_count() { return count; } };
  • 35. int main() { Counter c1; //define and initialize cout << "c1 = " << c1.get_count() << endl; //display c1.inc_count(); //increment c1 cout << "c1 = " << c1.get_count() << endl; //display again return 0; } – The default constructor.
  • 36. Destructor – The destructor is a special member function that is called automatically when an object is destroyed. – A destructor has the same name as the constructor (which is the same as the class name) but is preceded by a tilde symbol ( ~ ). – Destructor does not have a return value and they take no arguments.
  • 37. Destructor Example #include <iostream> using namespace std; class Test { public: // Constructor Test() { cout << "Constructor executed" << endl; } // Destructor ~Test() { cout << "Destructor executed" << endl; } }; int main() { Test t, t1, t2, t3; return 0; }
  • 38. Overloaded Constructors #include <iostream> #include <string.h> using namespace std; class Person { private: char name[80]; char gender[7]; int age; public: Person() { strcpy(name, "Mohamed"); strcpy(gender, "Male"); age = 25; } Person(char _name[]) { strcpy(name, _name); strcpy(gender, "Male"); age = 25; }
  • 39. Person(char _name[], char _gender[]) { strcpy(name, _name); strcpy(gender, _gender); age = 25; } Person(char _name[], char _gender[], int _age) { strcpy(name, _name); strcpy(gender, _gender); age = _age; } ~Person() { cout << "Destructor executed." << endl; } void print() { cout << "Name: " << name << endl; cout << "Gender: " << gender << endl; cout << "Age: " << age << endl; } }; int main() { Person p1, p2("Hassan", "Male", 32); p1.print(); p2.print(); return 0; }
  • 40. #include <iostream> #include <string> using namespace std; class Car { private: string make; double price; int year; public: Car() : make(""), price(0.0), year(0) { } Car(string carMake, double carPrice, int carYear) { make = carMake; price = carPrice; year = carYear; } void setDetails() { cout << "Enter car make: "; getline(cin, make); cout << "Enter car price: "; cin >> price; cout << "Enter production year: "; cin >> year; } void displayDetails() const { cout << "Car Make (Company): " << make << endl; cout << "Car Price: " << price << endl; cout << "Car Year: " << year << endl; } }; int main() { Car myCar; // Get car details myCar.setDetails(); // Show the car details cout << "Car Details:n"; myCar.displayDetails(); return 0; } Example Car Class
  • 41. Static Class Data – When a member variable is defined as static within a class, – All the objects created from that class would have access to this variable. – It would be the same variable for all of the created objects; they would all see the same count.
  • 42. #include <iostream> using namespace std; class foo { private: static int count; // only one data item for all objects public: foo() { //increments count when object created count++; } int getcount() { //returns count return count; } }; int foo::count = 0; // definition of 'count' int main() { foo f1, f2, f3; //create three objects //each object sees the same value cout << "count is " << f1.getcount() << endl; cout << "count is " << f2.getcount() << endl; cout << "count is " << f3.getcount() << endl; return 0; }
  • 43. #include <iostream> #include <cstring> //for strcpy() using namespace std; class part { private: char partname[30]; //name of widget part int partnumber; //ID number of widget part double cost; //cost of part public: void setpart(char pname[], int pn, double c) { strcpy(partname, pname); partnumber = pn; cost = c; } void showpart() //display data { cout << "nName = " << partname; cout << ", number = " << partnumber; cout << ", cost = $" << cost; } }; int main() { part part1, part2; part1.setpart("handle bolt", 4473, 217.55); //set parts part2.setpart("start lever", 9924, 419.25); cout << "nFirst part : "; //show parts part1.showpart(); cout << "nSecond part : "; part2.showpart(); return 0; } Complete Example
  • 44. End of lecture 1 ThankYou!