OOPs Concepts in C++ (Four Pillars of Object-Oriented Programming)
Object-Oriented Programming (OOP) is built on four fundamental pillars that help structure and organize code efficiently.
These pillars are Encapsulation, Abstraction, Inheritance, and Polymorphism. Understanding these concepts is essential for mastering C++.
1. Overview of OOP Pillars
1. Encapsulation → Data hiding
2. Abstraction → Hiding implementation details
3. Inheritance → Code reusability
4. Polymorphism → Multiple forms
2. Encapsulation
Encapsulation is the process of wrapping data and functions into a single unit (class) and restricting direct access to data.
It improves data security and prevents unauthorized access.
#include <iostream>
using namespace std;
class Bank {
private:
int balance;
public:
void setBalance(int b) { balance = b; }
int getBalance() { return balance; }
};
3. Abstraction
Abstraction hides complex implementation details and shows only the necessary features.
It is achieved using abstract classes and interfaces.
class Shape {
public:
virtual void draw() = 0;
};
4. Inheritance
Inheritance allows one class to inherit properties and methods from another class.
It promotes code reusability and hierarchical classification.
#include <iostream>
using namespace std;
class Animal {
public:
void eat() { cout << "Eating"; }
};
class Dog : public Animal {};
Types of inheritance:
- Single
- Multiple
- Multilevel
- Hierarchical
5. Polymorphism
Polymorphism means 'many forms'. It allows functions or objects to behave differently based on context.
Types:
- Compile-time (Function overloading)
- Runtime (Function overriding)
int add(int a, int b) { return a+b; }
int add(int a, int b, int c) { return a+b+c; }
6. Real-World Example
Consider a smartphone: users interact with buttons (abstraction), data is protected (encapsulation), models inherit features (inheritance), and functions behave differently (polymorphism).
7. Advantages of OOP
1. Better code organization.
2. Code reusability.
3. Easy maintenance.
4. Enhanced security.
8. Common Mistakes
1. Not using private variables.
2. Misunderstanding inheritance types.
3. Ignoring abstraction.
4. Incorrect use of polymorphism.
9. Practice Exercises
1. Create a class for Student.
2. Implement inheritance using Animal and Dog.
3. Demonstrate function overloading.
4. Create abstract class Shape.
10. Interview Questions
1. What are the four pillars of OOP?
2. Difference between abstraction and encapsulation?
3. What is polymorphism?
4. Explain inheritance types.
11. Tips for Beginners
1. Understand concepts with examples.
2. Practice coding regularly.
3. Build mini projects.
4. Focus on real-world usage.
Conclusion
The four pillars of OOP are the foundation of modern programming. Mastering them in C++ will help you write efficient, secure, and reusable code.
Practice consistently and apply these concepts in real-world projects to gain expertise.
Codecrown