PROGRAM 1- Employee Class
#include <iostream>
#include <string>
using namespace std;
class Employee {
private:
string name;
int id;
string designation;
double salary;
public:
// Constructor
Employee(string empName, int empId, string empDesignation,
double empSalary) {
name = empName;
id = empId;
designation = empDesignation;
salary = empSalary;
}
// Method to display employee details
void displayDetails() {
cout << "Employee ID: " << id << endl;
cout << "Name: " << name << endl;
cout << "Designation: " << designation << endl;
cout << "Salary: $" << salary << endl;
}
// Method to apply salary hike based on performance
void applySalaryHike(string performance) {
double hikePercentage = 0.0;
if (performance == "excellent") {
hikePercentage = 10.0;
} else if (performance == "good") {
hikePercentage = 5.0;
} else if (performance == "average") {
hikePercentage = 3.0;
} else {
cout << "Invalid performance rating! No salary hike applied." <<
endl;
return;
}
double hikeAmount = (salary * hikePercentage) / 100.0;
salary += hikeAmount;
cout << "Salary hiked by " << hikePercentage << "% ($" <<
hikeAmount << ")" << endl;
}
};
int main() {
// Creating an Employee object
Employee emp("John Doe", 101, "Software Engineer", 50000);
// Display initial details
cout << "Before Salary Hike:\n";
emp.displayDetails();
// Apply salary hike based on performance
cout << "\nApplying Salary Hike for Performance: Excellent\n";
emp.applySalaryHike("excellent");
// Display updated details
cout << "\nAfter Salary Hike:\n";
emp.displayDetails();
return 0;
}
OUTPUT
Before Salary Hike:
Employee ID: 101
Name: John Doe
Designation: Software Engineer
Salary: $50000
Applying Salary Hike for Performance: Excellent
Salary hiked by 10% ($5000)
After Salary Hike:
Employee ID: 101
Name: John Doe
Designation: Software Engineer
Salary: $55000
PROGRAM 2- Student Class
#include <iostream>
#include <string>
using namespace std;
class Student {
private:
string name;
int rollNumber;
double marks;
char grade;
public:
// Constructor
Student(string stuName, int stuRollNumber, double stuMarks) {
name = stuName;
rollNumber = stuRollNumber;
marks = stuMarks;
grade = calculateGrade(); // Calculate grade upon initialization
}
// Method to calculate grade based on marks
char calculateGrade() {
if (marks >= 90)
return 'A';
else if (marks >= 80)
return 'B';
else if (marks >= 70)
return 'C';
else if (marks >= 60)
return 'D';
else
return 'F';
}
// Method to display student details
void displayDetails() {
cout << "Student Roll Number: " << rollNumber << endl;
cout << "Name: " << name << endl;
cout << "Marks: " << marks << endl;
cout << "Grade: " << grade << endl;
}
// Method to update marks and recalculate grade
void updateMarks(double newMarks) {
marks = newMarks;
grade = calculateGrade();
cout << "Marks updated successfully!\n";
}
};
int main() {
// Creating a Student object
Student stu("Alice Johnson", 101, 85);
// Display initial details
cout << "Before Marks Update:\n";
stu.displayDetails();
// Update marks
cout << "\nUpdating Marks...\n";
stu.updateMarks(92);
// Display updated details
cout << "\nAfter Marks Update:\n";
stu.displayDetails();
return 0;
}
OUTPUT
Before Marks Update:
Student Roll Number: 101
Name: Alice Johnson
Marks: 85
Grade: B
Updating Marks...
Marks updated successfully!
After Marks Update:
Student Roll Number: 101
Name: Alice Johnson
Marks: 92
Grade: A
PROGRAM 3- Book Class
#include <iostream>
#include <string>
using namespace std;
class Book {
private:
string title;
string author;
string ISBN;
double price;
int stock;
public:
// Constructor to initialize book details
Book(string bookTitle, string bookAuthor, string bookISBN, double
bookPrice, int bookStock) {
title = bookTitle;
author = bookAuthor;
ISBN = bookISBN;
price = bookPrice;
stock = bookStock;
}
// Method to display book details
void displayDetails() {
cout << "Book Title: " << title << endl;
cout << "Author: " << author << endl;
cout << "ISBN: " << ISBN << endl;
cout << "Price: $" << price << endl;
cout << "Stock Available: " << stock << " copies\n";
}
// Method to purchase a book
void purchaseBook(int quantity) {
if (quantity > stock) {
cout << "Sorry! Not enough stock available.\n";
} else {
stock -= quantity;
cout << quantity << " copies of '" << title << "' purchased
successfully.\n";
}
}
// Method to restock books
void addStock(int quantity) {
stock += quantity;
cout << quantity << " copies of '" << title << "' added to stock.\n";
}
};
int main() {
// Creating a Book object
Book book1("The Great Gatsby", "F. Scott Fitzgerald", "978-
0743273565", 10.99, 50);
// Display book details
cout << "Book Details:\n";
book1.displayDetails();
// Purchasing books
cout << "\nAttempting to purchase 5 copies...\n";
book1.purchaseBook(5);
// Display updated details
cout << "\nAfter Purchase:\n";
book1.displayDetails();
// Adding stock
cout << "\nRestocking 10 copies...\n";
book1.addStock(10);
// Display updated details
cout << "\nAfter Restocking:\n";
book1.displayDetails();
return 0;
}
OUTPUT
Book Details:
Book Title: The Great Gatsby
Author: F. Scott Fitzgerald
ISBN: 978-0743273565
Price: $10.99
Stock Available: 50 copies
Attempting to purchase 5 copies...
5 copies of 'The Great Gatsby' purchased successfully.
After Purchase:
Book Title: The Great Gatsby
Author: F. Scott Fitzgerald
ISBN: 978-0743273565
Price: $10.99
Stock Available: 45 copies
Restocking 10 copies...
10 copies of 'The Great Gatsby' added to stock.
After Restocking:
Book Title: The Great Gatsby
Author: F. Scott Fitzgerald
ISBN: 978-0743273565
Price: $10.99
Stock Available: 55 copies
PROGRAM 4 – Static members accessed by static functions- Student
class
#include <iostream>
using namespace std;
class Student {
private:
string name;
int rollNumber;
public:
static int studentCount; // Static member variable
// Constructor
Student(string stuName, int stuRollNumber) {
name = stuName;
rollNumber = stuRollNumber;
studentCount++; // Increment student count when an object is
created
}
// Method to display student details
void displayDetails() {
cout << "Student Name: " << name << endl;
cout << "Roll Number: " << rollNumber << endl;
}
// Static method to display total student count
static void displayStudentCount() {
cout << "Total Students: " << studentCount << endl;
}
};
// Define and initialize the static member variable
int Student::studentCount = 0;
int main() {
// Display initial student count
Student::displayStudentCount();
// Creating student objects
Student s1("Alice", 101);
Student s2("Bob", 102);
Student s3("Charlie", 103);
// Display student details
cout << "\nStudent Details:\n";
s1.displayDetails();
s2.displayDetails();
s3.displayDetails();
// Display updated student count
cout << "\nAfter Adding Students:\n";
Student::displayStudentCount();
return 0;
}
OUTPUT
Total Students: 0
Student Details:
Student Name: Alice
Roll Number: 101
Student Name: Bob
Roll Number: 102
Student Name: Charlie
Roll Number: 103
After Adding Students:
Total Students: 3
PROGRAM 5 – Static members accessed by static functions-
BankAccount
#include <iostream>
using namespace std;
class BankAccount {
private:
string accountHolder;
int accountNumber;
double balance;
public:
static int totalAccounts; // Static member variable to count accounts
// Constructor
BankAccount(string name, int accNum, double initialBalance) {
accountHolder = name;
accountNumber = accNum;
balance = initialBalance;
totalAccounts++; // Increment the count of accounts
}
// Method to display account details
void displayAccount() {
cout << "Account Holder: " << accountHolder << endl;
cout << "Account Number: " << accountNumber << endl;
cout << "Balance: $" << balance << endl;
}
// Static method to display total number of accounts
static void displayTotalAccounts() {
cout << "Total Bank Accounts: " << totalAccounts << endl;
}
};
// Define and initialize the static member variable
int BankAccount::totalAccounts = 0;
int main() {
// Display initial total accounts
BankAccount::displayTotalAccounts();
// Creating bank account objects
BankAccount acc1("Alice", 1001, 5000.00);
BankAccount acc2("Bob", 1002, 3000.50);
BankAccount acc3("Charlie", 1003, 7000.75);
// Display account details
cout << "\nAccount Details:\n";
acc1.displayAccount();
acc2.displayAccount();
acc3.displayAccount();
// Display updated total accounts
cout << "\nAfter Creating Accounts:\n";
BankAccount::displayTotalAccounts();
return 0;
}
OUTPUT
Total Bank Accounts: 0
Account Details:
Account Holder: Alice
Account Number: 1001
Balance: $5000
Account Holder: Bob
Account Number: 1002
Balance: $3000.5
Account Holder: Charlie
Account Number: 1003
Balance: $7000.75
After Creating Accounts:
Total Bank Accounts: 3
PROGRAM 6 – Static members accessed by non-static functions
#include <iostream>
using namespace std;
class Counter {
private:
static int count; // Static variable to track the count of objects
public:
// Constructor
Counter() {
count++; // Accessing static variable inside a non-static method
}
// Non-static method accessing static variable
void showCount() {
cout << "Current Count: " << count << endl; // Accessing static
variable
}
// Static method to access static variable
static void displayCount() {
cout << "Total Count (from static method): " << count << endl;
}
};
// Define and initialize static member variable
int Counter::count = 0;
int main() {
Counter c1, c2, c3;
// Accessing static variable from a non-static method
c1.showCount();
c2.showCount();
c3.showCount();
// Accessing static variable from a static method
Counter::displayCount();
return 0;
}
OUTPUT
Current Count: 3
Current Count: 3
Current Count: 3
Total Count (from static method): 3
#include <iostream>
using namespace std;
Practice Programs
class test
{
int score;
static int count;
public:
void getscore(int a)
{
score=a;
count++;
}
static void display()
{
cout<<count<<endl;
}
void displayscore()
{
cout<<score<<endl;
cout<<count<<endl;
}
};
int test::count=0;
int main()
{
test::display();
test t1,t2,t3;
t1.getscore(100);
t1.displayscore();
t2.getscore(200);
t2.displayscore();
t3.getscore(300);
t3.displayscore();
test::display();
return 0;
}
Output:
0
100
1
200
2
300
3
3
PROGRAM 7 – Array of Objects
#include <iostream>
#include <string>
using namespace std;
class Employee {
public:
int empID;
string name;
double salary;
void getDetails() {
cout << "Enter Employee ID: ";
cin >> empID;
cin.ignore(); // Ignore the newline character left in the buffer
cout << "Enter Employee Name: ";
getline(cin, name);
cout << "Enter Employee Salary: ";
cin >> salary;
}
void displayDetails() {
cout << "\nEmployee ID: " << empID << endl;
cout << "Name: " << name << endl;
cout << "Salary: " << salary << endl;
}
};
int main() {
int num;
cout << "Enter number of employees: ";
cin >> num;
Employee empArr[num]; // Array of Employee objects
for (int i = 0; i < num; i++) {
cout << "\nEnter details for Employee " << i + 1 << ":" << endl;
empArr[i].getDetails();
}
cout << "\nEmployee Details:\n";
for (int i = 0; i < num; i++) {
empArr[i].displayDetails();
}
return 0;
}
Output:
Enter number of employees: 3
Enter details for Employee 1:
Enter Employee ID: 12
Enter Employee Name: Kavya
Enter Employee Salary: 100000
Enter details for Employee 2:
Enter Employee ID: 13
Enter Employee Name: Suma
Enter Employee Salary: 20000
Enter details for Employee 3:
Enter Employee ID: 3
Enter Employee Name: uma
Enter Employee Salary: 1000
Employee Details:
Employee ID: 12
Name: Kavya
Salary: 100000
Employee ID: 13
Name: Suma
Salary: 20000
Employee ID: 3
Name: uma
Salary: 1000
PROGRAM 7 –Objects as arguments to the function
#include <iostream>
#include <string>
using namespace std;
class Employee {
public:
int empID;
string name;
double salary;
// Constructor to initialize employee details
Employee(int id, string empName, double sal) {
empID = id;
name = empName;
salary = sal;
}
// Function to display details
void displayDetails() {
cout << "Employee ID: " << empID << endl;
cout << "Name: " << name << endl;
cout << "Salary: " << salary << endl;
}
// Function to compare salary of two employees
void compareSalary(Employee e) {
if (salary > e.salary)
cout << name << " has a higher salary than " << e.name << ".\n";
else if (salary < e.salary)
cout << e.name << " has a higher salary than " << name << ".\n";
else
cout << name << " and " << e.name << " have the same salary.\
n";
}
};
int main() {
// Creating Employee objects
Employee emp1(101, "Alice", 50000);
Employee emp2(102, "Bob", 60000);
// Display details of both employees
cout << "Employee 1 Details:\n";
emp1.displayDetails();
cout << "\nEmployee 2 Details:\n";
emp2.displayDetails();
// Compare salaries
cout << "\nSalary Comparison:\n";
emp1.compareSalary(emp2);
return 0;
}
Output:
Employee 1 Details:
Employee ID: 101
Name: Alice
Salary: 50000
Employee 2 Details:
Employee ID: 102
Name: Bob
Salary: 60000
Salary Comparison:
Bob has a higher salary than Alice.
PROGRAM 8–Objects as arguments to the function
#include <iostream>
#include <string>
using namespace std;
class Employee {
public:
int empID;
string name;
double salary;
// Constructor to initialize employee details
Employee(int id, string empName, double sal) {
empID = id;
name = empName;
salary = sal;
}
// Function to display details
void displayDetails() {
cout << "Employee ID: " << empID << endl;
cout << "Name: " << name << endl;
cout << "Salary: " << salary << endl;
}
// Function to compare salary of two employees
void compareSalary(Employee e1,Employee e2 ) {
if (e1.salary > e2.salary)
cout << e1.name << " has a higher salary than " << e2.name <<
".\n";
else if (e1.salary < e2.salary)
cout << e2.name << " has a higher salary than " << e1.name <<
".\n";
else
cout << e1.name << " and " << e2.name << " have the same
salary.\n";
}
};
int main() {
// Creating Employee objects
Employee emp1(101, "Alice", 6000);
Employee emp2(102, "Bob", 6000);
// Display details of both employees
cout << "Employee 1 Details:\n";
emp1.displayDetails();
cout << "\nEmployee 2 Details:\n";
emp2.displayDetails();
// Compare salaries
cout << "\nSalary Comparison:\n";
emp1.compareSalary(emp1, emp2);
return 0;
}
Output:
Employee 1 Details:
Employee ID: 101
Name: Alice
Salary: 6000
Employee 2 Details:
Employee ID: 102
Name: Bob
Salary: 6000
Salary Comparison:
Alice and Bob have the same salary.
PROGRAM 9–Returning Objects as arguments
#include <iostream>
using namespace std;
class Employee {
public:
int empID;
string name;
double salary;
// Default constructor
Employee() {
empID = 0;
name = "";
salary = 0.0;
}
// Parameterized constructor
Employee(int id, string empName, double sal) {
empID = id;
name = empName;
salary = sal;
}
// Function to display employee details
void displayDetails() {
cout << "Employee ID: " << empID << endl;
cout << "Name: " << name << endl;
cout << "Salary: " << salary << endl;
}
// Function that returns an Employee object
Employee updateSalary(double increment) {
Employee updated(empID, name, salary + increment);
return updated;
}
};
int main() {
// Creating an Employee object
Employee emp1(101, "Alice", 50000);
cout << "Original Employee Details:\n";
emp1.displayDetails();
// Updating salary and getting a new Employee object
Employee emp2 = emp1.updateSalary(5000);
cout << "\nUpdated Employee Details:\n";
emp2.displayDetails();
return 0;
}
Output:
Original Employee Details:
Employee ID: 101
Name: Alice
Salary: 50000
Updated Employee Details:
Employee ID: 101
Name: Alice
Salary: 55000
OR
#include <iostream>
using namespace std;
class Employee {
public:
int empID;
string name;
double salary;
void getdetails(int id, string empName, double sal)
{
empID = id;
name = empName;
salary = sal;
// Function to display employee details
void displayDetails() {
cout << "Employee ID: " << empID << endl;
cout << "Name: " << name << endl;
cout << "Salary: " << salary << endl;
}
// Function that returns an Employee object
Employee updateSalary(double increment) {
Employee updated;
updated.getdetails(empID, name, salary + increment);
return updated;
}
};
int main() {
// Creating an Employee object
Employee emp1;
int id;
string empName;
double sal, increment;
cout<<"Enter Employee ID:";
cin>>id;
cout<<"Enter Employee name:";
cin>>empName;
cout<<"Enter Employee salary:";
cin>>sal;
emp1.getdetails(id,empName,sal);
cout << "Original Employee Details:\n";
emp1.displayDetails();
cout<<"Enter Employee Increment:";
cin>>increment;
// Updating salary and getting a new Employee object
Employee emp2=emp1.updateSalary(increment);
cout << "\nUpdated Employee Details:\n";
emp2.displayDetails();
return 0;
}
PROGRAM 10–BankAccount Class to demonstrate Default and
Parameterized Constructor
#include <iostream>
using namespace std;
class BankAccount {
private:
int accountNumber;
double balance;
public:
// Default Constructor
BankAccount() {
accountNumber = 0;
balance = 0.0;
}
// Parameterized Constructor
BankAccount(int accNum, double initialBalance) {
accountNumber = accNum;
balance = initialBalance;
}
// Function to deposit money
void deposit(double amount) {
if (amount > 0) {
balance += amount;
cout << "Deposited: $" << amount << " Successfully!\n";
} else {
cout << "Invalid deposit amount!\n";
}
}
// Function to withdraw money
void withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
cout << "Withdrawn: $" << amount << " Successfully!\n";
} else {
cout << "Insufficient balance or invalid amount!\n";
}
}
// Function to retrieve current balance
double getBalance() {
return balance;
}
// Function to display account details
void display() {
cout << "\nAccount Number: " << accountNumber << endl;
cout << "Current Balance: $" << balance << endl;
}
};
int main() {
int accNum;
double initialBalance, amount;
char choice;
// Taking user input for account details
cout << "Enter Account Number: ";
cin >> accNum;
cout << "Enter Initial Balance: ";
cin >> initialBalance;
// Creating a bank account object
BankAccount myAccount(accNum, initialBalance);
do {
cout << "\n*** Bank Account Menu ***\n";
cout << "1. Deposit\n2. Withdraw\n3. Check Balance\n4. Display
Details\n5. Exit\n";
cout << "Enter your choice: ";
cin >> choice;
switch (choice) {
case '1':
cout << "Enter amount to deposit: ";
cin >> amount;
myAccount.deposit(amount);
break;
case '2':
cout << "Enter amount to withdraw: ";
cin >> amount;
myAccount.withdraw(amount);
break;
case '3':
cout << "Current Balance: $" << myAccount.getBalance() <<
endl;
break;
case '4':
myAccount.display();
break;
case '5':
cout << "Exiting... Thank you!\n";
break;
default:
cout << "Invalid choice! Try again.\n";
}
} while (choice != '5');
return 0;
}
Output:
Enter Account Number: 125
Enter Initial Balance: 5000
*** Bank Account Menu ***
1. Deposit
2. Withdraw
3. Check Balance
4. Display Details
5. Exit
Enter your choice: 1
Enter amount to deposit: 6000
Deposited: $6000 Successfully!
*** Bank Account Menu ***
1. Deposit
2. Withdraw
3. Check Balance
4. Display Details
5. Exit
Enter your choice: 3
Current Balance: $11000
*** Bank Account Menu ***
1. Deposit
2. Withdraw
3. Check Balance
4. Display Details
5. Exit
Enter your choice: 4
Account Number: 125
Current Balance: $11000
*** Bank Account Menu ***
1. Deposit
2. Withdraw
3. Check Balance
4. Display Details
5. Exit
Enter your choice: 2
Enter amount to withdraw: 2000
Withdrawn: $2000 Successfully!
*** Bank Account Menu ***
1. Deposit
2. Withdraw
3. Check Balance
4. Display Details
5. Exit
Enter your choice: 3
Current Balance: $9000
*** Bank Account Menu ***
1. Deposit
2. Withdraw
3. Check Balance
4. Display Details
5. Exit
Enter your choice: 5
Exiting... Thank you!
PROGRAM 11 –Default Constructor and Destructor
#include <iostream>
using namespace std;
class Demo {
public:
// Default Constructor
Demo() {
cout << "Constructor called for object " << this << endl;
}
// Destructor
~Demo() {
cout << "Destructor called for object " << this << endl;
}
};
int main() {
cout << "Creating first object obj1...\n";
Demo obj1; // First object
{
cout << "\nCreating second object obj2 inside a block...\n";
Demo obj2; // Second object (inside a block)
cout << "Exiting the block...\n";
} // obj2 goes out of scope and its destructor is called
cout << "\nCreating third object obj3...\n";
Demo obj3; // Third object
cout << "End of main function...\n";
return 0; // obj1 and obj3 get destroyed automatically when main
ends
}
Output:
Creating first object obj1...
Constructor called for object 0x7ffcf62d1d46
Creating second object obj2 inside a block...
Constructor called for object 0x7ffcf62d1d47
Exiting the block...
Destructor called for object 0x7ffcf62d1d47
Creating third object obj3...
Constructor called for object 0x7ffcf62d1d47
End of main function...
Destructor called for object 0x7ffcf62d1d47
Destructor called for object 0x7ffcf62d1d46
OR
#include <iostream>
using namespace std;
int c=0;
class Demo {
public:
// Default Constructor
Demo() {
cout << "Constructor called for object " << ++c << endl;
}
// Destructor
~Demo() {
cout << "Destructor called for object " << c-- << endl;
}
};
int main() {
cout << "Creating first object obj1...\n";
Demo obj1; // First object
{
cout << "\nCreating second object obj2 inside a block...\n";
Demo obj2; // Second object (inside a block)
cout << "Exiting the block...\n";
} // obj2 goes out of scope and its destructor is called
cout << "\nCreating third object obj3...\n";
Demo obj3; // Third object
cout << "End of main function...\n";
return 0; // obj1 and obj3 get destroyed automatically when main
ends
}
PROGRAM 12–Copy Constructor
#include <iostream>
using namespace std;
class Demo {
private:
int id;
double value;
public:
// Parameterized Constructor
Demo(int i, double v) {
id = i;
value = v;
cout << "Constructor called for Object " << id << endl;
}
// Copy Constructor
Demo( Demo &obj) {
id = obj.id;
value = obj.value;
cout << "Copy Constructor called: Object " << id << " copied.\n";
}
// Display function
void display() {
cout << "Object ID: " << id << ", Value: " << value << endl;
}
};
int main() {
cout << "Creating obj1...\n";
Demo obj1(101, 45.6); // Calls parameterized constructor
cout << "\nCreating obj2 using copy constructor...\n";
//Demo obj2 = obj1; // Calls the copy constructor
Demo obj2(obj1);
cout << "\nDisplaying obj1:\n";
obj1.display();
cout << "\nDisplaying obj2 (Copy of obj1):\n";
obj2.display();
return 0;
}
Output:
Creating obj1...
Constructor called for Object 101
Creating obj2 using copy constructor...
Copy Constructor called: Object 101 copied.
Displaying obj1:
Object ID: 101, Value: 45.6
Displaying obj2 (Copy of obj1):
Object ID: 101, Value: 45.6
PROGRAM 14– Overloading Binary Operators (+, -, *, /)
#include <iostream>
using namespace std;
class Complex {
public:
int real, imag;
Complex(int r = 0, int i = 0) : real(r), imag(i) {}
// Overloading + operator
Complex operator+(const Complex& obj) {
return Complex(real + obj.real, imag + obj.imag);
}
void display() {
cout << real << " + " << imag << "i" << endl;
}
};
int main() {
Complex c1(3, 4), c2(1, 2);
Complex c3 = c1 + c2; // Calls overloaded + operator
c3.display(); // Output: 4 + 6i
return 0;
}
Output: 4 + 6i
PROGRAM 14 – Overloading Unary Operators (++, --, -,!)
#include <iostream>
using namespace std;
class Count {
private:
int value;
public:
Count(int v) : value(v) {}
// Overloading ++ operator
void operator++() {
++value;
}
void display() {
cout << "Value: " << value << endl;
}
};
int main() {
Count c(5);
++c; // Calls overloaded ++ operator
c.display(); // Output: Value: 6
return 0;
}
Output: Value: 6
Overloading Unary Operators -
#include <iostream>
using namespace std;
class Number {
public:
int value; // Public data member
// Overloading unary - operator
Number operator-() {
Number temp;
temp.value = -value;
return temp;
}
// Display function
void display() {
cout << "Value: " << value << endl;
}
};
int main() {
Number num1;
num1.value = 10; // Assigning value manually
cout << "Before applying unary - operator:" << endl;
num1.display();
// Applying overloaded unary - operator
Number num2 = -num1;
cout << "After applying unary - operator:" << endl;
num2.display();
return 0;
}
Output: Before applying unary - operator:
Value: 10
After applying unary - operator:
Value: -10
PROGRAM 15 – Overloading the << and >> Operators
#include <iostream>
using namespace std;
class Point {
public:
int x, y;
// Constructor with default values
Point(int a = 0, int b = 0) : x(a), y(b) {}
// Overloading << operator as a member function
void display(ostream& out) const {
out << "(" << x << ", " << y << ")";
}
// Overloading >> operator as a member function
void input(istream& in) {
in >> x >> y;
}
};
int main() {
Point p1;
cout << "Enter x and y coordinates: ";
p1.input(cin); // Using member function for input
cout << "Point: ";
p1.display(cout); // Using member function for output
cout << endl;
return 0;
}
Output: Enter x and y coordinates: 10 5
Point: (10, 5)
PROGRAM 16 –Friend Function
#include <iostream>
using namespace std;
class Sample {
private:
int data;
public:
Sample(int val) // Constructor to initialize data
{
data=val;
}
// Declare the friend function
friend void displayData(const Sample& obj);
};
// Definition of the friend function
void displayData(const Sample& obj) {
cout << "The value of data is: " << obj.data << endl;
}
int main() {
Sample obj(42); // Create an object of Sample with
value 42
displayData(obj); // Call the friend function
return 0;
}
The value of data is: 42
PROGRAM 17 –Operator overloading using Friend
#include <iostream>
using namespace std;
class Complex {
private:
int real, imag;
public:
Complex(int r = 0, int i = 0) {
real = r;
imag = i;
}
// Friend function to overload '+' operator
friend Complex operator+(const Complex& c1, const Complex& c2);
// Friend function to overload '-' operator
friend Complex operator-(const Complex& c1, const Complex& c2);
void print() {
cout << real << " + i" << imag << '\n';
}
};
// Overloading '+' using a friend function
Complex operator+(const Complex& c1, const Complex& c2) {
Complex res;
res.real = c1.real + c2.real;
res.imag = c1.imag + c2.imag;
return res;
}
// Overloading '-' using a friend function
Complex operator-(const Complex& c1, const Complex& c2) {
Complex res;
res.real = c1.real - c2.real;
res.imag = c1.imag - c2.imag;
return res;
}
int main() {
Complex c1(10, 5), c2(2, 4);
Complex c3 = c1 + c2; // Calls friend function for '+'
Complex c4 = c1 - c2; // Calls friend function for '-'
c3.print();
c4.print();
return 0;
}
Output:
12 + i9
8 + i1
PROGRAM 18 –Function overloading
#include <iostream>
using namespace std;
class OverloadExample {
public:
// Function Overloading based on Number of Parameters
void display(int num) {
cout << "Integer: " << num << endl;
}
void display(int num1, int num2) {
cout << "Two Integers: " << num1 << " and " << num2 << endl;
}
// Function Overloading based on Data Types
void display(double num) {
cout << "Double: " << num << endl;
}
// Function Overloading based on Parameter Order
void display(int a, double b) {
cout << "Int: " << a << ", Double: " << b << endl;
}
void display(double a, int b) {
cout << "Double: " << a << ", Int: " << b << endl;
}
};
int main() {
OverloadExample obj;
obj.display(5); // Calls display(int)
obj.display(10, 20); // Calls display(int, int)
obj.display(5.5); // Calls display(double)
obj.display(10, 5.5); // Calls display(int, double)
obj.display(5.5, 10); // Calls display(double, int)
return 0;
}
Output:
Integer: 5
Two Integers: 10 and 20
Double: 5.5
Int: 10, Double: 5.5
Double: 5.5, Int: 10
Scenario Based Programs
1. ShopEase Supermarket wants to implement a billing system using
function overloading to compute the final payable amount. The
system should apply:
A 7% discount for loyal customers.
A 12% discount for gold members.
A fixed $25 discount if a special discount code is used.
The program should overload the calculateDiscount() function
to handle discounts based on customer type and discount
codes, allowing users to enter their details and displaying the
original amount, discount applied, and final payable amount.
#include <iostream>
using namespace std;
class ShopEase {
public:
// Function to calculate discount for loyal customers (7%)
double calculateDiscount(double amount, string customerType) {
if (customerType == "loyal") {
return amount * 0.07; // 7% discount
return 0;
// Function to calculate discount for gold members (12%)
double calculateDiscount(double amount, string customerType, bool
isGoldMember) {
if (isGoldMember) {
return amount * 0.12; // 12% discount
return calculateDiscount(amount, customerType);
// Function to calculate discount for special discount code ($25 off)
double calculateDiscount(double amount, string customerType, bool
isGoldMember, bool hasDiscountCode) {
double discount = calculateDiscount(amount, customerType,
isGoldMember);
if (hasDiscountCode) {
discount += 25; // Additional $25 discount
return discount;
};
int main() {
ShopEase shop;
double amount;
string customerType;
char goldMemberChoice, promoCodeChoice;
bool isGoldMember = false, hasDiscountCode = false;
// User input
cout << "Enter purchase amount: $";
cin >> amount;
cout << "Enter customer type (regular/loyal): ";
cin >> customerType;
cout << "Are you a Gold Member? (y/n): ";
cin >> goldMemberChoice;
cout << "Do you have a Special Discount Code? (y/n): ";
cin >> promoCodeChoice;
// Convert user choices
if (goldMemberChoice == 'y' || goldMemberChoice == 'Y')
isGoldMember = true;
if (promoCodeChoice == 'y' || promoCodeChoice == 'Y')
hasDiscountCode = true;
// Calculate discount
double discount = shop.calculateDiscount(amount, customerType,
isGoldMember, hasDiscountCode);
double finalAmount = amount - discount;
// Display results
cout << "\nOriginal Amount: $" << amount << endl;
cout << "Discount Applied: $" << discount << endl;
cout << "Final Payable Amount: $" << finalAmount << endl;
return 0;
Enter purchase amount: $200
Enter customer type (regular/loyal): loyal
Are you a Gold Member? (y/n): n
Do you have a Special Discount Code? (y/n): n
Original Amount: $200
Discount Applied: $14
Final Payable Amount: $186
2. BizTech Solutions wants to implement a salary increment system for
its employees using a friend function in C++. The system should
calculate the annual increment based on the employee’s role:
Senior Managers receive a 15% salary increment.
Software Developers receive a 7% salary increment.
Employees with more than 3 years of experience get an extra
$1,000 loyalty bonus.
The program should compute the total increment, display the original
salary, increment earned, and final salary after applying the
increment.
#include <iostream>
using namespace std;
class Employee {
private:
string name, role;
double salary;
int experience;
public:
// Function to set employee details
void setDetails(string empName, string empRole, double empSalary,
int empExperience) {
name = empName;
role = empRole;
salary = empSalary;
experience = empExperience;
}
// Friend function to calculate salary increment
friend void calculateIncrement(Employee emp);
};
// Function to calculate salary increment using friend function
void calculateIncrement(Employee emp) {
double increment = 0;
if (emp.role == "manager") {
increment = emp.salary * 0.15; // 15% increment for managers
} else if (emp.role == "developer") {
increment = emp.salary * 0.07; // 7% increment for developers
if (emp.experience > 3) {
increment += 1000; // Extra $1,000 for employees with more than
3 years of experience
double finalSalary = emp.salary + increment;
// Display Results
cout << "\nEmployee Name: " << emp.name << endl;
cout << "Role: " << emp.role << endl;
cout << "Original Salary: $" << emp.salary << endl;
cout << "Increment Earned: $" << increment << endl;
cout << "Final Salary After Increment: $" << finalSalary << endl;
int main() {
Employee emp;
string name, role;
double salary;
int experience;
// Taking user input
cout << "Enter Employee Name: ";
getline(cin, name);
cout << "Enter Role (manager/developer): ";
cin >> role;
cout << "Enter Salary: $";
cin >> salary;
cout << "Enter Years of Experience: ";
cin >> experience;
// Set details and calculate increment
emp.setDetails(name, role, salary, experience);
calculateIncrement(emp);
return 0;
Enter Employee Name: Alice
Enter Role (manager/developer): manager
Enter Salary: $5000
Enter Years of Experience: 5
Employee Name: Alice
Role: manager
Original Salary: $5000
Increment Earned: $1750
Final Salary After Increment: $6750
3. A Healthcare Crisis Management System needs to track and manage
emergency medical aid for affected areas. The system should store
details such as crisis type, location, number of patients, and
medical aid funds allocated. It should initialize crisis details when a
record is created and notify when a record is removed. The system
must allow increasing medical aid funds and decreasing the
number of patients as medical assistance is provided. Write a C++
program to implement this system using appropriate object-
oriented programming concepts.
#include <iostream>
#include <string>
using namespace std;
class HealthcareCrisis {
private:
string crisisType, location;
int patients;
double medicalFunds;
public:
// Constructor to initialize crisis details
HealthcareCrisis(string type, string loc, int numPatients, double
funds) {
crisisType = type;
location = loc;
patients = numPatients;
medicalFunds = funds;
cout << "Healthcare Crisis Record Created for: " << crisisType << "
at " << location << endl;
}
// Function to increase medical funds
void increaseFunds(double amount) {
if (amount > 0) {
medicalFunds += amount;
cout << "Medical funds increased by $" << amount << ". Total
funds: $" << medicalFunds << endl;
} else {
cout << "Invalid amount. Funds remain at $" << medicalFunds <<
endl;
}
}
// Function to decrease number of patients as aid is provided
void reducePatients(int treated) {
if (treated > 0 && treated <= patients) {
patients -= treated;
cout << treated << " patients treated. Remaining patients: " <<
patients << endl;
} else {
cout << "Invalid number of patients treated. Current count: " <<
patients << endl;
}
}
// Function to display crisis details
void displayInfo() {
cout << "\nCrisis Type: " << crisisType << endl;
cout << "Location: " << location << endl;
cout << "Number of Patients: " << patients << endl;
cout << "Medical Aid Funds: $" << medicalFunds << endl;
}
// Destructor to notify when crisis record is removed
~HealthcareCrisis() {
cout << "Healthcare Crisis Record for " << crisisType << " at " <<
location << " has been removed.\n";
}
};
int main() {
string type, loc;
int numPatients;
double funds;
// Taking user input
cout << "Enter crisis type (e.g., Epidemic, Natural Disaster): ";
getline(cin, type);
cout << "Enter location: ";
getline(cin, loc);
cout << "Enter number of patients: ";
cin >> numPatients;
cout << "Enter allocated medical aid funds: $";
cin >> funds;
// Creating crisis record
HealthcareCrisis crisis(type, loc, numPatients, funds);
// Performing operations
crisis.displayInfo();
crisis.increaseFunds(5000); // Example of adding funds
crisis.reducePatients(10); // Example of treating patients
crisis.displayInfo();
return 0; // Destructor will be automatically called
}
Enter crisis type (e.g., Epidemic, Natural Disaster): Epidemic
Enter location: City Hospital
Enter number of patients: 50
Enter allocated medical aid funds: $20000
Healthcare Crisis Record Created for: Epidemic at City Hospital
Crisis Type: Epidemic
Location: City Hospital
Number of Patients: 50
Medical Aid Funds: $20000
Medical funds increased by $5000. Total funds: $25000
10 patients treated. Remaining patients: 40
Crisis Type: Epidemic
Location: City Hospital
Number of Patients: 40
Medical Aid Funds: $25000
Healthcare Crisis Record for Epidemic at City Hospital has been
removed.