MODULE 6: OBJECT-ORIENTED PROGRAMMING (OOP) 6.1 C++ Classes and Objects (Instantiation, Access Specifiers, Member Functions)

Industrial reference manual: Comprehensive architectural breakdown of C++ Object-Oriented Programming principles—class blueprints, object instantiation, access specifiers (`private`, `public`, `protected`), member functions, encapsulation, and 10 production-aligned real-world implementations with outputs.

🏛️ Mastering Classes & Objects: The Foundation of C++ OOP

Object-Oriented Programming (OOP) models real-world entities using **Classes** and **Objects**. A **Class** serves as a user-defined blueprint or prototype that encapsulates data (attributes) and behavior (member functions). An **Object** is an instance of a class allocated in memory during runtime.

🔒 Access Specifiers

  • private: Members are accessible only within the class itself. Enforces encapsulation.
  • public: Members are accessible from outside the class (by any code in the program).
  • protected: Accessible within the class and its inherited derived classes.

⚙️ Core Concepts

  • Encapsulation: Bundling data and methods into a single unit while hiding internal state.
  • Member Functions: Operations defined inside or outside the class that act on object data.
  • Instantiation: Creating distinct object instances (`ClassName obj;`).

📊 End-to-End Class Blueprint, Instantiation & Method Execution Workflow Diagram

1. Class Definition

Define blueprint (`class BankAccount`) with private data and public methods.

→

2. Object Instantiation

Create object instance in memory (`BankAccount myAccount;`).

→

3. Encapsulation Barrier

Direct access to private attributes blocked by compiler access control.

↓

6. Console Rendering

Display updated object state via `std::cout` stream.

←

5. State Modification

Private member variables updated securely via public member functions.

←

4. Member Function Call

Invoke public methods (`myAccount.deposit(5000);`).

1. Bank Account Class (Encapsulation, Deposit, and Withdrawal)
Models a secure bank account with private balance encapsulation and public deposit/withdrawal methods.
C++ / Bank Account Class
#include 
#include 
#include 

using namespace std;

class BankAccount {
private:
    string accountNumber;
    double balance;

public:
    // Initialize account
    void setupAccount(string accNum, double initialDeposit) {
        accountNumber = accNum;
        balance = initialDeposit;
    }

    void deposit(double amount) {
        if (amount > 0) {
            balance += amount;
            cout << "[SUCCESS]: Deposited ₹" << amount << endl;
        }
    }

    void withdraw(double amount) {
        if (amount <= balance) {
            balance -= amount;
            cout << "[SUCCESS]: Withdrew ₹" << amount << endl;
        } else {
            cout << "[ERROR]: Insufficient funds!" << endl;
        }
    }

    void displayBalance() {
        cout << "Account [" << accountNumber << "] Balance: ₹" << fixed << setprecision(2) << balance << endl;
    }
};

int main() {
    cout << "--- Bank Account OOP Simulation ---" << endl;
    BankAccount myAccount;
    myAccount.setupAccount("SBIN0004829", 15000.00);
    
    myAccount.displayBalance();
    myAccount.deposit(5000.00);
    myAccount.withdraw(3000.00);
    myAccount.displayBalance();
    return 0;
}
--- Bank Account OOP Simulation --- Account [SBIN0004829] Balance: ₹15000.00 [SUCCESS]: Deposited ₹5000.00 [SUCCESS]: Withdrew ₹3000.00 Account [SBIN0004829] Balance: ₹17000.00
2. Employee Payroll Record Class
Manages employee salary data, bonus allocations, and gross compensation calculations inside a dedicated class.
C++ / Employee Payroll Class
#include 
#include 
#include 

using namespace std;

class Employee {
private:
    string empId;
    string name;
    double basicSalary;
    double allowance;

public:
    void setEmployeeData(string id, string empName, double basic, double allow) {
        empId = id;
        name = empName;
        basicSalary = basic;
        allowance = allow;
    }

    double calculateGrossSalary() {
        return basicSalary + allowance;
    }

    void printPayslip() {
        double gross = calculateGrossSalary();
        cout << "--- Payslip for " << name << " (" << empId << ") ---" << endl;
        cout << "Basic Salary : ₹" << fixed << setprecision(2) << basicSalary << endl;
        cout << "Allowances   : ₹" << allowance << endl;
        cout << "Gross Salary : ₹" << gross << endl;
    }
};

int main() {
    Employee emp1;
    emp1.setEmployeeData("EMP1001", "Aarav Sharma", 65000.00, 12000.00);
    emp1.printPayslip();
    return 0;
}
--- Payslip for Aarav Sharma (EMP1001) --- Basic Salary : ₹65000.00 Allowances : ₹12000.00 Gross Salary : ₹77000.00
3. E-Commerce Product Catalog Item Class
Encapsulates inventory stock levels and pricing rules for e-commerce catalog items.
C++ / Product Item Class
#include 
#include 
#include 

using namespace std;

