Overview of OOP Principles: Encapsulation, Inheritance, Polymorphism, and Abstraction in C++
Object-Oriented Programming (OOP) is a programming paradigm centered around objects, which combine data and methods to manipulate that data. C++ is a powerful language that supports OOP through four main principles: Encapsulation, Inheritance, Polymorphism, and Abstraction.
1. Encapsulation
Encapsulation involves bundling data and the methods that operate on the data into a single unit, typically a class. Access to this data is restricted through access specifiers such as private, protected, and public.
Example:
#include <iostream>
class Car {
private:
std::string brand;
int speed;
public:
void setBrand(const std::string &b) {
brand = b;
}
void setSpeed(int s) {
if (s > 0) {
speed = s;
}
}
void display() {
std::cout << "Brand: " << brand << ", Speed: " << speed << " km/h" << std::endl;
}
};
int main() {
Car car;
car.setBrand("Toyota");
car.setSpeed(120);
car.display();
return 0;
}
2. Inheritance
Inheritance allows a class (child class) to inherit attributes and methods from another class (parent class). It promotes code reusability.
Example:
#include <iostream>
class Vehicle {
public:
void move() {
std::cout << "This vehicle moves." << std::endl;
}
};
class Car : public Vehicle {
public:
void honk() {
std::cout << "Car honks: Beep! Beep!" << std::endl;
}
};
int main() {
Car car;
car.move();
car.honk();
return 0;
}
3. Polymorphism
Polymorphism allows objects to be treated as instances of their parent class, enabling a single interface to represent different data types. It is achieved using function overloading or overriding.
Example:
#include <iostream>
class Animal {
public:
virtual void sound() {
std::cout << "Animal makes a sound." << std::endl;
}
};
class Dog : public Animal {
public:
void sound() override {
std::cout << "Dog barks: Woof! Woof!" << std::endl;
}
};
class Cat : public Animal {
public:
void sound() override {
std::cout << "Cat meows: Meow!" << std::endl;
}
};
int main() {
Animal *a1 = new Dog();
Animal *a2 = new Cat();
a1->sound();
a2->sound();
delete a1;
delete a2;
return 0;
}
4. Abstraction
Abstraction involves hiding implementation details and showing only the essential features of an object. Abstract classes or interfaces are used to achieve abstraction.
Example:
#include <iostream>
class Shape {
public:
virtual void draw() = 0; // Pure virtual function
};
class Circle : public Shape {
public:
void draw() override {
std::cout << "Drawing a Circle." << std::endl;
}
};
class Rectangle : public Shape {
public:
void draw() override {
std::cout << "Drawing a Rectangle." << std::endl;
}
};
int main() {
Shape *shape1 = new Circle();
Shape *shape2 = new Rectangle();
shape1->draw();
shape2->draw();
delete shape1;
delete shape2;
return 0;
}
These examples demonstrate how C++ enables developers to implement OOP principles effectively, promoting modular, reusable, and maintainable code.