Kishan Jat

Object-Oriented Programming (OOP) with C++

Object-Oriented Programming (OOP) with C++
Kishan Jat

Kishan Jat

Introduction

C++ is a powerful programming language that supports the principles of Object-Oriented Programming (OOP). These principles help developers create modular, reusable, and maintainable code by modeling software around real-world objects.

Core OOP Concepts in C++

1. Classes and Objects

  • Class: A blueprint defining properties (attributes) and behaviors (methods).
  • Object: An instance of a class representing a specific entity.

Example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Car {
  public:
    string model;
    int year;

    Car(string m, int y) {
        model = m;
        year = y;
    }
};

Car myCar("Toyota", 2020);

2. Inheritance

Inheritance allows a class (derived class) to inherit attributes and methods from another class (base class), promoting code reuse.

Example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Vehicle {
  public:
    void start() {
      cout << "Vehicle started" << endl;
    }
};

class Bike : public Vehicle {
  public:
    void honk() {
      cout << "Bike honked" << endl;
    }
};

3. Polymorphism

Polymorphism enables entities to take multiple forms, typically implemented via method overriding, allowing derived classes to provide specific implementations.

Example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Animal {
  public:
    virtual void sound() {
      cout << "Animal sound" << endl;
    }
};

class Dog : public Animal {
  public:
    void sound() override {
      cout << "Bark" << endl;
    }
};

4. Abstraction

Abstraction hides complex implementation details and exposes simpler interfaces, facilitating easier usage and understanding.

5. Encapsulation

Encapsulation involves bundling data and methods operating on the data within a class while restricting direct access to some components for safety.

Importance of OOP in C++

  • Encourages modular design.
  • Simplifies maintenance and updates.
  • Supports real-world modeling.
  • Widely used in system software, games, and application development.

Mastering these concepts in C++ lays a strong foundation for writing efficient and scalable software.

Additional Resources