Lesson 18 of 45
C++Lesson 18: Classes and Objects
11 min
Course progress40%
What you'll learn
Keep these ideas in mind as you work through the lesson.
Lesson 18 of 45
C++11 min
Keep these ideas in mind as you work through the lesson.
A class defines a type consisting of data members (state) and member functions (behaviour). Objects are instances of classes. Encapsulation hides internal details behind a public interface.
BankAccount classclass BankAccount {
std::string owner;
double balance{};
public:
BankAccount(const std::string& name, double initial) : owner(name), balance(initial) {}
void deposit(double amount) { balance += amount; }
bool withdraw(double amount) {
if (amount > balance) return false;
balance -= amount;
return true;
}
void print() const { std::cout << owner << \" balance: $\" << balance << '\
'; }
};
int main() {
BankAccount acc(\"Alice\", 1000.0);
acc.deposit(250);
acc.withdraw(500);
acc.print();
return 0;
}
Key concepts demonstrated:
this pointer is implicit inside member functions.print marked const).Tip: Keep member data
privateand expose only the operations that maintain class invariants.
<Alert type="info">C++20 introduced explicit(bool) constructors for more granular control.