Destructor in C++

Level 4226 keystrokes

A local object's destructor runs automatically when the block that contains it ends, so Destroyed is printed between Inside scope and After scope.

C++ code

1class Resource {
2public:
// Constructor: prints Created
3 Resource() { cout << "Created" << endl; }
// Destructor (~ + class name): prints Destroyed
4 ~Resource() { cout << "Destroyed" << endl; }
5};
6
// Print Before scope
7cout << "Before scope" << endl;
// Start a new block scope
8{
// Constructing r prints Created
9 Resource r;
// Print Inside scope
10 cout << "Inside scope" << endl;
// r is destroyed here at the end of the block: prints Destroyed
11}
// Print After scope
12cout << "After scope" << endl;

Output

Before scope
Created
Inside scope
Destroyed
After scope
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this C++ code and how often they appear.

  • <× 20
  • "× 10
  • ;× 7
  • {× 4
  • }× 4
  • (× 2
  • )× 2
  • :× 1
  • ~× 1

More C++ examples at level 4

← C++ typing practice