Object-Oriented Programming (OOP) Essentials
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 << [Link]() << 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;
}
};
int main() {
Animal* myDog = new Dog();
Animal* myCat = new Cat();
myDog->sound(); // Output: Barks
myCat->sound(); // Output: Meows
return 0;
}
4. Encapsulation:
1. Hiding internal details
2. Exposing only necessary information
Example :
class BankAccount {
private:
double balance;
public:
BankAccount() : balance(0) {}
void deposit(double amount) {
balance += amount;
}
double getBalance() {
return balance;
}
};
int main() {
BankAccount myAccount;
[Link](100);
cout << [Link]() << endl; // Output: 100
return 0;
}
5. Abstraction:
1. Showing only essential features
2. Hiding implementation details
Example :
class BankAccount {
private:
double balance;
public:
BankAccount() : balance(0) {}
void deposit(double amount) {
balance += amount;
}
double getBalance() {
return balance;
}
};
int main() {
BankAccount myAccount;
[Link](100);
cout << [Link]() << endl; // Output: 100
return 0;
}
Benefits of OOP:
1. Modularity
2. Reusability
3. Easier maintenance
4. Flexibility
Real-World Applications:
Banking systems
Game development
GUI applications
Web development
Summary:
OOP is a powerful paradigm that helps create modular, reusable, and maintainable code.
Mastering OOP concepts will boost your programming skills.