Free tutorials & notes in Hindi & English · Clean code examples 🧰 Free PDF & Image Tools →
🟣 OOP  ·  Lesson 37

OOP Concepts in C++

In this lesson: OOP in C++ explained simply — class, object, encapsulation, abstraction, inheritance, polymorphism — with code. In Hindi & English.

What is object-oriented programming?

In procedural programming (like C), a program is a list of functions that work on separate data. As programs grow, it becomes hard to know which function changes which data. Object-oriented programming (OOP) groups data and the functions that work on it into objects that model real things — a student, a bank account, a library book.

OOP asks: *what things exist in my problem, what do they know, and what can they do?*

C++ added OOP on top of C, which is why it is often called "C with classes". This lesson explains each OOP concept with one running example — a school bank account — and links to the detailed lesson for each.

Class and object

A class is a blueprint; an object is a real thing built from it.

C++
class Account {          // blueprint
public:
    std::string holder;
    double balance;
};

Account a1;              // object 1
Account a2;              // object 2 — separate data

holder and balance are data members (attributes); functions inside the class are member functions (methods). Every object has its own copy of the data members. See classes and objects.

1. Encapsulation

Encapsulation means bundling data with the functions that use it *and* hiding the data from direct outside access. Make data private and allow changes only through public functions that check the rules.

C++
class Account {
private:
    double balance = 0;               // hidden
public:
    void deposit(double amt) {
        if (amt > 0) balance += amt;  // rule enforced in one place
    }
    double getBalance() const { return balance; }
};

Nobody can now write acc.balance = -5000;. See access specifiers.

2. Abstraction

Abstraction means showing *what* an object does and hiding *how*. When you call acc.withdraw(500) you do not care how the balance is stored, logged or checked — you use a simple interface. In C++, abstraction is achieved with classes, access specifiers and abstract classes (classes with pure virtual functions) that define an interface without an implementation. See abstract classes.

3. Inheritance

Inheritance lets a new class (derived/child) reuse and extend an existing class (base/parent). A SavingsAccount *is an* Account that also earns interest.

C++
class SavingsAccount : public Account {
    double rate = 0.04;
public:
    void addInterest() { deposit(getBalance() * rate); }
};

SavingsAccount automatically has deposit() and getBalance(). Types include single, multilevel, multiple, hierarchical and hybrid inheritance. See inheritance and multiple inheritance.

4. Polymorphism

Polymorphism ("many forms") means one name or interface can behave differently depending on the object.

KindWhen decidedHow in C++
Compile-time (static)During compilationFunction overloading, operator overloading, templates
Run-time (dynamic)While the program runsVirtual functions called through a base-class pointer or reference

Complete example: all four together

C++
#include <iostream>
#include <string>
#include <vector>
#include <memory>

// Abstraction: an interface every account must provide
class Account {
protected:
    std::string holder;
    double balance;                       // Encapsulation: not public
public:
    Account(std::string h, double b) : holder(h), balance(b) {}
    virtual ~Account() = default;
    void deposit(double amt) { if (amt > 0) balance += amt; }
    virtual void monthEnd() = 0;          // pure virtual -> abstract class
    void show() const {
        std::cout << holder << ": Rs " << balance << "\n";
    }
};

// Inheritance
class Savings : public Account {
public:
    using Account::Account;
    void monthEnd() override { balance += balance * 0.01; }   // 1% interest
};

class Current : public Account {
public:
    using Account::Account;
    void monthEnd() override { balance -= 50; }               // service fee
};

int main() {
    std::vector<std::unique_ptr<Account>> accounts;
    accounts.push_back(std::make_unique<Savings>("Aman", 10000));
    accounts.push_back(std::make_unique<Current>("Priya", 10000));

    for (auto& a : accounts) {
        a->monthEnd();     // Polymorphism: right version chosen at run time
        a->show();
    }
    return 0;
}
Aman: Rs 10100 Priya: Rs 9950

