Chapter - 5 - Introduction To Object Oriented Programming

You might also like

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 38

Chapter Five

Introduction to Object
Oriented Programming

1
Objectives
At the end of this chapter we aim students
● Understand Definition of Basic OO programming
Concepts (Abstraction, encapsulation, inheritance and
Polymorphism)
● Understand the concepts of classes and objects
● Define Classes
● Instantiate classes and Object variables
● Understand Constructor Methods
● Define Derived Classes (Inheritance)
● Understand Method Overloading and
Overriding(redefining)

Chapter 5:Introduction to Object oriented proramming 2


Object Oriented Programming Concepts
Basic concepts of Object Orientation
• Object-oriented programming (OOP) is a programming
structure that enables developers to create and manipulate
objects within a program.
• OOP is based on the idea of creating objects that contain
both data and functions that can manipulate that data. This
makes software development more efficient and helps to
avoid code duplication.
• It is commonly used for developing applications and systems
that are both maintainable and extensible, making it a popular
choice for large-scale software development.
• The four pillars of OOPs are abstraction, encapsulation,
inheritance, and polymorphism.
• By using these four pillars of OOPs, developers can create
programs that are powerful, maintainable, and extensible,
making them a great choice for software development
Chapter 5:Introduction to Object oriented proramming 4
Abstraction
• Abstraction means displaying only essential information and hiding the
details.
• Data abstraction refers to providing only essential information about the
data to the outside world, hiding the background implementation details

• An abstraction is a form of simplification and organization, allowing


developers to focus on the essential parts of their code without focusing
on the implementation details.
• Abstraction provides the ability to hide details, allowing for simpler
representations of objects.
• It helps developers create code in a more efficient manner, while still
providing the same functionality.

Chapter 5:Introduction to Object oriented proramming 5


Encapsulation
• Encapsulation is the process of aggregating data and
codes into a single unit, known as object.
• Encapsulation allows developers to create a secure
environment where data can be accessed and modified
only with the object’s methods.
• Encapsulation also leads to data abstraction or data hiding
• Encapsulation allows for data and functions to be stored in
one place, increasing security and allowing for easy
access.
• It helps keep code organized, as well as helps prevent
accidental data manipulation and changes.

Chapter 5:Introduction to Object oriented proramming 6


Inheritance
• Inheritance is the capability of a class to derive
properties and characteristics from another class; it is
the process of creating new classes based on an
existing class
• Inheritance is one of the most important features of
Object-Oriented Programming.
• Inheritance is the ability to define properties and
methods from a parent class to a child class
• It allows the developer to create subclasses that will
inherit the attributes and behaviors of the parent class.
• This makes it easy to reuse code, making development
faster and more efficient

Chapter 5:Introduction to Object oriented proramming 7


Inheritance cont’d
• Sub Class: The class that inherits properties from
another class is called Sub class or Derived Class
or Child Class.
• Super Class: The class whose properties are
inherited by a sub-class is called Base Class or
Superclass or Parent Class or ancestor class.
• Reusability: Inheritance supports the concept of
“reusability”, i.e. when we want to create a new
class and there is already a class that includes
some of the code that we want, we can derive our
new class from the existing class.
• By doing this, we are reusing the fields and methods
of the existing class.
Chapter 5:Introduction to Object oriented proramming 8
Polymorphism
• polymorphism is the process of creating multiple classes
with the same interface.
• Polymorphism allows for objects to take on different forms,
which is particularly useful when dealing with data of
varying types.
• The behavior depends upon the types of data used in the
operation. C++ supports operator overloading and function
overloading.
• Operator Overloading: The process of making an operator
exhibit different behaviors in different
• Function Overloading: Function overloading is using a single
function name to perform different types of tasks.
• Polymorphism is extensively used in implementing
inheritance.

Chapter 5:Introduction to Object oriented proramming 9


Polymorphism

Chapter 5:Introduction to Object oriented proramming 10


Class and Objects

In object-oriented programming, a class is a construct that is
used as a blueprint to create instances of the class (class
instances, class objects, instance objects or just objects).

It is the building block of C++ making it OOP language

It is a user-defined data type, which holds its own data
members and member functions, which can be accessed and
used by creating an instance of that class.

A class defines constituent members which enable class
instances (ie objects) to have state and behavior.

Data member enable a class object to maintain state while
Member functions or methods, enable an object's behavior.

A class usually represents a person, place or (possibly quite
abstract entity like an account), thus noun is used

Chapter 5:Introduction to Object oriented programming


11
Classes and objects cont’d
• A Class is like a blueprint and objects are like
houses built from the blueprint

Chapter 5:Introduction to Object oriented proramming 12


