🏛️ 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);`).
#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;
}
#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;
}
#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;
}
#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;
}
#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;
}
#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;
}
#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;
}
#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;
}
#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;
}
#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;
}