OOP Principles L-2
OOP Principles L-2
Data abstraction is one of the most essential and important feature of object oriented
programming in C++. 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 details or implementation.
Consider a real life example of a man driving a car. The man only knows that pressing the
accelerators will increase the speed of car or applying brakes will stop the car but he does not
know about how on pressing accelerator the speed is actually increasing, he does not know about
the inner mechanism of the car or the implementation of accelerator, brakes etc in the car. This is
what abstraction is.
We can implement Abstraction in C++ using classes. Class helps us to group data members and
member functions using available access specifiers. A Class can decide which data member will
be visible to outside world and which is not.
One more type of abstraction in C++ can be header files. For example, consider the pow()
method present in math.h header file. Whenever we need to calculate power of a number, we
simply call the function pow() present in the math.h header file and pass the numbers as
arguments without knowing the underlying algorithm according to which the function is actually
calculating power of numbers.
Access specifiers are the main pillar of implementing abstraction in C++. We can use access
specifiers to enforce restrictions on class members. For example:
• Members declared as public in a class, can be accessed from anywhere in the program.
• Members declared as private in a class, can be accessed only from within the class. They
are not allowed to be accessed from any part of code outside the class.
We can easily implement abstraction using the above two features provided by access specifiers.
Say, the members that defines the internal implementation can be marked as private in a class.
And the important information needed to be given to the outside world can be marked as public.
And these public members can access the private members as they are inside the class.
\
Example:
#include <iostream>
using namespace std;
class implementAbstraction
{
private:
int a, b;
public:
void display()
{
cout<<"a = "<<a << endl;
cout<<"b = "<< b << endl;
}
};
int main()
{
implementAbstraction obj;
obj.set(10, 20);
obj.display();
return0;
}
Output:
a = 10
b = 20
You can see in the above program we are not allowed to access the variables a and b directly,
however one can call the function set() to set the values in a and b and the function display() to
display the values of a and b.
Advantages of Data Abstraction:
• Helps the user to avoid writing the low level code
• Avoids code duplication and increases reusability.
• Can change internal implementation of class independently without affecting the user.
• Helps to increase security of an application or program as only important details are
provided to the user.
Encapsulation in C++
In normal terms Encapsulation is defined as wrapping up of data and information under a
single unit. In Object Oriented Programming, Encapsulation is defined as binding together the
data and the functions that manipulates them.
Consider a real life example of encapsulation, in a company there are different sections like
the accounts section, finance section, sales section etc. The finance section handles all the
financial transactions and keep records of all the data related to finance. Similarly the sales
section handles all the sales related activities and keep records of all the sales.
Now there may arise a situation when for some reason an official from finance section needs all
the data about sales in a particular month. In this case, he is not allowed to directly access the
data of sales section. He will first have to contact some other officer in the sales section and
then request him to give the particular data. This is what encapsulation is. Here the data of sales
section and the employees that can manipulate them are wrapped under a single name “sales
section”.
Encapsulation also lead to data abstraction or hiding. As using encapsulation also hides the data.
In the above example the data of any of the section like sales, finance or accounts is hidden from
any other section.
In C++ encapsulation can be implemented using Class and access modifiers. Look at the below
program:
#include<iostream>
using namespace std;
class Encapsulation
{
private:
// data hidden from outside world
int x;
public:
// function to set value of
// variable x
void set(int a)
{
x =a;
}
// main function
int main()
{
Encapsulation obj;
obj.set(5);
cout<<obj.get();
return 0;
}
output:
5
In the above program the variable x is made private. This variable can be accessed and
manipulated only using the functions get() and set() which are present inside the class. Thus we
can say that here, the variable x and the functions get() and set() are binded together which is
nothing but encapsulation.
Role of access specifiers in encapsulation
As we have seen in above example, access specifiers plays an important role in implementing
encapsulation in C++. The process of implementing encapsulation can be sub-divided into two
steps:
1. The data members should be labeled as private using the private access specifiers
2. The member function which manipulates the data members should be labeled as public
using the public access specifier
Inheritance in C++
The capability of a class to derive properties and characteristics from another class is
called Inheritance. Inheritance is one of the most important feature of Object Oriented
Programming.
Sub Class: The class that inherits properties from another class is called Sub class or Derived
Class.
Super Class:The class whose properties are inherited by sub class is called Base Class or Super
class.
You can clearly see that above process results in duplication of same code 3 times. This
increases the chances of error and data redundancy. To avoid this type of situation,
inheritance is used. If we create a class Vehicle and write these three functions in it and inherit
the rest of the classes from the vehicle class, then we can simply avoid the duplication of data
and increase re-usability. Look at the below diagram in which the three classes are inherited from
vehicle class:
Using inheritance, we have to write the functions only one time instead of three times as we have
inherited rest of the three classes from base class(Vehicle).
Implementing inheritance in C++: For creating a sub-class which is inherited from the base
class we have to follow the below syntax.
Syntax:
class subclass_name : access_mode base_class_name
{
//body of subclass
};
Here, subclass_name is the name of the sub class, access_mode is the mode in which you want
to inherit this sub class for example: public, private etc. and base_class_name is the name of the
base class from which you want to inherit the sub class.
Note: A derived class doesn’t inherit access to private data members. However, it does inherit a
full parent object, which contains any private members which that class declares.
#include <bits/stdc++.h>
using namespace std;
//Base class
class Parent
{
public:
int id_p;
};
//main function
int main()
{
Child obj1;
return0;
}
Output:
Child id is 7
Parent id is 91
In the above program the ‘Child’ class is publicly inherited from the ‘Parent’ class so the public
data members of the class ‘Parent’ will also be inherited by the class ‘Child’.
Modes of Inheritance
1. Public mode: If we derive a sub class from a public base class. Then the public member of
the base class will become public in the derived class and protected members of the base
class will become protected in derived class.
2. Protected mode: If we derive a sub class from a Protected base class. Then both public
member and protected members of the base class will become protected in derived class.
3. Private mode: If we derive a sub class from a Private base class. Then both public member
and protected members of the base class will become Private in derived class.
Note : The private members in the base class cannot be directly accessed in the derived class,
while protected members can be directly accessed. For example, Classes B, C and D all contain
the variables x, y and z in below example. It is just question of access.
classB : public A
{
// x is public
// y is protected
// z is not accessible from B
};
classC : protected A
{
// x is protected
// y is protected
// z is not accessible from C
};
Syntax:
class subclass_name : access_mode base_class
{
//body of subclass
};
// C++ program to explain
// Single inheritance
#include <iostream>
using namespace std;
// base class
class Vehicle {
public:
Vehicle()
{
cout << "This is a Vehicle"<< endl;
}
};
};
// main function
int main()
{
// creating object of sub class will
// invoke the constructor of base classes
Car obj;
return0;
}
Output:
This is a vehicle
2. Multiple Inheritance: Multiple Inheritance is a feature of C++ where a class can inherit
from more than one classes. i.e one sub class is inherited from more than one base classes.
Syntax:
class subclass_name : access_mode base_class1, access_mode base_class2, ....
{
//body of subclass
};
Here, the number of base classes will be separated by a comma (‘, ‘) and access mode for
every base class must be specified.
};
// main function
int main()
{
// creating object of sub class will
// invoke the constructor of base classes
Car obj;
return 0;
}
Output:
This is a Vehicle
This is a 4 wheeler Vehicle
3. Multilevel Inheritance: In this type of inheritance, a derived class is created from another
derived class.
// C++ program to implement
// Multilevel Inheritance
#include <iostream>
using namespace std;
// base class
class Vehicle
{
public:
Vehicle()
{
cout << "This is a Vehicle"<< endl;
}
};
class fourWheeler: public Vehicle
{ public:
fourWheeler()
{
cout<<"Objects with 4 wheels are vehicles"<<endl;
}
};
// sub class derived from two base classes
class Car: public fourWheeler{
public:
car()
{
cout<<"Car has 4 Wheels"<<endl;
}
};
// main function
int main()
{
//creating object of sub class will
//invoke the constructor of base classes
Car obj;
return 0;
}
output:
This is a Vehicle
Objects with 4 wheels are vehicles
Car has 4 Wheels
4. Hierarchical Inheritance: In this type of inheritance, more than one sub class is inherited
from a single base class. i.e. more than one derived class is created from a single base class.
// base class
class Vehicle
{
public:
Vehicle()
{
cout << "This is a Vehicle"<< endl;
}
};
};
// second sub class
class Bus: public Vehicle
{
};
// main function
int main()
{
// creating object of sub class will
// invoke the constructor of base class
Car obj1;
Bus obj2;
return 0;
}
Output:
This is a Vehicle
This is a Vehicle
5. Hybrid (Virtual) Inheritance: Hybrid Inheritance is implemented by combining more
than one type of inheritance. For example: Combining Hierarchical inheritance and
Multiple Inheritance.
Below image shows the combination of hierarchical and multiple inheritance:
#include <iostream>
using namespace std;
// base class
class Vehicle
{
public:
Vehicle()
{
cout << "This is a Vehicle"<< endl;
}
};
//base class
class Fare
{
public:
Fare()
{
cout<<"Fare of Vehicle\n";
}
};
};
};
// main function
int main()
{
// creating object of sub class will
// invoke the constructor of base class
Bus obj2;
return0;
}
Output:
This is a Vehicle
Fare of Vehicle
Polymorphism in C++
The word polymorphism means having many forms. In simple words, we can define
polymorphism as the ability of a message to be displayed in more than one form.
Real life example of polymorphism, a person at the same time can have different characteristic.
Like a man at the same time is a father, a husband, an employee. So the same person posses
different behavior in different situations. This is called polymorphism.
Polymorphism is considered as one of the important features of Object Oriented Programming.
• 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.
int main() {
Geeks obj1;
• 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.
•
Example:
// CPP program to illustrate
// Operator Overloading
#include<iostream>
using namespace std;
class Complex {
private:
int real, imag;
public:
Complex(int r = 0, int i =0)
{
real = r;
imag = i;
}
int main()
{
Complex c1(10, 5), c2(2, 4);
Complex c3 = c1 + c2; // An example call to "operator+"
c3.print();
}
Output:
12 + i9
In the above example the operator ‘+’ is overloaded. The operator ‘+’ is an addition
operator and can add two numbers(integers or floating point) but here the operator is
made to perform addition of two imaginary or complex numbers. To learn operator
overloading in details visit this link.
2. Runtime polymorphism: This type of polymorphism is achieved by Function Overriding.
• Function overriding on the other hand occurs when a derived class has a definition
for one of the member functions of the base class. That base function is said to
be overridden.
1. #include <iostream>
2. using namespace std;
3. class Animal {
4. public:
5. void eat(){
6. cout<<"Eating...";
7. }
8. };
9. class Dog: public Animal
10. {
11. public:
12. void eat()
13. {
14. cout<<"Eating bread...";
15. }
16. };
17. int main(void) {
18. Dog d = Dog();
19. d.eat();
20. return 0;
21. }
Output:
Eating bread...
Ref:
geeksforgeeks
javatpoint
tutorialspoimt