Chapter 13-OOP (Additional) V2
Chapter 13-OOP (Additional) V2
Inheritance
Overloading Vs. Overriding methods
Encapsulation
Access modifier/accessibility types: public, protected, private
Polymorphism
Abstraction, interface
2
• Data (variable)
Introduction • Behavior (function)
OOP is the principle for programming approach based on the concept of classes and objects.
OOP allows us to organize software as a collection of objects that consist of both data and behavior.
The core of OOP is to create an object that has certain properties (variable) and methods (function)
Properties: characteristics of an object
Methods: actions that can be performed by an object
Example:
A car is an object which has certain properties
such as color, year, price, model, etc.
It also has certain methods such as
start, drive, park, brake and so on. 3
Introduction
What is OOP?
4
Introduction
Why OOP?
5
References
Sources
Book
Learning Object-Oriented Programming: Explore and crack the OOP code in Python,
JavaScript, and C# (OOP books using Python, C#, JavaScript)
http://library1.org/_ads/F485A9E07966E40D96382FF767A0271D
Online document:
https://www.tutorialspoint.com/cplusplus/cpp_classes_objects.htm
https://www.programiz.com/cpp-programming
6
Class and Object
7
Introduction
Class and Object?
A class a template/blueprint for defining something.
An object is a specific item that belongs to a class.
An object is called an instance of a class.
A class defines characteristics of its objects and methods that can be applied to
its objects.
A class provides a way to group data and the functions that use the data.
Remark: Classes are similar to structures in that both provide a means to group data and behaviors
together so you can create objects. However, classes provides much more features than structures. 8
Introduction
Structure Vs. Class
C++ supports two ways to create your own complex data types:
structure
class
9
Introduction
Example: Structure
10
Introduction
Example: Class
When you create an object from the class, you automatically create all the related fields.
You gain the ability to pass an object into a function as a parameter, or receive an object from a
function as a returned value. Most importantly it can automatically pass or receive all the
individual fields that each object contains.
You think about class and object then and manipulate them similarly to the way you use real-
life classes and objects.
12
Introduction
Accessibility types (access modifier)
• The accessibility is used to define whether or not a variable/function can be accessed by the
others. The accessibility types are
• public : everyone can access
• protected : can be accessed within its class or child class. Protect from everyone except its child class (use in
inheritance)
13
Introduction
REMARKS
14
OOP
Examples Parameter name is optional in prototype
#include<iostream> #include<iostream>
class Student{
using namespace std; using namespace std;
public:
class Student{ class Student{
int idNum;
int idNum; private: int idNum;
string lastName;
string lastName; public: string lastName;
private: double gpa;
double gpa; private: double gpa;
public:
void displayStudentData();
void displayStudentData(); void displayStudentData();
void setIdNum(int);
void setIdNum(int); void setIdNum(int);
void setLastName(string);
void setLastName(string); void setLastName(string);
void setGPA(double);
void setGPA(double); void setGPA(double);
double getGPA();
double getGPA(); double getGPA();
};
}; };
main(){
#include<iostream> Student s1, s2, s3;
Example 4: using namespace std; s1.setData("Dara", 1, 3.5);
s2.setData("Sok", 2, 3);
Create a class and define class Student{ 1 s3.setData("Sao", 3, 3);
the implementation of the int idNum; s1.displayStudentData();
string lastName; s2.displayStudentData();
methods private: double gpa; s3.displayStudentData();
2 cout<<s1.getGPA()<<endl;
public: cout<<s2.getGPA()<<endl;
void displayStudentData(); cout<<s3.getGPA()<<endl;
void setData(string name, int id, double GPA); cout<<s3.lastName<<endl;
double getGPA(); cout<<s3.idNum<<endl;
1. Define characteristics }; //cout<<s3.gpa;
void Student::setData(string name, int id, double GPA){
2. Define methods lastName = name; }
3. Implementation of the idNum = id;
gpa = GPA; 3
defined methods }
void Student::displayStudentData(){
cout<<lastName<<" "<<idNum<<" "<<gpa;
cout<<"\n";
}
double Student::getGPA(){
return gpa;
} 16
Q&A
17
Practice
Exercise on Class and Object
1) Write a C++ program to create a class for a customer. The class Customer has some
characteristics/properties such as customer id, name, sex, phone. Make the customer id as a private
and the others (name, sex, phone) as public. In addition, the class Customer has 2 public methods such
as setCustomerData(int id, string name, char sex, string phone) [for initializing the data], and
displayACustomerInfo() [for displaying customer’s information]. Then,
18
Inheritance
19
Outline
Introdution to inheritance
Advantages of inheritance
Using inheritance
20
Introduction
Inheritance
Inheritance means you create a class that get their characteristics (data) and
methods (functions) from existing a class
Student
Class name
FirstYearStudent string name
string id char sex Characteristics/properties/fields/
inherit string address attributes
void doOrientation()
void register()
Methods/functions/operations
void payFee()
Create a new class which
inherits from existing class
Existing class
21
Introduction
Inheritance
Suppose you have written several programs with a class
Student
named Student
string name
You already defined the characteristics and methods char sex
If you need to write a program using a new class named string address
FirstYearStudent void register()
void payFee()
You just need to inherit from the class Student
The class FirstYearStudent may require some additional
data members and functions inherit
Save time
Because you don’t have to start from scratch when you want to
create a class that has similar characteristics and methods to
your existing class
What you need to do is just to expand on an existing class
In a child class, you can extend and revise a parent class
without corrupting the existing parent class’s features
You don’t have to modify a parent class to get it to work
correctly with your requirement
When you create a child class, much of the code has been
tested and it makes this new child class more reliable
23
Introduction
Example
25
Creating a child class with different types of accessibility
Using public
Using protected
Using private
26
Introduction
Example
27
Examples
Examples
#include<iostream>
using namespace std;
class Person{ 1
private:
int idNum;
string lastName; class Customer : public Person{
string firstName; //other statements go here
public: };
void setFields(int, string,
string); int main(){
void outputData(); Customer c1;
}; c1.setFields(1, "Sok", "Dara");
void Person::setFields(int num, string c1.outputData();
last, string first){ } 2
idNum = num;
lastName = last;
firstName = first; Example 2: Create an inheritance class
}
void Person::outputData(){
1. Create a new class with inheritance
cout<<"ID #"<<idNum<<"\nName:
"<<firstName<<" "<<lastName<<endl; to the existing class
} 2. Using the child class
Example 1: Create a class 28
Examples
#include<iostream> int main(){
Customer c1;
Examples
using namespace std; class Customer : public Person{
//other statements go here c1.setFields(1, "Sok",
class Person{ private: "Dara");
private: double balanceDue; c1.outputData();
int idNum; public: c1.setBalDue(147.99);
string lastName; void setBalDue(double); c1.outputBalDue();
string firstName; void outputBalDue(); }
public: }; 2 Example 3: Main program
void setFields(int, string,
string); void Customer::setBalDue(double bal){
void outputData(); balanceDue = bal;
}; }
void Person::setFields(int num, string void Customer::outputBalDue(){
last, string first){ cout<<"Balance due $
idNum = num; "<<balanceDue<<endl;
lastName = last; }
firstName = first;
}
void Person::outputData(){ Example 2: Create an inheritance class then More characteristics and 2
cout<<"ID #"<<idNum<<"\nName: add some more characteristics and methods
methods are added to the
"<<firstName<<" "<<lastName<<endl;
child class
} Example 1: Create a class 29
Q&A
30
Practice exercise on Class and Object
1) Write a C++ program to create a class for a customer. The class Customer has some
characteristics/properties such as customer id, name, sex, phone. Make the customer id as a private
and the others (name, sex, phone) as public. In addition, the class Customer has 2 public methods such
as setCustomerData(int id, string name, char sex, string phone) [for initializing the data], and
displayACustomerInfo() [for displaying customer’s information]. Then,
Write code (implementation) for the method setCustomerData
Write code (implementation) for the method displayACustomerInfo
Create 5 objects from the class Customer.
Set data for each object by using the method setCustomerData with the information from any five students of
your classmates.
Display the 1st, 3rd and 5th object by using the method displayACustomerInfo
31
Practice exercise
Practice
1) Write a C++ program to create a class Computer. This class has three protected characteristics such as id, size of hdd, and size
of ram. In addition, this class has two public methods, i.e i) setSpec which assign data to it, and ii) displaySpec which display
characteristics’ information of this computer.
2) Next, create two subclasses (Laptop and Desktop). Each subclass has some additional private characteristics such as price,
model, and year. These two subclasses also have two more public methods setData and showDetail, for assigning all required data
and shows all detail information.
32
Class
Examples
main(){
#include<iostream> Student s1, s2, s3;
Example 4: using namespace std; s1.setData("Dara", 1, 3.5);
s2.setData("Sok", 2, 3);
Create a class and define class Student{ 1 s3.setData("Sao", 3, 3);
the implementation of the int idNum; s1.displayStudentData();
string lastName; s2.displayStudentData();
methods private: double gpa; s3.displayStudentData();
2 cout<<s1.getGPA()<<endl;
public: cout<<s2.getGPA()<<endl;
void displayStudentData(); cout<<s3.getGPA()<<endl;
void setData(string name, int id, double GPA); cout<<s3.lastName<<endl;
double getGPA(); cout<<s3.idNum<<endl;
1. Define characteristics }; //cout<<s3.gpa;
void Student::setData(string name, int id, double GPA){
2. Define methods lastName = name; }
3. Implementation of the idNum = id;
gpa = GPA; 3
defined methods }
void Student::displayStudentData(){
cout<<lastName<<" "<<idNum<<" "<<gpa;
cout<<"\n";
}
double Student::getGPA(){
return gpa;
} 33
Encapsulation
34
Outline
Advantages of encapsulation
Using encapsulation
35
Introduction
Encapsulation
Encapsulation is the process of combining variables and
functions into a class then you make some variables as private.
In simple word, encapsulation is a principle that you store
variables (characteristics/data) in a class as private
That means, only the codes inside its class can use it (data hiding)
36
Introduction
Why Encapsulation?
Secure and consistent results
That means, giving the user access to a limited data and keeps our
valuable data
37
Introduction
Main advantages of Encapsulation
Enhanced security
38
Introduction
Implementation
To implement an encapsulation
We declare the variables (characteristics) that should be restrict access as a private
Example
Person
39
Examples
#include<iostream>
using namespace std;
class Person{
Examples
public:
int idNum; class Customer: public Person{
string lastName; //other statements go here
string firstName; };
private: string password; 1
public: int main(){
string getPassword(int); Customer c1;
void setFields(int, string, c1.setFields(1, "Sok", "Dara");
string); cout<<c1.lastName<<endl;
}; cout<<c1.idNum<<endl;
void Person::setFields(int num, string 2
cout<<c1.password<<endl;//error
last, string first){ cout<<c1.getPassword(c1.idNum)<<endl;
idNum = num; }
Encapsulation
lastName = last;
firstName = first;
Example 2: Create an inheritance class
}
string Person::getPassword(int id){
if(id==idNum){ 1. Create a new class with inheritance to the existing class
return password; 2. Using the child class with encapsulation
}
Example 1: Create a class 40
}
Q&A
41
Practice exercise
Practice
1) Create a class that has two properties as private and one public method.
Create an object in main. Then try to access an property of its object.
42
Overloading Vs.
Overridding function
43
Introduction
Overloading functions
The processing of providing more than one functions with the same name is called method
overloading (overloading function).
We can say: These functions have been overloaded
Overloading helps us to provide a consistent and clear interface to our methods regardless of
the parameter types.
Ex: We don’t need to create two functions with different names addTwoInt and addTwoFloat. We can just
create two functions having the same names but different returning type and/or parameter types.
int addTwo(int, int)
double addTwo(double, double)
44
Introduction
Overloading functions
Overloading occurs when the same function name is used with different signatures
Signature refers ordered list of its parameter types
Examples:
void add(int, double) and void add(int, int) : they are overloading functions because they have
the same names but their second parameter types are different
void add(int, int, int) and void add(int, int) : they are overloading functions because they have
the same names but the number of parameters are not the same
int add(int, int) and double add(int, int) : they are overloading functions because they have
the same names but they have different returning types
45
Overloading function
Code example
#include<iostream>
using namespace std;
Example:
Parent class has this function void add(int, int)
Child class also has its own function called void add(int, int)
That means the function in child class overrides the function in its parent class
47
Overriding function main(){
A obj1;
#include<iostream>
B obj2;
Code example
using namespace std;
int a=1, b=1;
class A{
public: int r;
int addTwoNumbers(int n1, int n2);
void display(); r = obj1.addTwoNumbers(a, b);
}; cout<<"Sum of a and b is: "<<r<<endl;
int A::addTwoNumbers(int n1, int n2){ obj1.display();
int result; cout<<"---------"<<endl;
result = n1+n2;
r = obj2.addTwoNumbers(a, b);
return result;
} cout<<"Sum of a and b is: "<<r<<endl;
void A::display(){ obj2.display();
cout<<"Good bye! (called from class A)"<<endl; }
}
class B: public A{
public:
void display();
};
void B::display(){
cout<<"Good bye! (called from class B)"<<endl;
}
Output 48
Example 2: Overriding function
Overloading Vs. Overriding functions
Comparison
Overloading deals with multiple functions in the same class with the same
name but different signatures
Overriding deals with two functions, one in a parent class and one in a child
class that have the same signature
49
Q&A
50
Continue …
Constructor
Polymorphism
Data Abstraction
Interface
51
Constructor
A constructor in C++ is a special method/function that is automatically called when an object of a class is created.
A constructor is basically used to initialize variables when create object.
To create a constructor, use the same name as the class, followed by parentheses ( )
Data abstraction is a programming (and design) technique that relies on the separation of interface and implementation.
Consider a class below. It add numbers together and returns the sum.
• The public members addNum and getTotal are the interfaces to the outside
world and a user needs to know them to use the class.
• The private member total is something that the user doesn't need to know
about, but is needed for the class to operate properly.
54
Interface
An interface describes the behavior or capabilities of a C++ class without committing to a particular implementation of that class.
The C++ interfaces are implemented using abstract classes
Note: Don’t confuse abstract class with data abstraction. Data abstraction is a concept of keeping implementation details
separate from associated data.
A class is made abstract by declaring at least one of its functions as pure virtual function.
A pure virtual function is specified by placing "= 0" in its declaration
A child class that inherits this abstract class will also be called an
abstract class if this class does not override the pure virtual functions.
55
More about virtual function: https://www.geeksforgeeks.org/virtual-function-cpp/
Q&A
56