Examples Codes 2 object oriented programming
Examples Codes 2 object oriented programming
Example 1
1. Private attributes:
2. spendMoney(amount): Deducts money from the wallet if there are sufficient funds.
3. displayWalletInfo(): Displays the wallet owner's name and the current balance.
1. Create a Wallet object with initial values for the owner's name and balance.
SOLUTION
#include <iostream>
#include <string>
// class
class Wallet {
private:
string owner;
double balance;
public:
// Constructor
cout << "Wallet created for " << owner << " with initial balance: $" << balance << endl;
// Destructor
~Wallet() {
cout << "Wallet object for " << owner << " is destroyed.\n";
if (amount > 0) {
cout << "Added $" << amount << " to the wallet. New balance: $" << balance << endl;
} else {
cout << "Invalid amount. Cannot add $" << amount << " to the wallet.\n";
cout << "Insufficient funds! Cannot spend $" << amount << ". Current balance: $" << balance <<
endl;
} else {
balance -= amount;
cout << "Spent $" << amount << " from the wallet. Remaining balance: $" << balance << endl;
cout << "Owner: " << owner << ", Balance: $" << balance << endl;
};
int main() {
myWallet.displayWalletInfo();
myWallet.spendMoney(150.0);
myWallet.addMoney(50.0);
// Successfully spend money
myWallet.spendMoney(80.0);
return 0;
Example 2
Write a C++ program to model a Cube class and demonstrate the use of constructors and a destructor.
a. Create a Cube class with a private attribute: side (length of the side of the cube).
b. Implement two constructors:
SOLUTION
#include <iostream>
class Cube
private:
public:
// Default constructor
Cube() {
cout << "Default constructor called. Side initialized to " << side << endl;
}
// Parameterized constructor
Cube(double sideLength)
cout << "Parameterized constructor called. Side initialized to " << side << endl;
// Destructor
~Cube() {
cout << "Destructor called for cube with side " << side << endl;
};
int main() {
Cube cube1;
Cube cube2(3.5);
return 0;