Features/Principles of OOP
Course: MPHYCC-05 Modeling and Simulation
(M.Sc. Sem-II)
Unit-1 of CC-05
Features/Principles of OOP
Objects and Classes
In the last class we discuss the objects and classes using the following
example.
#include <iostream>
using namespace std;
class smallobj{
public:
int somedata;
public:
void setdata(int d)
{ somedata = d; }
void showdata()
{ cout << “Data is “ << somedata << endl; }
};
int main()
{smallobj s1, s2;
s1.setdata(1066);
s2.setdata(1776);
s1.showdata();
s2.showdata();
return 0;}
Here smallobj is a class while s1 and s2 are its objects. In other words,
smallobj serves as blue prints for the objects s1 and s2.
Encapsulation
In OOP, the encapsulation generally refers to the bundling of data, along
with the methods that operate on that data, into a single unit. Moreover,
encapsulation may also refer to a mechanism of restricting the direct
access to some components of an object, such that users cannot access
state values for all of the variables of a particular object. Encapsulation can
be used to hide both data members and data functions. Hence, in OOP,
encapsulation can be represented in the form of classes in which data and
fuctions are private as access specifier.
Example of Data Hiding Using the private Specifier
#include <iostream>
using namespace std;
class Rectangle {
private:
// Variables required for area calculation
int length;
int breadth;
public:
// Setter function for length
void setLength(int len) {
length = len;
}
// Setter function for breadth
void setBreadth(int brth) {
breadth = brth;
}
// Getter function for length
int getLength() {
return length;
}
// Getter function for breadth
int getBreadth() {
return breadth;
}
// Function to calculate area
int getArea() {
return length * breadth;
}
};
int main() {
// Create object of Rectangle class
Rectangle rectangle1;
// Initialize length using Setter function
rectangle1.setLength(8);
// Initialize breadth using Setter function
rectangle1.setBreadth(6);
// Access length using Getter function
cout << "Length = " << rectangle1.getLength() << endl;
// Access breadth using Getter function
cout << "Breadth = " << rectangle1.getBreadth() << endl;
// Call getArea() function
cout << "Area = " << rectangle1.getArea();
return 0;
}
Output
Length = 8
Breadth = 6
Area = 48
Here, we have made the length and breadth variables private. This means
that these variables cannot be directly accessed outside of the Rectangle
class.
To access these private variables, we have used public functions
setLength(), getLength(), setBreadth(), and getBreadth(). These are called
getter and setter functions.
Making the variables private allowed us to restrict unauthorized access
from outside the class. This is data hiding.
If we try to access the variables from the main() class, we will get an
error.
// error: rectangle1.length is inaccessible
rectangle1.length = 8;
// error: rectangle1.breadth is inaccessible
rectangle1.length = 6;
Abstraction
Abstraction is another important features of OOP that allows to showing
only essential attributes (data) and, hiding of unnecessary information.
Therefore, the main purpose of abstraction is to hide the details which are
not useful for the users. In abstraction, data is selected from a larger pool
to show only relevant details of the object to the user, which essentially
reduces the programming complexity and efforts.
Using classes, we can achieve data abstraction in C++. Program to
illustrate data abstraction using classes:
#include <iostream>
using namespace std;
#define PI 3.142
using namespace std;
// declaring class
class circle
{
private :
float radius; // private variables radius
public :
// function to get value of radius from the user
void get_radius(void)
{
cout<<"Enter radius of circle"<<endl;
cin>>radius;
}
// declaring function to calculate area of the circle
float area(void)
{
return(PI*radius*radius);
}
// declaring function to calculate circumference of the circle
float circumference(void)
{
return(PI*2*radius);
}
};
//implementation of the class
int main ()
{
// creating object of declared class
circle c;
c.get_radius();
cout << " AREA = " << c.area() << endl ;
cout << " CIRCUMFERENCE = " << c.circumference() << endl ;
return 0 ;
}
In C++, header files could be another form of abstraction. For instance,
consider the pow() method present in the header file of math.h.
We basically use the pow() function from the math.h header file. Then we
transfer the numbers as arguments. We calculate the power of a number
without understanding the algorithm that underpins it.
#include <iostream>
#include <math.h>
using namespace std ;
int main ()
{
int a = 5 ;
int power = 2 ;
int result = pow ( a , power ) ;// pow(n,power) is the power function to
calculate power
cout << " Square of a = " << result << std::endl ;
return 0 ;}
The core principle of implementing abstraction in C++ is permission labels
that determine how the data is accessed in a program. To impose
restrictions on data members of a class, we can use permission labels as
follows:
Public - Data members and member functions declared as public can be
accessed from anywhere the class is visible.
Private - Data members and member functions declared as private can
only be accessed within the class. Outside of the class, they are
inaccessible.
Protected – Data members and member functions can be accessed by
their friend class and derived class only.
Inheritance
The idea of classes leads to the idea of inheritance. In our daily lives, we
use the concept of classes divided into subclasses. We know that the
animal class is divided into mammals, amphibians, insects, birds, and so
on. The vehicle class is divided into cars, trucks, buses, motorcycles, and
so on.
In a similar way, an OOP class can become a parent of several subclasses.
In C++ the original class is called the base class; other classes can be
defined that share its characteristics, but add their own as well. These are
called derived classes. Such a procedure of creating derived classes
from the base class is called inheritance.
Don’t confuse the relation of objects to classes, on the one hand, with the
relation of a base class to derived classes, on the other. Objects, which
exist in the computer’s memory, each embody the exact characteristics of
their class, which serves as a template. Derived classes inherit some
characteristics from their base class, but add new ones of their own.
Example -1:
class A{
public: void func(){
cout << “print inherited”;
}};
class B : public A{};
int main(){
B b;
b.func();
return 0;}
Example-2
class A{
public: void Afunc(){
cout << “Fuction A \n”;}
};
class B{
public: void Bfunc(){
cout << “Fuction B \n”;}
};
class C : public A, public B{};
int main(){
C c;
c.Afunc();
c.Bfunc();
return 0;}
In OOP, the concept of inheritance provides an important extension to
the idea of reusability. A programmer can take an existing class and,
without modifying it, add additional features and capabilities to it. This is
done by deriving a new class from the existing one. The new class will
inherit the capabilities of the old one, but is free to add new features of its
own.
For example, you might have written (or purchased from someone else) a
class that creates a menu system, such as that used in Windows or other
Graphic User Interfaces (GUIs). This class works fine, and you don’t want
to change it, but you want to add the capability to make some menu entries
flash on and off. To do this, you simply create a new class that inherits all
the capabilities of the existing one but adds flashing menu entries.
Polymorphism
Polymorphism is the ability of any data to be processed in more than one
form. The word itself indicates the meaning as poly means many and
morphism means types. In simple words, we can define polymorphism
as the ability of a message to be displayed in more than one form.
Polymorphism is one of the most important feature of object oriented
programming language. The most common use of polymorphism in object-
oriented programming occurs when a parent class reference is used to refer
to a child class object.
Real life example of polymorphism, a person at the same time can have
different roles to play in life. Like a woman at the same time is a mother, a
wife, an employee and a daughter. So the same person has to have many
features but has to implement each as per the situation and the condition.
Polymorphism is considered as one of the important features of Object
Oriented Programming.
In C++ polymorphism is mainly divided into two types:
Compile time Polymorphism
Runtime Polymorphism
Function overloading
Compile time
Operator overloading
Polymorphism
Runtime Virtual functions
Compile time polymorphism: This type of polymorphism is achieved by
function overloading or operator overloading.
Function overloading: When there are multiple functions with same
name but different parameters then these functions are said to be
overloaded. Functions can be overloaded by change in number of
arguments or/and change in type of arguments.
#include <iostream.h>
using namespace std;
class Geeks
{ public:
// function with 1 int parameter
void func(int x)
{
cout << "value of x is " << x << endl;
}
// function with same name but 1 double parameter
void func(double x)
{
cout << "value of x is " << x << endl;
}
// function with same name and 2 int parameters
void func(int x, int y)
{
cout << "value of x and y is " << x << ", " << y << endl;
}};
int main() {
Geeks obj1;
obj1.func(7);
// The second 'func' is called
obj1.func(9.132);
// The third 'func' is called
obj1.func(85,64);
return 0;}
Output:
value of x is 7
value of x is 9.132
value of x and y is 85, 64
In the above example, a single function named func acts differently in
three different situations which is the property of polymorphism.
Operator overloading: C++ also provide option to overload operators.
For example, we can make the operator (‘+’) for string class to concatenate
two strings. We know that this is the addition operator whose task is to add
two operands. So a single operator ‘+’ when placed between integer
operands, adds them and when placed between string operands,
concatenates them.