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
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
#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; }
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.
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!

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

  • 1.
    Object Oriented Programming usingC++ 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 oftoday’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 – Someof 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 namespacestd; 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 namespacestd; 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 structureis 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 namespacestd; 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 namespacestd; 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 enumerationis 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 – Thefunction 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; }
  • 19.
  • 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.
  • 24.
  • 25.
    An Analogy – Youmight 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 ClassObjects Car Toyota BMW Mercedes
  • 29.
    Data Hiding – Akey 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.
  • 30.
  • 31.
    Example #include <iostream> using namespacestd; 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 requiredthat 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> usingnamespace 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() { Counterc1; //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 destructoris 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> usingnamespace 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> usingnamespace 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 namespacestd; 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 lecture1 ThankYou!