Ad space (banner)
Lesson 12 / 20

Constructors and Destructors

This lesson covers constructors and destructors โ€” code that runs automatically when a class instance is created or destroyed. It's for anyone searching "C++ constructor destructor."

A constructor is a member function with the same name as the class, called automatically when an instance is created, used to run initialization logic. A destructor, written ~ClassName(), is called automatically when an instance is destroyed.

The example initializes a name in the constructor, Animal(std::string n), and prints a "goodbye" message in the destructor, ~Animal().

A common early mistake is not knowing exactly when the destructor gets called. In C++, the destructor is called automatically the moment an object goes out of scope (the logic block it was declared in) โ€” a big difference from languages with garbage collection.

In real projects, this is used as a resource-management pattern โ€” opening a file in the constructor and reliably closing it in the destructor, for example.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run C++ directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)