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

PDF
Operating System Notes.pdf
PDF
OS - Process Concepts
PDF
M.c.a. (sem ii) operating systems
PPTX
Staffing level estimation
PPTX
process control block
PPT
The Evolution of Java
PPTX
Cpu scheduling
PPT
Strings
Operating System Notes.pdf
OS - Process Concepts
M.c.a. (sem ii) operating systems
Staffing level estimation
process control block
The Evolution of Java
Cpu scheduling
Strings

What's hot (20)

PPTX
Operating system components
PPT
Chapter 7 - Deadlocks
PPTX
datatypes and variables in c language
PPT
Intro automata theory
PDF
Unit 4-input-output organization
PPT
deadlock avoidance
PPTX
Kernel. Operating System
PPTX
Os unit 3 , process management
PPT
Memory : operating system ( Btech cse )
DOCX
Parallel computing persentation
PPTX
Timestamp based protocol
PPTX
Design Issues of Distributed System (1).pptx
DOC
operating system lecture notes
PDF
Syntax Directed Definition and its applications
PPTX
Binary Semaphore
PDF
5 process synchronization
PPTX
Modules in Python Programming
PPTX
Theory of automata and formal language
PDF
Cs8493 unit 2
Operating system components
Chapter 7 - Deadlocks
datatypes and variables in c language
Intro automata theory
Unit 4-input-output organization
deadlock avoidance
Kernel. Operating System
Os unit 3 , process management
Memory : operating system ( Btech cse )
Parallel computing persentation
Timestamp based protocol
Design Issues of Distributed System (1).pptx
operating system lecture notes
Syntax Directed Definition and its applications
Binary Semaphore
5 process synchronization
Modules in Python Programming
Theory of automata and formal language
Cs8493 unit 2
Ad

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

PPT
Oops lecture 1
PDF
22 scheme OOPs with C++ BCS306B_module2.pdfmodule2.pdf
PPTX
Oop concept in c++ by MUhammed Thanveer Melayi
PPTX
OOP-Lecture-05 (Constructor_Destructor).pptx
PDF
C++ Interview Questions and Answers PDF By ScholarHat
PDF
C++ Programming
PPTX
INTRODUCTION TO OBJECT ORIENTED PROGRAMMING.pptx
PPTX
OOC MODULE1.pptx
PPT
C++ tutorials
PPTX
Object Oriented Design and Programming Unit-04
PPTX
21CSC101T best ppt ever OODP UNIT-2.pptx
PPTX
Chapter1.pptx
PPTX
Lecture 3, c++(complete reference,herbet sheidt)chapter-13
PPTX
Chapter 1 (2) array and structure r.pptx
PPTX
CONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptx
PPTX
chapter 5 Templates-Introduction in C++.pptx
PPTX
USER DEFINE FUNCTION AND STRUCTURE AND UNION
PPSX
SRAVANByCPP
Oops lecture 1
22 scheme OOPs with C++ BCS306B_module2.pdfmodule2.pdf
Oop concept in c++ by MUhammed Thanveer Melayi
OOP-Lecture-05 (Constructor_Destructor).pptx
C++ Interview Questions and Answers PDF By ScholarHat
C++ Programming
INTRODUCTION TO OBJECT ORIENTED PROGRAMMING.pptx
OOC MODULE1.pptx
C++ tutorials
Object Oriented Design and Programming Unit-04
21CSC101T best ppt ever OODP UNIT-2.pptx
Chapter1.pptx
Lecture 3, c++(complete reference,herbet sheidt)chapter-13
Chapter 1 (2) array and structure r.pptx
CONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptx
chapter 5 Templates-Introduction in C++.pptx
USER DEFINE FUNCTION AND STRUCTURE AND UNION
SRAVANByCPP
Ad

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

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

Recently uploaded (20)

PDF
Design an Analysis of Algorithms II-SECS-1021-03
PPTX
Introduction to Artificial Intelligence
PDF
Softaken Excel to vCard Converter Software.pdf
PDF
Audit Checklist Design Aligning with ISO, IATF, and Industry Standards — Omne...
PDF
medical staffing services at VALiNTRY
PPTX
history of c programming in notes for students .pptx
PDF
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
PPTX
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
PDF
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
PPTX
ISO 45001 Occupational Health and Safety Management System
PDF
Which alternative to Crystal Reports is best for small or large businesses.pdf
PDF
top salesforce developer skills in 2025.pdf
PPTX
Operating system designcfffgfgggggggvggggggggg
PPT
Introduction Database Management System for Course Database
PDF
How to Migrate SBCGlobal Email to Yahoo Easily
PDF
How to Choose the Right IT Partner for Your Business in Malaysia
PPTX
CHAPTER 12 - CYBER SECURITY AND FUTURE SKILLS (1) (1).pptx
PDF
Nekopoi APK 2025 free lastest update
PDF
Design an Analysis of Algorithms I-SECS-1021-03
PDF
Wondershare Filmora 15 Crack With Activation Key [2025
Design an Analysis of Algorithms II-SECS-1021-03
Introduction to Artificial Intelligence
Softaken Excel to vCard Converter Software.pdf
Audit Checklist Design Aligning with ISO, IATF, and Industry Standards — Omne...
medical staffing services at VALiNTRY
history of c programming in notes for students .pptx
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
ISO 45001 Occupational Health and Safety Management System
Which alternative to Crystal Reports is best for small or large businesses.pdf
top salesforce developer skills in 2025.pdf
Operating system designcfffgfgggggggvggggggggg
Introduction Database Management System for Course Database
How to Migrate SBCGlobal Email to Yahoo Easily
How to Choose the Right IT Partner for Your Business in Malaysia
CHAPTER 12 - CYBER SECURITY AND FUTURE SKILLS (1) (1).pptx
Nekopoi APK 2025 free lastest update
Design an Analysis of Algorithms I-SECS-1021-03
Wondershare Filmora 15 Crack With Activation Key [2025

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!