-
-
Notifications
You must be signed in to change notification settings - Fork 1
6. CPP
AsynchronousAI edited this page Sep 3, 2025
·
2 revisions
You can also use C++!
Warning
Because of C++ name mangling, if you want a custom function in C++ you must use extern "C".
extern "C" void printf(const char *, ...);
class BankAccount {
private:
const char* owner;
int balance; // integer balance only
public:
BankAccount(const char* name, int initialBalance)
: owner(name), balance(initialBalance) {}
void deposit(int amount) {
if (amount > 0) {
balance += amount;
printf("Deposited: $%d", amount);
} else {
printf("Invalid deposit amount.");
}
}
void withdraw(int amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
printf("Withdrew: $%d", amount);
} else {
printf("Insufficient funds or invalid amount.");
}
}
void showBalance() const {
printf("%s's balance: $%d", owner, balance);
}
};
int main() {
BankAccount account("Alice", 1000); // initial balance is integer
account.showBalance();
account.deposit(250);
account.withdraw(500);
account.showBalance();
BankAccount account2("Bob", 1250); // initial balance is integer
account2.showBalance();
account2.deposit(250);
account2.withdraw(500);
account2.showBalance();
return 0;
}