All Oops Concepts In One Program To Implement In C++

4 min read Jul 03, 2024
All Oops Concepts In One Program To Implement In C++

All OOP Concepts in One C++ Program

This program demonstrates all the major Object-Oriented Programming (OOP) concepts in C++:

  • Abstraction
  • Encapsulation
  • Inheritance
  • Polymorphism

Let's break down the code:

#include 
#include 

// Base class for all vehicles
class Vehicle {
protected:
    std::string brand;
    int year;

public:
    Vehicle(std::string b, int y) : brand(b), year(y) {}
    
    // Abstract function for getting the vehicle type
    virtual std::string getVehicleType() = 0;

    // Common functionality for all vehicles
    void display() {
        std::cout << "Brand: " << brand << std::endl;
        std::cout << "Year: " << year << std::endl;
        std::cout << "Type: " << getVehicleType() << std::endl;
    }
};

// Derived class for cars
class Car : public Vehicle {
public:
    Car(std::string b, int y) : Vehicle(b, y) {}

    // Overridden function to get the vehicle type
    std::string getVehicleType() override {
        return "Car";
    }
};

// Derived class for bikes
class Bike : public Vehicle {
public:
    Bike(std::string b, int y) : Vehicle(b, y) {}

    // Overridden function to get the vehicle type
    std::string getVehicleType() override {
        return "Bike";
    }
};

int main() {
    // Create objects of different vehicle types
    Car car("Toyota", 2022);
    Bike bike("Yamaha", 2021);

    // Display information about the vehicles
    std::cout << "\nCar Details:\n";
    car.display();

    std::cout << "\nBike Details:\n";
    bike.display();

    return 0;
}

Explanation:

  1. Abstraction: The Vehicle class provides an abstract interface for all vehicles, hiding the internal implementation details. The getVehicleType() function is abstract, requiring derived classes to implement it.

  2. Encapsulation: Data members (brand, year) are protected and accessible only through member functions. This ensures data integrity and controlled access.

  3. Inheritance: The Car and Bike classes inherit from the Vehicle class, inheriting its attributes and methods. This promotes code reusability and avoids redundancy.

  4. Polymorphism: The getVehicleType() function is overridden in the derived classes, allowing different types of vehicles to provide their specific type information. This is achieved through dynamic binding, where the correct function call is determined at runtime.

Output:

Car Details:
Brand: Toyota
Year: 2022
Type: Car

Bike Details:
Brand: Yamaha
Year: 2021
Type: Bike

This example demonstrates how OOP concepts can be effectively used to design and implement a program. It shows the power of abstraction, encapsulation, inheritance, and polymorphism for creating flexible, modular, and reusable code.

Latest Posts