Class cont’d

Structure is the forerunner to class

A structure provides a framework for declaration of user defined data
type

Can be defined with various data types

A function can also e defined in a structure,


Example:
#include<iostream>
usign namespace std;
struct Account {
void main(){
int num;
Account saving;
double balance;
saving.num=100;
void display(){
saving.balance = 23456.00
cout<<“Account N0.: “<<num;
saving.display(); }
cout<<“\nBalance: “ <<balance; }
};

Chapter 5:Introduction to Object oriented proramming 13


Class cont’d

Class in C++ is similarly framework for user defined data types

Class and structure provide a programmer the privilege to build their own data types

These data types are convenient to represent real entities like account, student,
course, that are not available in built in ones

A structure is seldom built with functions; a class will have both data members and
member functions

Similar to the struct keyword in structure definition, the keyword class is used in
class definition

A simple class can be as simple as class with no function definitions

#include<iostream>
usign namespace std;
struct Account {
int num; void main(){
double balance; Account saving;
void display(){ saving.num=100;
cout<<“Account N0.: “<<num; saving.balance = 23456.00
cout<<“\nBalance: “ <<balance; } saving.display(); }
}; Chapter 5:Introduction to Object oriented proramming 14
Member functions and data members

Functions declared in a class are called member functions

The member functions provide the interface to access the
variables in the class

The variables are called data members
class Account {
int num;
double balance;
void didsplay(){
cout<<balance;
}
};

Chapter 5:Introduction to Object oriented proramming 15


Object

Object is an instance of a class or a replica of a class

Analogous to structure variable, an object is a variable
of type class

A class provides a blueprint for the object

An Object is an identifiable entity with some
characteristics and behavior.

When a class is defined, no memory is allocated but
when it is instantiated (i.e. an object is created)
memory is allocated.

Chapter 5:Introduction to Object oriented proramming 16


Object

Here, Account is a class;

every person’s account is an object this means every account holder has a
number and balance; but all accounts use the same template; a class gives
rise to many objects

While class holds generic data structure, objects hold specific and unique
data

Class
class Account {
int num; Objects
Account
double balance;
void didsplay(){ Data members
cout<<balance; }
Num cust1 cust2
Balance
};
Member function 001 002
int main(){ Display
Account cust1, cust2; 10000.15 10000.15
…. }
Chapter 5:Introduction to Object oriented proramming 17
Access Control

The access to the data members and member functions of a class or structure
can be controlled by using the access control key words or access specifiers:

Private

Public

The data members or member functions declared private can only be accessed
from within the class

the default access for structure is public and private for class

Objects outside the class can access its private data members only through the
member functions of the class that are declared public

The member functions cannot be accessed from outside if they are declared
private

Member functions have to be declared public for meaningful programs

The data members should not be declared public as it defeats the very
purpose of data hiding, which is one of the most important requirements
of object oriented programming

the member functions are usually declared public

Declaring both data members and member functions private will totally
shield the class from outside world and therefore serves no purpose out there

Chapter 5:Introduction to Object oriented proramming 18


