ENCAPSULATION EXAMPLE
#include <iostream>
#include <string>
using namespace std;
class BankAccount {
private:
string accountHolderName; // Private member to store the account holder's
name
string accountNumber; // Private member to store the account number
double balance; // Private member to store the account balance
public:
// Constructor to initialize the BankAccount object with provided values
BankAccount(const string &holderName, const string &accNumber, double
initialBalance)
: accountHolderName(holderName), accountNumber(accNumber),
balance(initialBalance) {}
// Getter function to retrieve the account holder's name
string getAccountHolderName() {
return accountHolderName;
}
// Getter function to retrieve the account number
string getAccountNumber() {
return accountNumber;
// Getter function to retrieve the balance
double getBalance() {
return balance;
// Setter function to update the account holder's name
void setAccountHolderName(const string &holderName) {
accountHolderName = holderName;
// Function to deposit money into the account
void deposit(double amount) {
if (amount > 0) {
balance += amount;
cout << "Deposited: $" << amount << endl;
} else {
cout << "Invalid deposit amount!" << endl;
// Function to withdraw money from the account
void withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
cout << "Withdrawn: $" << amount << endl;
} else {
cout << "Invalid withdrawal amount or insufficient funds!" << endl;
};
int main() {
// Create a BankAccount object with initial values
BankAccount account("John Doe", "123456789", 1000.0);
// Display the initial account details
cout << "Account Holder: " << account.getAccountHolderName() << endl;
cout << "Account Number: " << account.getAccountNumber() << endl;
cout << "Initial Balance: $" << account.getBalance() << endl;
// Perform a deposit
account.deposit(500.0);
// Display the updated balance
cout << "Updated Balance: $" << account.getBalance() << endl;
// Perform a withdrawal
account.withdraw(300.0);
// Display the updated balance
cout << "Updated Balance: $" << account.getBalance() << endl;
// Attempt an invalid withdrawal
account.withdraw(1500.0);
// Display the final balance
cout << "Final Balance: $" << account.getBalance() << endl;
return 0;
}Explanation
1. Private Members:
accountHolderName: Stores the name of the account holder.
accountNumber: Stores the account number.
balance: Stores the account balance.
2. Constructor:
Initializes the BankAccount object with the account holder's name,
account number, and initial balance.
3. Getter Functions:
getAccountHolderName(): Returns the account holder's name.
getAccountNumber(): Returns the account number.
getBalance(): Returns the balance.
4. Setter Function:
setAccountHolderName(const string &holderName): Updates the
account holder's name.
5. Member Functions:
deposit(double amount): Adds the specified amount to the balance
if it is positive.
withdraw(double amount): Deducts the specified amount from the
balance if it is positive and there are sufficient funds.
6. Main Function:
Creates a BankAccount object with initial values.
Displays the initial account details.
Performs a deposit and displays the updated balance.
Performs a withdrawal and displays the updated balance.
Attempts an invalid withdrawal and displays the final balance.
Encapsulation Benefits
Data Hiding: The private members are not accessible directly from outside
the class, ensuring that the internal state of the object can only be modified
through the public methods.
Controlled Access: The public methods (deposit and withdraw) provide
controlled access to modify the balance, preventing invalid operations.
Maintainability: Changes to the internal implementation can be made
without affecting the code that uses the BankAccount class, as long as
the public interface remains consistent.
This example demonstrates how encapsulation helps in protecting the internal
state of an object and provides a clear and controlled interface for interacting with
the object.
Question:
You are given the following code for a BankAccount class, which demonstrates
the principle of encapsulation. The BankAccount class contains private data
members for the account holder's name, account number, and balance. It
provides public methods to deposit and withdraw money, as well as to retrieve
the account details. The main function creates BankAccount objects for four
different people, displays their initial account details, and allows the user to
perform deposit and withdrawal transactions for each account.
#include <iostream>
#include <string>
using namespace std;
class BankAccount {
private:
string accountHolderName;
string accountNumber;
double balance;
public:
// Constructor to initialize the BankAccount with initial values
BankAccount(const string &holderName, const string &accNumber, double
initialBalance)
: accountHolderName(holderName), accountNumber(accNumber),
balance(initialBalance) {}
// Getters to access private member variables
string getAccountHolderName() {
return accountHolderName;
string getAccountNumber() {
return accountNumber;
}
double getBalance() {
return balance;
// Function to deposit money into the account
void deposit(double amount) {
if (amount > 0) {
balance += amount;
cout << "Deposited: $" << amount << " into account: " << accountNumber
<< endl;
} else {
cout << "Invalid deposit amount!" << endl;
// Function to withdraw money from the account
void withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
cout << "Withdrawn: $" << amount << " from account: " << accountNumber
<< endl;
} else {
cout << "Invalid withdrawal amount or insufficient funds!" << endl;
};
void showAccountDetails(BankAccount &account) {
cout << "Account Holder: " << account.getAccountHolderName() << endl;
cout << "Account Number: " << account.getAccountNumber() << endl;
cout << "Balance: $" << account.getBalance() << endl;
void handleUserInput(BankAccount &account) {
double amount;
cout << "Enter amount to deposit for " << account.getAccountHolderName()
<< ": ";
cin >> amount;
account.deposit(amount);
cout << "Updated Balance: $" << account.getBalance() << endl;
cout << "Enter amount to withdraw for " << account.getAccountHolderName()
<< ": ";
cin >> amount;
account.withdraw(amount);
cout << "Updated Balance: $" << account.getBalance() << endl;
int main() {
// Create BankAccount objects for four different people
BankAccount account1("John Doe", "123456789", 1000.0);
BankAccount account2("Jane Smith", "987654321", 2000.0);
BankAccount account3("Alice Johnson", "123123123", 1500.0);
BankAccount account4("Bob Brown", "321321321", 1800.0);
// Display initial details and handle user input for each account
cout << "Initial Account Details:" << endl;
showAccountDetails(account1);
showAccountDetails(account2);
showAccountDetails(account3);
showAccountDetails(account4);
cout << "\nTransactions:" << endl;
handleUserInput(account1);
handleUserInput(account2);
handleUserInput(account3);
handleUserInput(account4);
return 0;
Explanation
1. Class Definition:
The BankAccount class remains unchanged, with private members
for the account holder's name, account number, and balance.
Public methods include a constructor, getters, deposit(), and
withdraw() functions.
2. Helper Functions:
showAccountDetails(BankAccount &account): Displays the
account details (holder's name, account number, and balance).
handleUserInput(BankAccount &account): Handles user input for
deposit and withdrawal operations on a given account.
3. Main Function:
Creates four BankAccount objects for different people.
Displays the initial account details for each account using
showAccountDetails.
Interacts with the user to deposit and withdraw money for each
account using handleUserInput.
Key Points
Encapsulation: Each BankAccount object encapsulates its data,
ensuring that the balance and account details are only accessible through
the public methods.
Modularity: The use of helper functions (showAccountDetails and
handleUserInput) makes the code more modular and easier to
understand.
Interactive User Input: The program interacts with the user to perform
transactions on each account, demonstrating the encapsulated behavior of
each BankAccount object independently.
This example shows how encapsulation works with multiple objects, each
maintaining its own state and behavior, and how user interaction can be handled
for each object individually.
Write a C++ program to create a class called Car that has private member
variables for company, model, and year. Implement member functions to get and
set these variables.
Sample Solution:
C ++ Code:
#include <iostream> // Including the necessary header for input/output
stream
#include <string> // Including the necessary header for string
operations
using namespace std; // Use the standard namespace
class Car { // Defining a class named Car
private:
string company; // Private member to store the company name of the
car
string model; // Private member to store the model name of the car
int year; // Private member to store the year of the car
public:
// Constructor to initialize Car object with provided values
Car(const string & comp, const string & mdl, int yr):
company(comp), model(mdl), year(yr) {}
// Getter functions to retrieve private member variables
string getCompany() { // Getter function for retrieving the
company name
return company; // Return the stored company name
}
string getModel() { // Getter function for retrieving the model
name
return model; // Return the stored model name
}
int getYear() { // Getter function for retrieving the year
return year; // Return the stored year
}
// Setter functions to modify private member variables
void setCompany(const string & comp) { // Setter function for
modifying the company name
company = comp; // Assign the provided company name to the
'company' member variable
}
void setModel(const string & mdl) { // Setter function for
modifying the model name
model = mdl; // Assign the provided model name to the 'model'
member variable
}
void setYear(int yr) { // Setter function for modifying the year
year = yr; // Assign the provided year to the 'year' member
variable
}
};
int main() {
// Create a car object with initial values
Car car("AUDI", "A6", 2023);
// Get and display the car details using getter functions
cout << "Company: " << car.getCompany() << endl; // Output the car's
company name
cout << "Model: " << car.getModel() << endl; // Output the car's
model name
cout << "Year: " << car.getYear() << endl; // Output the car's year
// Set new values for the car using setter functions
car.setCompany("BMW"); // Update the car's company name
car.setModel("M4"); // Update the car's model name
car.setYear(2022); // Update the car's year
// Get and display the updated car details using getter functions
cout << "\nUpdated Company: " << car.getCompany() << endl; // Output
the updated car's company name
cout << "Updated Model: " << car.getModel() << endl; // Output the
updated car's model name
cout << "Updated Year: " << car.getYear() << endl; // Output the
updated car's year
return 0; // Return 0 to indicate successful completion
}
Sample Output:
Company: AUDI
Model: A6
Year: 2023
Updated Company: BMW
Updated Model: M4
Updated Year: 2022
Explanation:
In the above exercise,
The "Car" class represents a car with private member variables company, model,
and year. The constructor initializes these variables.
The getter functions (getCompany(), getModel(), getYear()) are used to retrieve
the values of the private member variables.
The setter functions (setCompany(), setModel(), setYear()) are used to modify
the values of the private member variables.
In the main() function, a Car object is created with the company as "AUDI",
model as "A6", and year as 2023. The getter functions (getCompany(),
getModel(), getYear()) are then called to retrieve and display the car details.
Next, the setter functions (setCompany(), setModel(), setYear()) are used to set
new values for the car's company, model, and year. Again, the getter functions
are called to retrieve and display updated car details.
Flowchart:
Write a C++ program to get the current date and time.
1.Display the current date and time
#include <iostream>
#include <ctime> // Including the C Standard Library header for time functions
using namespace std;
int main()
// current date and time in current system using time_t data type
time_t current_dt = time(0); // Get the current system time in seconds since epoch (Jan 1, 1970)
// convert date time to string format using ctime function
char* result = ctime(¤t_dt); // Convert the time_t value to a string representing local time
// Display the current date and time in string format
cout << "The current date and time is:\n" << result << endl;
Sample Output:
The current date and time is:
Tue Mar 15 14:28:05 2022
Flowchart:
Sample Solution-2:
C++ Code:
#include <iostream>
#include <ctime>
using namespace std;
int main() {
time_t crtime; // Declare a variable to hold the current time as seconds since epoch
struct tm* time_info; // Declare a pointer to a structure to hold time information
char result[80]; // Declare an array to store formatted time as a string
time(&crtime); // Get the current system time in seconds since epoch and store it in crtime
time_info = localtime(&crtime); // Convert the time_t value into a local time representation using
localtime function
// Format the time_info into a string according to the specified format "%d-%m-%Y %H:%M:%S"
strftime(result, sizeof(result), "%d-%m-%Y %H:%M:%S", time_info);
cout << result; // Output the formatted time string
return 0;
Sample Output:
15-03-2022 12:15:31
Flowchart:
Sample Solution-2:
C++ Code:
#include <iostream>
#include <ctime>
using namespace std;
int main() {
time_t crtime; // Declare a variable to hold the current time as seconds since epoch
struct tm* time_info; // Declare a pointer to a structure to hold time information
char result[80]; // Declare an array to store formatted time as a string
time(&crtime); // Get the current system time in seconds since epoch and store it in crtime
time_info = localtime(&crtime); // Convert the time_t value into a local time representation using
localtime function
// Format the time_info into a string according to the specified format "%d-%m-%Y %H:%M:%S"
strftime(result, sizeof(result), "%d-%m-%Y %H:%M:%S", time_info);
cout << result; // Output the formatted time string
return 0;
Sample Output:
15-03-2022 12:15:31
Flowchart:
C++ Exercises: Get the day of the week from
a given date
Write a C++ program to get the current date and time.
Sample Solution-1:
C++ Code:
#include <iostream>
#include <ctime> // Including the C Standard Library header for time
functions
using namespace std;
int main()
// current date and time in current system using time_t data type
time_t current_dt = time(0); // Get the current system time in
seconds since epoch (Jan 1, 1970)
// convert date time to string format using ctime function
char* result = ctime(¤t_dt); // Convert the time_t value to a
string representing local time
// Display the current date and time in string format
cout << "The current date and time is:\n" << result << endl;
Sample Output:
The current date and time is:
Tue Mar 15 14:28:05 2022
Flowchart:
Sample Solution-2:
C++ Code:
#include <iostream>
#include <ctime>
using namespace std;
int main() {
time_t crtime; // Declare a variable to hold the current time as
seconds since epoch
struct tm* time_info; // Declare a pointer to a structure to hold
time information
char result[80]; // Declare an array to store formatted time as a
string
time(&crtime); // Get the current system time in seconds since
epoch and store it in crtime
time_info = localtime(&crtime); // Convert the time_t value into a
local time representation using localtime function
// Format the time_info into a string according to the specified
format "%d-%m-%Y %H:%M:%S"
strftime(result, sizeof(result), "%d-%m-%Y %H:%M:%S", time_info);
cout << result; // Output the formatted time string
return 0;
Copy
Sample Output:
15-03-2022 12:15:31
Flowchart: