Abstraction and Encapsulation, Inheritance, Polymorphism and Abstract Classes
These concepts form the core principles of Object-Oriented Programming (OOP). In C++, they allow a program to represent real-world entities, protect data, reuse existing code, and provide different implementations of the same interface.
1. Abstraction
Abstraction is the process of representing only the essential features of an object while hiding unnecessary implementation details.
In simple words, abstraction answers:
What does an object do?
rather than:
How does the object do it?
For example, when a user drives a car, the user operates the steering wheel, accelerator and brakes. The internal operation of the engine, fuel injection system and transmission is not required to be known by the user.
Similarly, in C++, a class can provide public functions through which users interact with an object while the internal implementation remains hidden.
Definition
Abstraction is an OOP mechanism that exposes the essential characteristics and operations of an object while hiding unnecessary implementation details.
1.1 Example of Abstraction
Consider a bank account:
class BankAccount
{
public:
void withdraw(double amount)
{
// Internal banking logic
}
};The user only needs to call:
account.withdraw(5000);The user does not need to know how the bank internally verifies the balance, records the transaction, or updates its database.
Thus, the interface exposes what operation is available, while implementation details remain hidden.
2. Abstraction in C++
Abstraction can be achieved in C++ using several mechanisms, particularly:
Classes
Access specifiers
Member functions
Abstract classes
Pure virtual functions
For example:
class ATM
{
private:
int balance;
public:
void withdraw(int amount)
{
if (amount <= balance)
balance -= amount;
}
};Here, the user interacts with the withdraw() function without directly accessing the internal balance.
3. Encapsulation
Encapsulation is the process of bundling data and the functions that operate on that data into a single unit, usually a class.
It also provides controlled access to the internal data of an object.
Definition
Encapsulation is the mechanism of wrapping data members and member functions together within a class and controlling access to the internal data.
For example:
class Student
{
private:
int marks;
public:
void setMarks(int m)
{
if (m >= 0 && m <= 100)
marks = m;
}
int getMarks()
{
return marks;
}
};Here:
marksis private.setMarks()controls how marks are assigned.getMarks()provides controlled access to marks.
The data and functions are encapsulated within the Student class.
4. Encapsulation and Data Hiding
Data hiding is an important consequence of encapsulation.
If a data member is declared as private, it cannot normally be accessed directly from outside the class.
For example:
class Account
{
private:
double balance;
public:
void deposit(double amount)
{
if (amount > 0)
balance += amount;
}
};The following is not permitted from outside the class:
account.balance = -5000; // ErrorInstead, access is controlled through:
account.deposit(5000);Therefore, encapsulation helps prevent inappropriate or uncontrolled modification of an object's state.
5. Abstraction vs Encapsulation
These two concepts are closely related but are not identical.
| Abstraction | Encapsulation |
|---|---|
| Focuses on what an object does | Focuses on how data and operations are packaged and protected |
| Hides unnecessary implementation details | Controls access to internal members |
| Helps reduce complexity | Helps protect object state |
| Achieved using classes, interfaces, abstract classes, etc. | Mainly implemented using classes and access specifiers |
| Concerned with essential features | Concerned with bundling and access control |
Easy way to remember
Abstraction → What to show
Encapsulation → What to hide/protect
6. Inheritance
Inheritance is an OOP mechanism through which a new class acquires properties and behaviour from an existing class.
The existing class is called the:
Base class
Parent class
Super class
The new class is called the:
Derived class
Child class
Sub class
Inheritance promotes code reuse and establishes a relationship between classes.
Definition
Inheritance is the mechanism by which a derived class acquires accessible data members and member functions of an existing base class.
7. Basic Syntax of Inheritance
class DerivedClass : access_specifier BaseClass
{
// Members of derived class
};For example:
class Animal
{
public:
void eat()
{
cout << "Animal eats";
}
};
class Dog : public Animal
{
public:
void bark()
{
cout << "Dog barks";
}
};Here:
Animal→ Base classDog→ Derived classeat()→ Inherited member functionbark()→ Derived class member function
8. Example of Inheritance
#include <iostream>
using namespace std;
class Person
{
public:
string name;
void displayName()
{
cout << "Name: " << name << endl;
}
};
class Student : public Person
{
public:
int rollNo;
void displayRollNo()
{
cout << "Roll Number: " << rollNo << endl;
}
};
int main()
{
Student s;
s.name = "Rahul";
s.rollNo = 101;
s.displayName();
s.displayRollNo();
return 0;
}Output
Name: Rahul
Roll Number: 101The Student class inherits the accessible member name and the function displayName() from Person.
9. Types of Inheritance
C++ supports several forms of inheritance.
9.1 Single Inheritance
One derived class inherits from one base class.
A
↓
BExample:
class B : public A
{
};9.2 Multilevel Inheritance
A class is derived from another derived class.
A
↓
B
↓
CExample:
class B : public A
{
};
class C : public B
{
};9.3 Multiple Inheritance
One derived class inherits from more than one base class.
A B
\ /
\ /
CExample:
class C : public A, public B
{
};9.4 Hierarchical Inheritance
Multiple derived classes inherit from the same base class.
A
/ \
B CExample:
class B : public A
{
};
class C : public A
{
};9.5 Hybrid Inheritance
Hybrid inheritance is a combination of two or more forms of inheritance.
For example, a combination of hierarchical and multiple inheritance can create a hybrid structure.
10. Advantages of Inheritance
Inheritance provides several benefits:
Code reusability – Existing functionality can be reused.
Reduced code duplication – Common functionality can be placed in a base class.
Easy maintenance – Common modifications can be made at the appropriate level.
Extensibility – Derived classes can add new functionality.
Supports polymorphism – Inheritance is an important foundation for runtime polymorphism.
Logical classification – It can represent relationships such as:
Animal → Dog
Vehicle → Car
Employee → Manager
Shape → Circle11. Polymorphism
The word polymorphism is derived from two Greek words:
Poly → Many
Morphism → Forms
Therefore, polymorphism means one interface or operation having multiple forms.
In C++, the same function name or interface can produce different behaviour depending on the context.
Definition
Polymorphism is the ability of an interface, function, or operation to exhibit different behaviours in different situations.
For example:
cout << 10 + 20;and
cout << 10.5 + 20.5;The + operator operates with different data types.
Similarly, a base-class interface can be used to invoke different derived-class implementations.
12. Types of Polymorphism in C++
Polymorphism in C++ is broadly classified into:
Polymorphism
|
-----------------------
| |
Compile-time Run-time
Polymorphism Polymorphism
| |
---------------- Virtual Functions
| |
Function Operator
Overloading Overloading13. Compile-Time Polymorphism
Compile-time polymorphism is resolved by the compiler during compilation.
Common examples include:
Function overloading
Operator overloading
13.1 Function Overloading
Function overloading means defining multiple functions with the same name but different parameter lists.
Example:
#include <iostream>
using namespace std;
class Calculator
{
public:
int add(int a, int b)
{
return a + b;
}
int add(int a, int b, int c)
{
return a + b + c;
}
};
int main()
{
Calculator c;
cout << c.add(10, 20) << endl;
cout << c.add(10, 20, 30);
return 0;
}Output
30
60The compiler determines which add() function should be called based on the arguments.
14. Operator Overloading
C++ allows many operators to be given special meaning for user-defined types.
For example, the + operator can be overloaded for adding two objects.
class Complex
{
public:
int real, imag;
Complex operator+(Complex c)
{
Complex temp;
temp.real = real + c.real;
temp.imag = imag + c.imag;
return temp;
}
};Here, the + operator has been defined for objects of the Complex class.
This is another example of compile-time polymorphism.
15. Run-Time Polymorphism
Run-time polymorphism is achieved primarily through virtual functions and overriding in an inheritance hierarchy.
The appropriate function implementation is selected during program execution.
Consider:
class Animal
{
public:
virtual void sound()
{
cout << "Animal makes a sound";
}
};
class Dog : public Animal
{
public:
void sound() override
{
cout << "Dog barks";
}
};Now:
Animal *ptr;
Dog d;
ptr = &d;
ptr->sound();Output
Dog barksAlthough ptr is an Animal*, it points to a Dog object. Because sound() is virtual, the overridden Dog::sound() is selected at runtime.
16. Method Overriding
When a derived class provides its own implementation of a member function already provided by the base class, it is called function overriding.
Example:
class Animal
{
public:
virtual void sound()
{
cout << "Animal sound";
}
};
class Cat : public Animal
{
public:
void sound() override
{
cout << "Cat meows";
}
};The derived class Cat overrides the sound() function.
17. Abstraction, Encapsulation, Inheritance and Polymorphism Together
These concepts work together to provide the major advantages of OOP.
Consider a simple vehicle management system.
Vehicle
|
-------------------
| |
Car Bike
| |
start() start()The Vehicle class can define a common interface.
Car and Bike can provide their own implementations.
Abstraction → Only necessary vehicle operations are exposed.
Encapsulation → Internal vehicle data is protected.
Inheritance →
CarandBikeinherit fromVehicle.Polymorphism →
start()can behave differently forCarandBike.
These four concepts therefore complement one another.
18. Abstract Class
An abstract class is a class that is designed to act as a base class and cannot be instantiated directly.
In C++, a class becomes abstract when it contains at least one pure virtual function.
Definition
An abstract class is a class containing at least one pure virtual function and cannot be used to create objects directly.
19. Pure Virtual Function
A pure virtual function is a virtual function declared using = 0.
Syntax
virtual return_type functionName() = 0;Example:
class Shape
{
public:
virtual void draw() = 0;
};Here:
virtual void draw() = 0;is a pure virtual function.
Therefore, Shape becomes an abstract class.
20. Example of Abstract Class
#include <iostream>
using namespace std;
class Shape
{
public:
virtual void area() = 0;
};
class Circle : public Shape
{
private:
float radius;
public:
Circle(float r)
{
radius = r;
}
void area() override
{
cout << "Area of Circle = "
<< 3.14 * radius * radius;
}
};
int main()
{
Circle c(5);
c.area();
return 0;
}Output
Area of Circle = 78.5Here:
Shape→ Abstract classarea()→ Pure virtual functionCircle→ Derived classCircle::area()→ Overridden functionc→ Object ofCircle
The following is not allowed:
Shape s; // Errorbecause Shape is an abstract class.
21. Why Are Abstract Classes Used?
Abstract classes are useful when we want to define a common interface for a group of related classes without providing a complete implementation at the base-class level.
For example:
Shape
|
------------------
| | |
Circle Rectangle TriangleAll shapes have an area(), but the calculation is different for each shape.
Therefore, the base class can specify:
virtual void area() = 0;and each derived class can provide its own implementation.
This is an important application of abstraction and runtime polymorphism.
22. Abstract Class with Multiple Derived Classes
#include <iostream>
using namespace std;
class Shape
{
public:
virtual void area() = 0;
};
class Circle : public Shape
{
public:
void area() override
{
cout << "Area of Circle" << endl;
}
};
class Rectangle : public Shape
{
public:
void area() override
{
cout << "Area of Rectangle" << endl;
}
};
int main()
{
Circle c;
Rectangle r;
c.area();
r.area();
return 0;
}Output
Area of Circle
Area of RectangleBoth derived classes follow the common interface provided by Shape, but each implements the operation differently.
23. Abstract Class and Polymorphism
Abstract classes are particularly useful when combined with base-class pointers or references.
Shape *ptr;
Circle c;
Rectangle r;
ptr = &c;
ptr->area();
ptr = &r;
ptr->area();The same pointer:
Shape *ptrcan refer to different derived-class objects.
The call:
ptr->area();can therefore execute different implementations depending on the actual object.
This demonstrates runtime polymorphism.
24. Difference Between Concrete and Abstract Classes
| Concrete Class | Abstract Class |
|---|---|
| Can be instantiated | Cannot be instantiated |
| Objects can be created directly | Objects cannot be created directly |
| Does not necessarily contain pure virtual functions | Contains at least one pure virtual function |
| Can be used as a normal class | Primarily used as a base class |
| Provides complete implementation where required | May define an interface requiring derived classes to implement operations |
25. Difference Between Abstraction and Abstract Class
These terms should not be treated as synonyms.
Abstraction is an OOP principle.
An abstract class is a C++ language mechanism that can be used to implement abstraction.
For example:
class Shape
{
public:
virtual void area() = 0;
};The concept of hiding unnecessary implementation details is abstraction, while Shape being non-instantiable because of its pure virtual function makes it an abstract class.
26. Overall Comparison of Four Major OOP Concepts
| Concept | Main Purpose | C++ Mechanism |
|---|---|---|
| Abstraction | Hide unnecessary implementation details | Classes, interfaces through classes, abstract classes |
| Encapsulation | Bundle and protect data and operations | Classes, access specifiers |
| Inheritance | Reuse and extend existing classes | : inheritance syntax |
| Polymorphism | Allow one interface to have multiple behaviours | Overloading, overriding, virtual functions |
27. Important Points for Students
Abstraction hides unnecessary implementation details.
Encapsulation combines data and functions and controls access to data.
privatemembers are useful for implementing data hiding.Inheritance allows a derived class to reuse and extend a base class.
C++ supports single, multiple, multilevel, hierarchical and hybrid inheritance.
Polymorphism means one interface having multiple forms.
Function overloading is an example of compile-time polymorphism.
Operator overloading is also a form of compile-time polymorphism.
Virtual functions support runtime polymorphism.
Function overriding occurs when a derived class provides a new implementation of an inherited virtual function.
A pure virtual function is declared using
= 0.A class containing at least one pure virtual function is an abstract class.
An abstract class cannot be instantiated directly.
Abstract classes are useful for defining a common interface for derived classes.
Abstraction and encapsulation are related, but they represent different OOP concepts.
Quick Memory Rule
Abstraction → Hide complexity
Encapsulation → Protect data
Inheritance → Reuse code
Polymorphism → One interface, many behaviours
Abstract Class → Common interface without direct object creation
No comments:
Post a Comment