Constructors initialize new objects; destructors clean up when lifetime ends—the foundation of RAII in C++.
Constructor basics
class User {
public:
User(std::string name, int age)
: name_(std::move(name)), age_(age) {}
~User() { /* cleanup if needed */ }
private:
std::string name_;
int age_;
};
Member initializer lists run before the constructor body—required for const and reference members.
Important interview questions and answers
- Q: Rule of zero?
A: If members manage resources via RAII types (std::string,std::vector, smart pointers), compiler-generated special members are often sufficient. - Q: When write a destructor?
A: When the class directly owns raw resources not wrapped in RAII helpers.
Self-check
- Why use initializer lists?
- When does a destructor run?
Tip: Use member initializer lists for const and reference members—they must be initialized before the constructor body runs.
Interview prep
- Rule of zero?
If all members manage resources via RAII types, compiler-generated special members are often sufficient.
- Initializer lists?
Initialize members before the constructor body—required for const and reference members.