Introduction to OOP in C++

By Shakib Ansari | Date: Mon, Jun 2, 2025

OOP ek programming style hai jo real-world entities ko classes aur objects ke through represent karta hai.

1. What is OOP?

OOP ka matlab hai Object-Oriented Programming. Ismein aap code ko real-world jaise structures mein likhte ho jaise:

  • Class – Blueprint/Design
  • Object – Real entity based on that blueprint

2. Classes and Objects

Class:

Ek class ek blueprint hoti hai jisme aap variables (data members) aur functions (member functions) define karte ho.

Object:

Object class ka ek instance hota hai jo us class ke members ko access kar sakta hai.

#include <iostream>
using namespace std;

class Car {
public:
    string brand;
    int speed;


    void display() {
        cout << "Brand: " << brand << ", Speed: " << speed << " km/h" << endl;
    }
};

int main() {
    Car c1;              // Object banaya
    c1.brand = "Toyota";
    c1.speed = 120;


    c1.display();        // Function call kiya


    return 0;
}

Output:

Brand: Toyota, Speed: 120 km/h

3. Access Specifiers

C++ mein 3 main access specifiers hote hain:

public:

  • Is type ke members ko class ke andar bhi access kiya ja sakta hai.
  • Aur class ke object ke through bhi directly access kiya ja sakta hai.

private:

  • Ye members sirf class ke andar hi accessible hote hain.
  • Object ke through directly access nahi kiya ja sakta.
  • Aise cases mein get aur set jaise functions use karte hain.

protected:

  • Ye bhi private ki tarah hota hai, lekin inheritance mein kaam aata hai.
  • Directly object ke through access nahi kar sakte.
Private members directly accessible nahi hote object ke through. Hume functions (set / get) use karne padte hain.

4. Member Functions and Data

Member Variables (Data Members)

Ye woh variables hote hain jo class ke andar declare hote hain.


Member Functions

Ye functions class ke andar hote hain jo kisi object ka kaam perform karte hain.

Example:

class Circle {
private:
    float radius;

public:
    void setRadius(float r) {
        radius = r;
    }


    float area() {
        return 3.14 * radius * radius;
    }
};

Real-Life Analogy:

Think of a class as a mobile phone blueprint – it defines buttons, screen size, etc.

Now each mobile phone you buy is an object – all based on that design but with their own data (like phone number, wallpaper, etc.)

Practice Questions:

  • Create a class Book with name, author, and price. Use member functions to set and display data.
  • Create a class BankAccount with deposit, withdraw, and check balance functions.
About the Author

Hi, I'm Shakib Ansari, Founder and CEO of BeyondMan. I'm a highly adaptive developer who quickly learns new programming languages and delivers innovative solutions with passion and precision.

Shakib Ansari
Programming

Comments