Object-Oriented Programming (OOP) is one of the core features of C++.
It involves
organizing code into "objects," which are instances of "classes." Here are the
basic principles of OOP:
Classes and Objects: A class is a blueprint for creating objects. It defines
attributes (variables) and methods (functions).
cpp
Copy
class Car {
public:
string brand;
string model;
int year;
void startEngine() {
cout << "The " << brand << " " << model << " is starting!" << endl;
}
};
int main() {
Car myCar; // Creating an object
myCar.brand = "Toyota";
myCar.model = "Corolla";
myCar.year = 2021;
myCar.startEngine(); // Calling a method
}
Encapsulation: Encapsulation is the practice of bundling data (attributes) and
methods that operate on the data into a single unit called a class. Access
modifiers such as public, private, and protected help control how the data is
accessed.
cpp
Copy
class BankAccount {
private:
double balance;
public:
void deposit(double amount) {
balance += amount;
}
double getBalance() {
return balance;
}
};
Inheritance: Inheritance allows one class to inherit the properties and methods of
another class. This promotes code reusability.
cpp
Copy
class Animal {
public:
void eat() {
cout << "Eating..." << endl;
}
};
class Dog : public Animal {
public:
void bark() {
cout << "Woof!" << endl;
}
};
Polymorphism: Polymorphism allows you to use the same method name for different
behaviors based on the object type.
cpp
Copy
class Shape {
public:
virtual void draw() {
cout << "Drawing a shape" << endl;
}
};
class Circle : public Shape {
public:
void draw() override {
cout << "Drawing a circle" << endl;
}
};