Topic 4 of 27 · Intermediate
Classes, Constructors & Destructors
Access specifiers, initialiser lists, this and static members.
Concept
A class bundles data and functions. Members are private by default (public in a struct).
Constructors initialise objects — prefer member initialiser lists. The destructor (~Class) runs automatically when the object goes out of scope.
static members belong to the class. this is a pointer to the current object.
Code (C++20)
#include <iostream>
#include <string>
class Account {
std::string owner_;
double balance_;
static inline int count_ = 0;
public:
Account(std::string owner, double bal = 0) : owner_(std::move(owner)), balance_(bal) { ++count_; }
~Account() { --count_; }
void deposit(double amt) { if (amt > 0) balance_ += amt; }
double balance() const { return balance_; }
static int count() { return count_; }
};
int main() {
Account a("Asha", 500);
a.deposit(250);
std::cout << a.balance() << ' ' << Account::count() << '\n';
}Remember
- class = private default; struct = public.
- Use initialiser lists.
- Destructors run in reverse order of construction.
Interview questions
Why use initialiser lists?
Members are initialised directly instead of default-constructed then assigned; const and reference members require them.
When is the destructor called?
When an automatic object leaves scope, when delete is called on a heap object, or at program end for statics.
Lesson test
Take an 8-question test on “Classes, Constructors & Destructors” — concepts, output prediction, bug spotting and interview questions.