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++.

Challenge

+30 XP

Write class Time with a constructor Time(int h, int m, int s), add(int seconds) that adds time (wrapping at 24 hours) and print() that prints "HH:MM:SS" with two digits each. In main(), read h m s and the seconds to add, then print. Input: 23 59 30 45 Output: 00:00:15

Output Loading C++ (first time takes a few seconds)
Press Run to see the result here.