The loop does not know which kind of account it holds; each object runs its own monthEnd().

Benefits of OOP

  • Modularity: each class is a self-contained unit that is easier to understand and test.
  • Reusability: inheritance and composition reuse tested code.
  • Data security: encapsulation prevents invalid changes to data.
  • Maintainability: changes inside a class do not break code that uses its public interface.
  • Real-world modelling: classes map naturally to things in the problem.

Procedural vs object-oriented

PointProcedural (C)Object-oriented (C++)
Program built fromFunctionsObjects (data + functions)
Data accessOften global, open to allPrivate, via member functions
ReuseCopy or call functionsInheritance and composition
ApproachTop-downBottom-up
Example languageCC++, Java, Python

See C++ vs C for more differences.

Other OOP terms you will meet

  • Constructor / destructor: special functions that run when an object is created / destroyed. See constructors.
  • Message passing: objects communicate by calling each other's member functions.
  • Dynamic binding: the function to run is decided at run time (virtual functions).
  • Composition: a class *has* objects of another class (a School has Students).

Common mistakes

  • Making every data member public, which defeats encapsulation.
  • Using inheritance where "has-a" (composition) fits better — a Car has an Engine, it is not an Engine.
  • Forgetting virtual on the base function, so the base version runs instead of the derived one.
  • Forgetting a virtual destructor in a base class that is deleted through a base pointer.
  • Confusing abstraction (hiding complexity) with encapsulation (hiding data).
🏋️ Practice

Model a library: an abstract class Item with a pure virtual lateFee(int days), and derived classes Book (Rs 2/day) and Magazine (Rs 1/day). Store both in a vector<unique_ptr<Item>> and print each item's fee for 5 late days.

Summary

  • OOP organises programs around objects that combine data and behaviour.
  • Class = blueprint, object = instance.
  • Encapsulation hides data; abstraction hides complexity.
  • Inheritance reuses and extends classes; polymorphism lets one interface have many forms.
  • C++ supports OOP but is not a pure OOP language.

Next: classes and objects → constructors → inheritance → polymorphism.

Frequently Asked Questions

What are the four pillars of OOP in C++?
The four pillars are encapsulation (bundling data with the functions that use it and hiding the details), abstraction (showing only what an object does, not how), inheritance (creating a new class from an existing one) and polymorphism (one interface, many forms — for example, the same function call behaving differently for different classes).
What is the difference between a class and an object?
A class is a blueprint that defines data members and member functions, for example Student. An object is a real instance created from that blueprint, such as Student s1;, which has its own values in memory. One class can create many objects.
What is the difference between encapsulation and abstraction?
Encapsulation is about how data is protected: keep data members private and allow access only through public functions. Abstraction is about what the user sees: expose a simple interface such as withdraw(amount) and hide the complex implementation behind it. Encapsulation is one of the tools used to achieve abstraction.
Is C++ a pure object-oriented language?
No. C++ supports OOP but also allows procedural code — you can write functions and variables outside any class, and main() itself is not a member of a class. That is why C++ is called a multi-paradigm (or partially object-oriented) language, unlike Java or Smalltalk-style designs.
← Back to C++ Tutorial
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

💻 Live Code Editor

This page's programs are ready here — run them, edit them, and learn. No installation needed.
Powered by OneCompiler. The code loads into the editor automatically — press Run to see the output. If the editor does not open, open it in a new tab.
Next topicClasses and Objects Your progress: 37 / 81 (46%) · Lesson 38 / 81 Continue →

How was this lesson?

Your feedback helps us make the content better.

Write a review or suggestion (optional)

After approval, your name and city may appear publicly with your review. Please do not write your email or phone number.

▶ CodingEasily on YouTube

Learn with video lessons in easy Hindi

Featured video: RDBMS Part 3 – Class XI Commerce IT

▶ Subscribe – it’s free