0% found this document useful (0 votes)
34 views

Chapter 13-OOP (Additional) V2

The document discusses object-oriented programming concepts including classes, objects, inheritance, encapsulation, polymorphism, and abstraction. It provides examples of how to define a class with properties and methods, create objects from a class, and specify different access modifiers like public, private, and protected. The document also demonstrates how to define classes and methods to organize data and behavior for objects.

Uploaded by

Hai Kim Sreng
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views

Chapter 13-OOP (Additional) V2

The document discusses object-oriented programming concepts including classes, objects, inheritance, encapsulation, polymorphism, and abstraction. It provides examples of how to define a class with properties and methods, create objects from a class, and specify different access modifiers like public, private, and protected. The document also demonstrates how to define classes and methods to organize data and behavior for objects.

Uploaded by

Hai Kim Sreng
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 56

Algorithm and Programming

Chapter 13: OOP

Prepared by: Mr. BOU Channa


1
Object-Oriented Programming (OOP)
 A Brief of Outline
 Introduction

 Class and Object

 Inheritance
 Overloading Vs. Overriding methods

 Encapsulation
 Access modifier/accessibility types: public, protected, private

 Polymorphism

 Abstraction, interface

2
• Data (variable)
Introduction • Behavior (function)

 What is OOP? OOP: Object-Oriented Programming

 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?

 The main principles of OOP are


 Class, object, overloading and overriding
 Inheritance,
 Encapsulation,
 Abstraction,
 Polymorphism

4
Introduction
 Why OOP?

 OOP has the following main advantages


 OOP makes it easy to maintain and modify existing code (code reusability)
 It provides a clear structure for programs
 It helps to manage the complexity of large software systems
 Objects can also be reused within or across applications
 The reuse of software also lowers the cost of development

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

 “Object-Oriented Programming Using C++”, Joyce Farrell, (4th edition)


 http://library1.org/_ads/E599B867E1FE1C14C5E4ABA7E3F6942D

 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.

 The concept of using classes provides a useful way to organize objects


 It is especially useful because classes are reusable.

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

Remark: You cannot assign a value to a field in a class definition.


E.g:, in the Student class, you cannot write idNum = 123;.
A class definition is only a description of a type; you cannot assign
values to fields until you create an object. 11
Introduction
 Advantages of Using Class and Object

 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

• private : can only be accessed within its class

• protected : can be accessed within its class or child class. Protect from everyone except its child class (use in
inheritance)

Remark: For most C++ classes, data is private or protected, and


most functions are public

13
Introduction
 REMARKS

 By default, the data of the class are private.

 By default, the methods of the class are public.

 To make a data to be public, use public:


 string lastName;

 public: string lastName;

 Similarly, for the private and protected, use private: or protected:

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();
};
}; };

Example 2: Create a class and Example 3: Create a class and


Example 1: Create a class specify accessibility specify accessibility
(alternative way) (alternative way)
15
OOP
 Examples Parameter name is optional.

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,

 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

18
Inheritance

19
Outline

 Introdution to inheritance

 Advantages of inheritance

 Using inheritance

 Create and use a derived/child/subclass class

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

 Remark: Observe the example of inheritance on the right FirstYearStudent


 The class Student is called a parent class, base class, superclass or ancestor.
 The class FirstYearStudent is called a child class, derived class, subclass or descendant.
string id
void doOrientation()
22
Advantages of using Inheritance
 Inheritance

 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

The class Customer is inherited


from the existing class Person
(Inheritance)

Using different accessibility types 24


Accessibility Type (access modifier)

 private data and functions


 can be accessed only within a class

 protected data and functions


 can be accessed within its class or child class

 public data and functions


 can be accessed anywhere

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.

3) Create a main program to run and test your code by


 Create two objects obj1 from Laptop class and obj2 from Desktop class
 Set data (id: 1, size of hdd: 1T, size of ram: 8GB) to obj1 using setData method
 Set data (id: 2, size of hdd: 2T, size of ram: 16GB) to obj2 using setData method
 Display all detail info of obj1 and obj2 via their showDetail methods
 Display specification of the computer obj1 using displaySpec method

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

 Learn about encapsulation

 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)

 In other word, it is a mechanism for restricting access to some


of the object’s data (characteristics)
 Data is only accessible through the functions present inside the class

 Encapsulation helps to make the module independent of all


other modules and therefore reusable.

36
Introduction
 Why Encapsulation?
 Secure and consistent results
 That means, giving the user access to a limited data and keeps our
valuable data

 Example: Suppose that we made a Rectangle class that contained four


variables (characteristics) such as length, width, area and perimeter.
 Note that area and perimeter are obtained from length and width,
so changing length would change area and perimeter.
 If not use info hiding (encapsulation), then another program
using that Rectangle class could change the length without
changing the area, and you would have an inconsistent Rectangle

37
Introduction
 Main advantages of Encapsulation

 Makes maintenance of application easier

 Improve the understandability of the application

 Enhanced security

38
Introduction
 Implementation

 To implement an encapsulation
 We declare the variables (characteristics) that should be restrict access as a private

 Then, we create a public function to return those variables

 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;

int addTwoNumbers(int n1, int n2){


int result;
result = n1+n2;
return result;
}
double addTwoNumbers(double n1, double n2){
double result;
result = n1+n2;
return result;
}
main(){
cout<<addTwoNumbers(1, 1)<<endl;
cout<<addTwoNumbers(1.3, 2.6)<<endl;
}

Example 1: Overloading function 46


Introduction
 Overriding functions
 Overriding functions occurs in inheritance when the child class has exactly the
same function as function in the parent class
 Same function here means they have the same returning type, the same name, the same
number of parameters and the same parameter types

 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 ( )

Remark: We can more than one


constructor in a class. Just make each
constructor has different parameter. 52
Polymorphism
 Polymorphism means "many forms” and it happens in inheritance.
 It occurs when we have many classes that are related to each other by inheritance.
 Inheritance lets us inherit attributes and methods from another class.
 Polymorphism uses those methods to perform different tasks. This allows us to perform a single action in different ways.

Remark: Polymorphism happens in inheritance


in the forms of overriding methods.
53
Data Abstraction
 Data abstraction refers to providing only essential information to the outside world and hiding their background details,
 i.e., to represent the needed information in program without presenting the details.

 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

 The purpose of an abstract class is to provide an appropriate base


class from which other classes can inherit.

 Abstract classes cannot be used to instantiate objects. It serves only as


an interface.

 We can not create an object of an abstract class. It causes a


compilation error.

 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

You might also like