- 01Getting Started
- 02Your First Output (cout)
- 03Variables and Types (int/double/string/bool)
- 04Conditionals (if statements)
- 05Loops (for statements)
- 06Writing a Function
- 07Working with Arrays
- 08Loops (while statements)
- 09Pointer Basics
- 10References
- 11Classes (Object-Oriented Programming)
- 12Constructors and Destructors
- 13Inheritance
- 14Using vector (the Standard Library)
- 15String Manipulation (string)
- 16Structs (struct)
- 17Error Handling (try/catch)
- 18The Ternary Operator
- 19The switch Statement
- 20[Applied] Build a Mini Inventory Management System
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.
๐งช 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).
