Tutorials Logic, IN info@tutorialslogic.com

C++ OOP Basics Classes, Objects, Encapsulation: Notes, Examples & Interview Tips

C++ OOP Basics Classes, Objects, Encapsulation

Object-oriented programming in C++ organizes code around classes and objects.

A class is a blueprint; an object is a real instance created from that blueprint.

The four core OOP ideas are encapsulation, abstraction, inheritance, and polymorphism.

What is OOP in C++?

Object-oriented programming, or OOP, is a programming style where we model real-world or logical entities as objects. Each object can store data and perform actions through functions.

C++ supports procedural programming like C, but it also supports object-oriented programming through classes, objects, constructors, access specifiers, inheritance, virtual functions, and more. OOP helps large programs stay organized because related data and behavior live together.

  • Use OOP when data and behavior naturally belong together.
  • A class defines the structure and behavior.
  • An object is a runtime instance of a class.
  • Methods are functions that belong to a class.
  • Data members are variables that belong to a class.

Class vs Object

Beginners often confuse class and object. The class is only the design. The object is the actual thing created from that design.

Concept Meaning Example
Class Blueprint or template class Student
Object Instance created from a class Student s1;
Data member Variable inside a class name, rollNo, marks
Member function Function inside a class display(), calculateGrade()

Four Pillars of OOP

The foundation of OOP is usually explained with four major pillars. These ideas help you design reusable and maintainable programs.

Pillar Meaning C++ Feature
Encapsulation Bind data and methods together and protect internal state class, private, public, getters, setters
Abstraction Show essential behavior and hide implementation details public methods, abstract classes
Inheritance Create a new class from an existing class class Child : public Parent
Polymorphism Same interface, different behavior function overloading, overriding, virtual functions

Access Specifiers in C++

Access specifiers decide where class members can be used. They are central to encapsulation.

Specifier Access Common Use
private Only inside the same class Protect data members
public Accessible from outside the class Expose useful methods
protected Inside class and derived classes Allow controlled inheritance access

Constructor and Destructor

A constructor runs automatically when an object is created. It is commonly used to initialize data members. A destructor runs automatically when an object is destroyed. It is commonly used for cleanup.

  • Constructor name is the same as the class name.
  • Constructor has no return type.
  • Destructor name is the class name with ~ before it.
  • Destructor also has no return type.
  • A class can have multiple constructors using constructor overloading.

Complete C++ OOP Example

This example shows class, object, private data, constructor, member functions, encapsulation, inheritance, and runtime polymorphism in one simple program.

C++ OOP Basics Example

C++ OOP Basics Example
#include <iostream>
#include <string>
using namespace std;

class Account {
private:
    string owner;
    double balance;

public:
    Account(string ownerName, double openingBalance) {
        owner = ownerName;
        balance = openingBalance;
    }

    string getOwner() const {
        return owner;
    }

    double getBalance() const {
        return balance;
    }

    void deposit(double amount) {
        if (amount > 0) {
            balance += amount;
        }
    }

    bool withdraw(double amount) {
        if (amount > 0 && amount <= balance) {
            balance -= amount;
            return true;
        }
        return false;
    }

    virtual void printAccountType() const {
        cout << "General account" << endl;
    }

    virtual ~Account() {}
};

class SavingsAccount : public Account {
private:
    double interestRate;

public:
    SavingsAccount(string ownerName, double openingBalance, double rate)
        : Account(ownerName, openingBalance), interestRate(rate) {}

    void printAccountType() const override {
        cout << "Savings account with interest rate "
             << interestRate << "%" << endl;
    }
};

int main() {
    SavingsAccount acc("Asha", 5000, 4.5);

    acc.deposit(1000);
    acc.withdraw(750);

    cout << "Owner: " << acc.getOwner() << endl;
    cout << "Balance: " << acc.getBalance() << endl;

    Account* basePtr = &acc;
    basePtr->printAccountType(); // runtime polymorphism

    return 0;
}

Program Output

Program Output
Owner: Asha
Balance: 5250
Savings account with interest rate 4.5%

How the Example Uses OOP

OOP Concept Where It Appears Why It Matters
Class Account and SavingsAccount Groups related data and behavior
Object SavingsAccount acc Creates a usable account instance
Encapsulation owner and balance are private Protects data from direct external modification
Inheritance SavingsAccount inherits Account Reuses common account behavior
Polymorphism virtual printAccountType() Calls derived behavior through base pointer
Abstraction deposit(), withdraw(), getBalance() User calls simple methods without knowing internals

When Should You Use OOP?

OOP is useful when your program has entities with state and behavior. It is not required for every small program, but it becomes powerful as programs grow.

  • Use OOP for models like Student, Employee, Product, Account, Order, Shape, Vehicle, and User.
  • Use OOP when behavior belongs naturally with data.
  • Use OOP when you need reuse through inheritance or composition.
  • Avoid forcing OOP when a simple function is clearer.

OOP Basics vs Classes and Objects

This page gives the big picture of OOP. The Classes and Objects page focuses more deeply on class syntax, object creation, constructors, destructors, getters, setters, and member functions.

  • Start here if you want to understand the OOP model.
  • Go to Classes and Objects when you want more syntax-level practice.
  • Study Inheritance and Polymorphism after this page.
  • Study Encapsulation and Abstraction to improve design clarity.
Key Takeaways
  • I can explain class and object with one example.
  • I know why private data members are used.
  • I can identify encapsulation, inheritance, abstraction, and polymorphism in code.
  • I can write a small class with constructor and member functions.
  • I understand why virtual functions are needed for runtime polymorphism.
Common Mistakes to Avoid
WRONG Make every data member public for easy access.
RIGHT Keep data private and expose controlled public methods.
Encapsulation protects object state and prevents invalid changes.
WRONG Use inheritance only to avoid writing repeated code.
RIGHT Use inheritance only when the relationship is truly is-a.
For simple reuse, composition is often cleaner than inheritance.
WRONG Expect overriding to work through a base pointer without virtual.
RIGHT Mark base methods virtual when runtime polymorphism is required.
Without virtual, C++ uses static binding for base class pointers.

Practice Tasks

  • Create a Student class with name, roll number, marks, and a display method.
  • Create a Product class with private price and a setter that rejects negative values.
  • Create a Shape base class and Circle derived class with a virtual area method.
  • Rewrite a procedural bank account program using classes and objects.
  • Explain the Account example line by line without looking at the notes.

Frequently Asked Questions

C++ supports object-oriented programming, but it is multi-paradigm. You can write procedural, object-oriented, generic, and functional-style C++.

A class is a blueprint. An object is an actual instance created from that blueprint.

Private data members prevent outside code from putting an object into an invalid state. Public methods can validate changes.

Study classes and objects, constructors, inheritance, polymorphism, encapsulation, abstraction, and then smart pointers for safer object management.

Ready to Level Up Your Skills?

Explore 500+ free tutorials across 20+ languages and frameworks.