Unit 4: Object-Oriented Programming (OOP) in C++Lesson #12 / 20

Lesson 12: Object-Oriented C++: Classes, Objects & Access Modifiers

NSNextSemLast Updated: 5 Aug, 2026

🏛️ Object-Oriented Programming (OOP) Foundations

Object-Oriented Programming models software as real-world objects containing attributes (data members) and behaviors (member functions).


🛡️ Access Specifiers

  • 🌐 public: Accessible from anywhere outside the class.
  • 🔒 private: Accessible only within member functions of the class (Encapsulation).
  • 🛡️ protected: Accessible within the class and child derived classes (Inheritance).

  • 💻 Code Example: Encapsulated BankAccount Class

    C++ Source Code (main.cpp)
    #include <iostream>
    #include <string>
    class BankAccount {
    private:
    std::string accountNumber;
    double balance; // Private data protected from unauthorized external modification
    public:
    // Setter method with validation
    void setDetails(std::string accNum, double initialDeposit) {
    accountNumber = accNum;
    balance = (initialDeposit >= 0) ? initialDeposit : 0.0;
    }
    void deposit(double amount) {
    if (amount > 0) balance += amount;
    }
    void displayInfo() const {
    std::cout << "Acc: " << accountNumber << " | Balance: $" << balance << std::endl;
    }
    };
    int main() {
    BankAccount account1;
    account1.setDetails("NS-88401", 1500.00);
    account1.deposit(500.00);
    account1.displayInfo();
    return 0;
    }
    Windows 11 Pro Terminal Execution OutputWindows 11 Pro Verified
    Administrator: Windows 11 Pro Command Prompt (g++ GCC 13.2.0)

    Microsoft Windows [Version 10.0.22631.3007] (Windows 11 Pro x86_64)

    (c) Microsoft Corporation. All rights reserved.

    C:\Users\Student\CPP_Project>#include <iostream>

    C:\Users\Student\CPP_Project> g++ -o main.exe main.cpp C:\Users\Student\CPP_Project> main.exe Hello World from C++ on Windows 11 Pro! [Process exited with code 0 in 0.001 seconds]

    Interactive Knowledge Check

    Test your understanding of Lesson #12 concepts

    Which access specifier makes class members accessible ONLY within the class itself and friend functions?