class ProductItem {
private:
    string sku;
    string title;
    double price;
    int stockQty;

public:
    void setProduct(string s, string t, double p, int stock) {
        sku = s;
        title = t;
        price = p;
        stockQty = stock;
    }

    void applyDiscount(double percent) {
        price -= price * (percent / 100.0);
    }

    void displayDetails() {
        cout << "Product SKU  : " << sku << endl;
        cout << "Title        : " << title << endl;
        cout << "Price        : ₹" << fixed << setprecision(2) << price << endl;
        cout << "Stock Units  : " << stockQty << " available" << endl;
    }
};

int main() {
    cout << "--- E-Commerce Product Object ---" << endl;
    ProductItem item;
    item.setProduct("NIK-KEY-402", "Mechanical Wireless Keyboard", 4500.00, 25);
    item.applyDiscount(10.0); // 10% OFF
    item.displayDetails();
    return 0;
}
--- E-Commerce Product Object --- Product SKU : NIK-KEY-402 Title : Mechanical Wireless Keyboard Price : ₹4050.00 Stock Units : 25 available
4. Smart Home IoT Thermostat Class
Models a smart IoT thermostat with setter/getter validation for temperature control.
C++ / Smart Thermostat Class
#include 
#include 

using namespace std;

class SmartThermostat {
private:
    double targetTemperature;
    bool isHeatingActive;

public:
    void initialize(double defaultTemp) {
        targetTemperature = defaultTemp;
        isHeatingActive = false;
    }

    void setTemperature(double temp) {
        if (temp >= 16.0 && temp <= 30.0) {
            targetTemperature = temp;
            cout << "[SUCCESS]: Target temperature set to " << targetTemperature << "°C" << endl;
        } else {
            cout << "[WARNING]: Temperature out of safe range (16°C - 30°C)!" << endl;
        }
    }

    void toggleSystem(bool active) {
        isHeatingActive = active;
        cout << "Heating System State: " << (isHeatingActive ? "ON" : "OFF") << endl;
    }
};

int main() {
    cout << "--- IoT Thermostat Simulation ---" << endl;
    SmartThermostat thermostat;
    thermostat.initialize(22.0);
    thermostat.setTemperature(24.5);
    thermostat.toggleSystem(true);
    thermostat.setTemperature(35.0); // Invalid trigger
    return 0;
}
--- IoT Thermostat Simulation --- [SUCCESS]: Target temperature set to 24.5°C Heating System State: ON [WARNING]: Temperature out of safe range (16°C - 30°C)!
5. Rectangle Geometry Calculator Class
Encapsulates length and width attributes inside a geometry class to compute area and perimeter.
C++ / Rectangle Geometry Class
#include 
#include 

using namespace std;

class Rectangle {
private:
    double length;
    double width;

public:
    void setDimensions(double l, double w) {
        length = (l > 0) ? l : 1.0;
        width = (w > 0) ? w : 1.0;
    }

    double getArea() {
        return length * width;
    }

    double getPerimeter() {
        return 2.0 * (length + width);
    }
};

int main() {
    cout << "--- Rectangle Geometry Calculator ---" << endl;
    Rectangle rect;
    rect.setDimensions(15.5, 8.0);

    cout << "Area      : " << fixed << setprecision(2) << rect.getArea() << " sq.units" << endl;
    cout << "Perimeter : " << rect.getPerimeter() << " units" << endl;
    return 0;
}
--- Rectangle Geometry Calculator --- Area : 124.00 sq.units Perimeter : 47.00 units
6. User Authentication Profile Class
Models user login credentials, authentication checks, and active session status flags.
C++ / User Profile Class
#include 
#include 

using namespace std;

class UserProfile {
private:
    string username;
    string passwordHash;
    bool isLoggedIn;

public:
    void registerUser(string uname, string pass) {
        username = uname;
        passwordHash = pass;
        isLoggedIn = false;
    }

    bool login(string pass) {
        if (pass == passwordHash) {
            isLoggedIn = true;
            cout << "[AUTH]: User '" << username << "' logged in successfully." << endl;
            return true;
        }
        cout << "[AUTH]: Incorrect password for '" << username << "'." << endl;
        return false;
    }

    void logout() {
        isLoggedIn = false;
        cout << "[AUTH]: User logged out." << endl;
    }
};

int main() {
    cout << "--- User Profile Authentication ---" << endl;
    UserProfile user;
    user.registerUser("AaravSharma", "Secret#123");
    user.login("WrongPass");
    user.login("Secret#123");
    user.logout();
    return 0;
}
--- User Profile Authentication --- [AUTH]: Incorrect password for 'AaravSharma'. [AUTH]: User 'AaravSharma' logged in successfully. [AUTH]: User logged out.
7. Shopping Cart Item Manager Class
Manages cart item quantities and computes total pricing updates dynamically.
C++ / Shopping Cart Item Class
#include 
#include 
#include 

using namespace std;

class CartItem {
private:
    string itemName;
    double unitPrice;
    int quantity;

public:
    void addItem(string name, double price, int qty) {
        itemName = name;
        unitPrice = price;
        quantity = qty;
    }