Access Control Example
#include<iostream>
using namespace std;
class Account { int main(){
Public: Account cust1;
int num; //assignment outside
double balance; the //class since data
members //are public
Public:
void didsplay(){
cust1.num = 001;
cout<<“Account No: ”<<num; cust1.balance = 10000.00;
cout<<“Balance: “<<balance; } cust1.display();
}; return 0;
//if the data members are }
//public, we can use struct
Chapter 5:Introduction to Object oriented proramming 19

Access Control
in the example shown previously, as the data members are declared public, we could use them
outside the class, to give values to the variables of the object, we assigned
cust1.num = 001;
cust1.balance = 10000.00;

When the data members are declared private, we can assign values using a member function in
the#...
class and this is the only way to assign values to the object variables
class Account {
Privaate :
int num;
double balance; int main(){
Public:
Account cust1;
void indata(int x, double y)
{ //assignment outside the //class
num=x; via //member function as the
balance = y; }
member //variables are private
Public: cust1.indata(001, 10000.00);
void didsplay(){ cust1.display();
cout<<“Account No: return 0;
”<<num;
cout<<“Balance:
} to Object oriented proramming
Chapter 5:Introduction 20
Data Encapsulation and Abstraction

Data encapsulation, sometimes referred to as data hiding.

The wrapping up of data and code into a single unit is called data
encapsulation.

The data is not accessible to the outside world only those functions which
are wrapped into a class can only access the private data of the class.

Data Encapsulation and Data Abstraction is one of the most striking
feature of object oriented programming.

The concept of data encapsulation is supported in C++ through the use of
the public, protected and private keywords which are placed in the
declaration of the class.

Note :

Anything in the class placed after the public keyword is accessible to all the
users of the class

Elements placed after the protected keyword are accessible only to the
methods of the class or classes derived from that class

Elements placed after the private keyword are accessible only to the
methods of the class.
Chapter 5:Introduction to Object oriented proramming 23
Inheritance

Inheritance is one of the most spectacular feature of object
oriented programming.

Inheritance is the process by which one class can acquire the
properties of another class.

The new classes, known as subclasses (or derived classes),
inherit attributes and behavior of the pre-existing classes,
which are referred to as superclasses (or ancestor classes). The
inheritance relationships of classes gives rise to a hierarchy

A superclass, base class, or parent class is a class from which
other classes are derived. The classes that are derived from a
superclass are known as child classes, derived classes, or
subclasses.

In object-oriented programming (OOP), inheritance is a way
to compartmentalize and reuse code by creating collections of
attributes and behaviors called objects which can be based on
previously created Chapter
objects.5:Introduction to Object oriented proramming 25
Defining member function
A member function is defined the same way as any other function except
that the ClassName and the scope resolution operator :: are given in the
function heading.
SYNTAX
ReturnedType ClassName::FunctionName(ParameterList)
{
FunctionBodyStatements
}
//Uses iostream:
void Year::output()
{
cout << "month = " << month
<< ", day = " << day << endl;
}

Chapter 5:Introduction to Object oriented proramming 26


Dot operator and scope resolution operator
Both the dot operator and the scope resolution operator are used with
member names to specify what thing they are members of.
For example, suppose you have declared a class called Year and you declare an object
called today as follows:
Year today;
You use the dot operator to specify a member of the object today. If output() is a member
function for the class Year and the following function call will output the data values
stored in the object today:
today.output();
You use the scope resolution operator :: to specify the class name when
giving the function definition for a member function. For example, the
heading of the function definition for the member function output
would be as follows:
void Year::output()
Remember, the scope resolution operator :: is used with a class name,
whereas the dot operator is used with an object of that class.

Chapter 5:Introduction to Object oriented proramming 27


Exercise
Given the following class definition, write an appropriate
definition for
the member function set:
class Temperature {
public:
void set(double newDegrees, char newScale);
//Sets the member variables to the values given as
arguments.
double degrees;
char scale; //'F' for Fahrenheit or 'C' for Celsius.
};
Chapter 5:Introduction to Object oriented proramming 28
Exercise
//Program to demonstrate the class Year.
#include <iostream> //This is an improved version
using namespace std;
class Year {
public:
void input( );
void output( );
//Precondition: newMonth and newDay form a possible date
//Postcondition: The date is reset according to the arguments.
void set(int newMonth, int newDay);
int getMonth( );//Returns the month, 1 for January, 2 for
February, etc
int getDay( ); //Returns the day of the month.
private:
//Private members are used in member function definitions
only
void checkDate( );
int month;
int day; Chapter 5:Introduction to Object oriented proramming
29
};
Exercise
int main( ){
Year today, yourBirthday;
cout << "Enter today's date :\n";
today.input( ); //input is defined next slide
cout << "Today's date is ";
today.output( );
yourBirthday.set(3, 21);//set is defined next slide
cout << "Your birthday is ";
youBirthday.output( );
if (today.getMonth( ) == yourBirthday.getMonth( ) &&
today.getDay( ) == yoourBirthday.getDay( ) )
cout << "Happy Birthday!\n";
else
cout << "Happy Unbirthday!\n";
return 0;
} Chapter 5:Introduction to Object oriented proramming 30
Exercise
void Year::input( ){
cout << "Enter the month as a number: "; cin >> month;
cout << "Enter the day of the month: "; cin >> day;
CheckDate( ); }//to check valid date
void Year::output( ){
cout<<”month = “<<month;
cout<<”day = “<<day;}
void Year::set(int newMonth, int newDay){
month = newMonth;
day = newDay;
checkDate();}
void Year::checkDate( ){
if ((month < 1) || (month > 12) || (day < 1) || (day > 31)){
cout << "Illegal date. Aborting program.\n"; exit(1);}
int Year::getMonth( ){//accessor function
return month;}
int Year::getDay( ){//accessor function
return day; }
Chapter 5:Introduction to Object oriented proramming 31
Accessor and mutator function
•Member functions that allow you to find out the values of the
private member variables of a class are called accessor
functions.
•The accessor functions need not literally return the values of
each member variable, but they must return something
equivalent to those values.
•Member functions that allow you to change the values of the
private member variables of a class are called mutator
functions.
•Although this is not required by the C++ language, the names
of accesor functions normally include the word get while those
of mutator functions include the word set.
•It is important to always include accessor and mutator functions
with each class definition so that you can change the data
stored in an object.
Chapter 5:Introduction to Object oriented proramming 33
Constructor
• You often want to initialize some or all the member variables for an object
when you declare the object.
• Initializing member variables is the most common sort of initialization.
C++ includes special provisions for such initializations. When you define a
class, you can define a special kind of member function known as a
constructor.
• A constructor is a member function that is automatically called when an
object of that class is declared. A constructor is used to initialize the
values of member variables
• You can define a constructor the same way that you define any other
member function, except for two points:
1. A constructor must have the same name as the class. For example, if the
class is named BankAccount, then any constructor for this class must be
named BankAccount.
2. A constructor definition cannot return a value. Moreover, no return type,
not even void, can be given at the start of the function declaration or in
the function header.

Chapter 5:Introduction to Object oriented proramming 34


Example
class SampleClass {
public:
SampleClass(int parameter1, double parameter2);//constructor that
//requires two arguments
void do_stuff();
private:
int data1;
double data2;
};
• You should recognize the following as a legal way to declare an object of type
SampleClass and call the constructor for that class:
SampleClass myObject(7, 7.77);
• However, you may be surprised to learn that the following is illegal:
SampleClass yourObject;
• The compiler interprets this declaration as including a call to a constructor
with no arguments, but there is no definition for a constructor with zero
arguments.
• You must either add two arguments to the declaration of yourObject
or add a constructor definition for a constructor with no arguments.
Chapter 5:Introduction to Object oriented proramming 35
Example
• A constructor that can be called with no arguments is called a default
constructor, since it applies in the default case where you declare an
object without specifying any arguments.
• Since it is likely that you will sometimes want to declare an object without
giving any constructor arguments, you should always include a default
constructor. The following redefined version of SampleClass that includes
a default constructor:
class SampleClass {
public:
SampleClass(int parameter1, double parameter2);
SampleClass();//default constructor
void doStuff();
private:
int data1;
double data2;
};
Chapter 5:Introduction to Object oriented proramming 36
Example
• If you redefine the class SampleClass in this manner,
then the previous declaration of yourObject would be
legal.
• If you do not want the default constructor to initialize
any member variables,
• you can simply give it an empty body when you
implement it. The following constructor definition is
perfectly legal. It does nothing when called except
make the compiler happy:
SampleClass::SampleClass()
{
//Do nothing.
}
Chapter 5:Introduction to Object oriented proramming 37
Example
class Coordinate {
public:
Coordinate();
Coordinate(int x);
Coordinate(int x, int y);
int getX();
int getY();
private:
int x=1;
int y=2;
};
Coordinate::Coordinate()
{}
Coordinate::Coordinate(int xVal) : x(xVal)
{}
Coordinate::Coordinate(int xVal, int yVal) : x(xVal), y(yVal)
{}
int Coordinate::getX() {
return x; }
int Coordinate::getY() {
return y; }
Chapter 5:Introduction to Object oriented proramming 38
Example
• If we create a Coordinate object, then member
variable x will be set to 1 and member variable y will
be set to 2 by default.
• These values can be overridden if we invoke a
constructor that explicitly sets the variable.
• In the snippet below, the default values for x and y
are set for c1, but for c2 the default valueis only set
for y because x is explicitly set to the input argument:
Coordinate c1, c2(10);
cout << c1.getX() << ‘\t’<< c1.getY() << endl; //
//Output: 1 2
cout << c2.getX() << ‘\t’ << c2.getY() << endl; //
//Output: 10 2
Chapter 5:Introduction to Object oriented proramming 39
Example
•Suppose your program contains the following class definition (along with
•definitions of the member functions):
class YourClass {
public:
YourClass(int newInfo, char moreNewInfo);
YourClass();
void doStuff();
private:
int information;
char moreInformation;
};
•Which of the following are legal?
•YourClass anObject(42, 'A');
•YourClass anotherObject;
•YourClass yetAnotherObject();
•anObject = YourClass(99, 'B');
•anObject = YourClass();
•anObject = YourClass;
Chapter 5:Introduction to Object oriented proramming 40
Exercise
•Wite a complete program that implements the four
pillars of object orientation on a case of
•Students of a school or a university
•Employees of a company
•Domestic animals
•Wild animals
•In each case
•decide on the level of abstraction in terms of their attributes and
methods the objects encapsulate

•Show the reusability of features of base classes by the respective


derived classes as an implementation of inheritance

•Show the implementation of polymorphism in threenpossibilities which


are function overloading, function overriding and function redefining

Chapter 5:Introduction to Object oriented proramming 41


End of chapter 5

You might also like