Loading workspace environment...
Learn modern C++ class structure, member initialization lists, encapsulation (public/private), and pass-by-const-reference.
class BankAccount { private: double balance; public: BankAccount(double b); };Defines class with encapsulated private member variables.void print(const std::string& str);Passes large objects by const reference without copying.#include <iostream>
#include <string>
class BankAccount {
private:
std::string accountHolder;
double balance;
public:
// Constructor with member initializer list
BankAccount(const std::string& name, double initialDeposit)
: accountHolder(name), balance(initialDeposit) {}
void deposit(double amount) {
if (amount > 0) {
balance += amount;
std::cout << "[Deposit] Added $" << amount << " to " << accountHolder << "\n";
}
}
bool withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
std::cout << "[Withdrawal] Dispensed $" << amount << "\n";
return true;
}
std::cout << "[Error] Insufficient funds!\n";
return false;
}
void displaySummary() const { // const member function does not modify state
std::cout << "Account: " << accountHolder << " | Balance: $" << balance << "\n";
}
};
int main() {
BankAccount account("Ada Lovelace", 500.0);
account.displaySummary();
account.deposit(250.0);
account.withdraw(120.0);
account.displaySummary();
return 0;
}Account: Ada Lovelace | Balance: $500
[Deposit] Added $250 to Ada Lovelace
[Withdrawal] Dispensed $120
Account: Ada Lovelace | Balance: $630void processLargeVector(std::vector<int> data); // Deep copies millions of elements!void processLargeVector(const std::vector<int>& data); // Zero-copy read-only referenceArchitectural Explanation: Passing objects by value in C++ triggers a deep copy constructor. Pass by `const &` to eliminate unnecessary copying.
Create a `Rectangle` class with private `width` and `height`, constructor initializer list, and `double getArea() const` and `double getPerimeter() const` methods.