CJCoding With Joseph
15free / daySign inCreate account

Mastering C++

Class Destructors

Classes In C++

A destructor in C++ is a special member function that is automatically called when an object goes out of scope or is explicitly deleted. Destructors are primarily used to clean up resources, such as releasing memory that was allocated with the keyword new.

To create a destructor, it's very similar to making a constructor, with one key difference: you need to add a ~ (tilde) in front of the class name. For example, if your class is named Foo, the constructor would be Foo() { ... }, and the destructor would be ~Foo() { ... }.

Destructors - A

In this example, we’ll use a FileHandler class to simulate managing a file's lifecycle.

Members only

Keep reading this lesson

You've reached the end of the free preview. Unlock the rest of this lesson plus 21 more lessons in Mastering C++.

  • Unlimited coding questions
  • Unlimited access to all classroom material
  • Weekly live call for questions and guidance
  • 3,000 AI tutor tokens / month
  • Personal SQL database (3 MB)
  • Progress tracking

Cancel any time.