Lesson 16 of 24
Constructors and Destructors
10 min 30 XP
A constructor runs when an object is created; the destructor (~ClassName) runs when it is destroyed. An initializer list (: name(n)) is the best way to set fields. A static member is shared by all objects.
Example: edit me and press Run
Output Loading C++ (first time takes a few seconds)
Press Run to see the result here.b's destructor runs automatically when the block ends. This is RAII, tying resources to an object's lifetime, and it is the most important idea in C++.