Introduction:
Object-Oriented Programming (OOP) is a programming paradigm that revolves around
the concept of objects and classes. It's a powerful tool for solving complex problems
and creating reusable code.
Basic Concepts:
1. Classes and Objects:
1. Class: A blueprint or template
2. Object: An instance of a class
2. Inheritance:
1. Mechanism for creating new classes from existing ones
2. Promotes code reusability
Example :
1. class Vehicle {
2. public:
3. Vehicle(string brand, int year) {
4. this->brand = brand;
5. this->year = year;
6. }
7. string getBrand() { return brand; }
8. protected:
9. string brand;
10. int year;
11. };
12. class Car : public Vehicle {
13. public:
, 14. Car(string brand, string model, int year) : Vehicle(brand, year) {
15. this->model = model;
16. }
17. string getModel() { return model; }
18. private:
19. string model;
20. };
21. int main() {
22. Car myCar("Toyota", "Corolla", 2015);
23. cout << myCar.getBrand() << endl; // Output: Toyota
24. return 0;
25. }
3. Polymorphism:
1. Ability to take multiple forms
2. Method overriding
Example :
class Animal {
public:
virtual void sound() {
cout << "Makes a sound" << endl;
}
};
class Dog : public Animal {
public:
void sound() {
cout << "Barks" << endl;
}
};
class Cat : public Animal {
public:
void sound() {
cout << "Meows" << endl;
}