An object and its member functions
Account acct{"Ada", 100}; runs the constructor, which fills in the private fields. When deposit runs, its frame has this, a pointer to acct: that's how a member function knows which object it's working on.
#include <iostream>
#include <string>
class Account {
public:
Account(std::string owner, int balance) : owner_(owner), balance_(balance) {}
void deposit(int amount) {
balance_ += amount;
}
int balance() const { return balance_; }
private:
std::string owner_;
int balance_;
};
int main() {
Account acct{"Ada", 100};
acct.deposit(50);
std::cout << acct.balance() << "\n";
return 0;
}
Output:
150
From the lesson: Classes