    void updateQuantity(int newQty) {
        quantity = newQty;
    }

    double getTotalCost() {
        return unitPrice * quantity;
    }

    void displaySummary() {
        cout << itemName << " (Qty: " << quantity << ") | Total: ₹" << fixed << setprecision(2) << getTotalCost() << endl;
    }
};

int main() {
    cout << "--- Shopping Cart Item Manager ---" << endl;
    CartItem cart;
    cart.addItem("Wireless Mouse", 850.00, 2);
    cart.displaySummary();

    cart.updateQuantity(3); // Increase quantity
    cart.displaySummary();
    return 0;
}
--- Shopping Cart Item Manager --- Wireless Mouse (Qty: 2) | Total: ₹1700.00 Wireless Mouse (Qty: 3) | Total: ₹2550.00
8. Hospital Patient Record Management Class
Encapsulates patient vital signs and medical history logs inside a clinical object model.
C++ / Patient Record Class
#include 
#include 

using namespace std;

class PatientRecord {
private:
    string patientId;
    string fullName;
    int age;
    string bloodGroup;

public:
    void admitPatient(string id, string name, int patAge, string bg) {
        patientId = id;
        fullName = name;
        age = patAge;
        bloodGroup = bg;
    }

    void printPatientCard() {
        cout << "--- Hospital Patient ID Card ---" << endl;
        cout << "Patient ID : " << patientId << endl;
        cout << "Full Name  : " << fullName << endl;
        cout << "Age & BG   : " << age << " yrs | " << bloodGroup << endl;
    }
};

int main() {
    PatientRecord patient;
    patient.admitPatient("PAT-99821", "Priya Sharma", 28, "B+");
    patient.printPatientCard();
    return 0;
}
--- Hospital Patient ID Card --- Patient ID : PAT-99821 Full Name : Priya Sharma Age & BG : 28 yrs | B+
9. Vehicle Fleet Speedometer Class
Models vehicle speed limits, acceleration, and braking controls inside an automotive telemetry object.
C++ / Vehicle Speedometer Class
#include 

using namespace std;

class Speedometer {
private:
    double currentSpeedKmH;
    double maxSpeedLimit;

public:
    void initializeVehicle(double maxLimit) {
        currentSpeedKmH = 0.0;
        maxSpeedLimit = maxLimit;
    }

    void accelerate(double increment) {
        currentSpeedKmH += increment;
        if (currentSpeedKmH > maxSpeedLimit) {
            currentSpeedKmH = maxSpeedLimit;
            cout << "[WARNING]: Speed limit reached (" << maxSpeedLimit << " km/h)!" << endl;
        } else {
            cout << "Accelerated. Current Speed: " << currentSpeedKmH << " km/h" << endl;
        }
    }

    void brake(double decrement) {
        currentSpeedKmH -= decrement;
        if (currentSpeedKmH < 0) currentSpeedKmH = 0;
        cout << "Braked. Current Speed: " << currentSpeedKmH << " km/h" << endl;
    }
};

int main() {
    cout << "--- Vehicle Speedometer Simulation ---" << endl;
    Speedometer car;
    car.initializeVehicle(120.0);
    car.accelerate(45.0);
    car.accelerate(80.0); // Triggers limit warning
    car.brake(30.0);
    return 0;
}
--- Vehicle Speedometer Simulation --- Accelerated. Current Speed: 45 km/h [WARNING]: Speed limit reached (120 km/h)! Braked. Current Speed: 90 km/h
10. Library Book Catalog Item Class
Encapsulates book borrowing status, issue tracking, and return timestamps in a library catalog object.
C++ / Library Book Class
#include 
#include 

using namespace std;

class LibraryBook {
private:
    string isbn;
    string title;
    string author;
    bool isIssued;

public:
    void registerBook(string bookIsbn, string bookTitle, string bookAuthor) {
        isbn = bookIsbn;
        title = bookTitle;
        author = bookAuthor;
        isIssued = false;
    }

    void issueBook() {
        if (!isIssued) {
            isIssued = true;
            cout << "[LIBRARY]: Book '" << title << "' successfully issued." << endl;
        } else {
            cout << "[LIBRARY]: Book '" << title << "' is already checked out." << endl;
        }
    }

    void returnBook() {
        isIssued = false;
        cout << "[LIBRARY]: Book '" << title << "' returned to catalog." << endl;
    }
};

int main() {
    cout << "--- Library Book Catalog ---" << endl;
    LibraryBook book;
    book.registerBook("978-0131103627", "The C++ Programming Language", "Bjarne Stroustrup");
    
    book.issueBook();
    book.issueBook(); // Already issued warning
    book.returnBook();
    return 0;
}
--- Library Book Catalog --- [LIBRARY]: Book 'The C++ Programming Language' successfully issued. [LIBRARY]: Book 'The C++ Programming Language' is already checked out. [LIBRARY]: Book 'The C++ Programming Language' returned to catalog.