Constructors and Destructors
The constructor sets up an object and the destructor cleans up when it ends.
Example
#include <iostream>
#include <string>
struct Res {
std::string n;
Res(std::string n) : n(n) { std::cout << "make " << n << "\n"; }
~Res() { std::cout << "free " << n << "\n"; }
};
int main() {
{
Res r("A");
std::cout << "in scope\n";
}
std::cout << "after\n";
return 0;
}Result
make A in scope free A after
Exercise
Destructor prefix.
Res() {}Quiz Test
These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.