Introduction of Object Oriented Programming
Object-Oriented Programming (OOP) is a programming paradigm that uses objects and classes to design and develop software applications. Unlike procedural programming, which focuses on functions and logic, OOP emphasizes real-world entities, making the code more modular, reusable, and maintainable.
Key Concepts of OOP in C++
-
Class and Object
- A class is a blueprint for creating objects, defining attributes (data members) and behaviors (member functions).
- An object is an instance of a class that stores data and performs operations.
-
Encapsulation
- Bundling data and methods that operate on the data into a single unit (class).
- Data hiding is achieved using access specifiers like
private
,protected
, andpublic
.
-
Inheritance
- Enables one class (child) to inherit properties and behaviors from another class (parent), promoting code reusability.
- Example:
class Car : public Vehicle { }
-
Polymorphism
- Allows objects to be treated as instances of their parent class, enabling function overloading and method overriding.
- Example: Function overloading (
print(int)
,print(double)
) and function overriding (redefining a base class method in a derived class).
-
Abstraction
- Hiding complex implementation details and exposing only essential features.
- Achieved using abstract classes and pure virtual functions.
Why Use OOP in C++?
- Modularity: Code is organized into classes, improving maintainability.
- Reusability: Inheritance allows reuse of existing code.
- Scalability: Easy to extend and modify applications.
- Security: Encapsulation protects data from unauthorized access.
Example of OOP in C++
#include <iostream>
using namespace std;
// Class definition
class Car {
private:
string brand;
int speed;
public:
// Constructor
Car(string b, int s) {
brand = b;
speed = s;
}
// Method to display car details
void display() {
cout << “Brand: ” << brand << “, Speed: ” << speed << ” km/h” << endl;
}
};
int main() {
// Creating an object of the class
Car car1(“Tesla”, 200);
car1.display(); // Output: Brand: Tesla, Speed: 200 km/h
return 0;
}