10.4 — Constructors: setting up an object
Read one box at a time. No rush.
The setup function#
A constructor is a special member function that runs automatically when an object is created. It has the same name as the class and no return type.
C++▶ Run
class BankAccount{public: BankAccount(std::string owner, double balance) : m_owner { owner }, m_balance { balance } { std::cout << "Account opened for " << m_owner << '\n'; } double balance() const { return m_balance; } private: std::string m_owner {}; double m_balance {};}; int main(){ BankAccount acc { "Ana", 50.0 }; std::cout << acc.balance() << '\n'; return 0;}Output
Account opened for Ana50The member initializer list#
The part after the : — m_owner { owner }, m_balance { balance } — sets the members' starting values. This is the preferred way to set them.
Default constructor#
A constructor with no parameters lets you write BankAccount acc {};:
C++
BankAccount() : m_owner { "nobody" }, m_balance { 0.0 }{}Destructors (a quick look)#
A destructor runs when an object is destroyed. Its name is ~ plus the class name. You rarely need to write one yourself — std::string, std::vector and smart pointers clean up after themselves.
Tip: press ← / → to move between lessons, / to search.