Lesson 10 of 45 · C++
Lesson 18: Classes and Objects
Duration: 11 min
Lesson 10 of 45 · C++
Duration: 11 min
BankAccount class\ncpp\nclass BankAccount {\n std::string owner;\n double balance{};\npublic:\n BankAccount(const std::string& name, double initial) : owner(name), balance(initial) {}\n void deposit(double amount) { balance += amount; }\n bool withdraw(double amount) {\n if (amount > balance) return false;\n balance -= amount;\n return true;\n }\n void print() const { std::cout << owner << \" balance: $\" << balance << '\\n'; }\n};\n\nint main() {\n BankAccount acc(\"Alice\", 1000.0);\n acc.deposit(250);\n acc.withdraw(500);\n acc.print();\n return 0;\n}\n\n\nKey concepts demonstrated:\n- Constructor initialises members.\n- this pointer is implicit inside member functions.\n- Const‑correctness (print marked const).\n\n> Tip: Keep member data private and expose only the operations that maintain class invariants.\n\n---\n\n<Alert type="info">C++20 introduced explicit(bool) constructors for more granular control.