What are constructors and destructors in C++?
Why Interviewers Ask This
This is a classic screening question for C++ roles. Hiring managers ask it early in interviews to gauge your baseline understanding and determine if you can communicate technical concepts clearly.
Answer
A constructor is a special member function with the same name as the class and no return type. It is automatically called when an object is created, used to initialize the object's state. A destructor is the complement — called automatically when an object goes out of scope or is deleted, used to release resources. Types of constructors: (1) Default constructor: no parameters — Car() : year(0) {}; (2) Parameterized constructor: accepts arguments — Car(std::string b, int y) : brand(b), year(y) {}; (3) Copy constructor: initializes from another object of the same type — Car(const Car& other) : brand(other.brand), year(other.year) {}; (4) Move constructor (C++11): transfers resources from a temporary — Car(Car&& other) noexcept : brand(std::move(other.brand)), year(other.year) {}; (5) Delegating constructor (C++11): one constructor calls another: Car() : Car("Unknown", 0) {}. Destructor: ~Car() { std::cout << "Car destroyed\n"; }. Only one destructor per class — no parameters, no overloading. Rule of Three: if you define any of copy constructor, copy assignment, or destructor, define all three (managing resources manually). Rule of Five (C++11): also define move constructor and move assignment. Rule of Zero: prefer to use smart pointers and containers so the compiler-generated defaults handle everything correctly. RAII (Resource Acquisition Is Initialization): acquire resources in constructors, release in destructors — the foundation of exception-safe C++ programming.
Common Mistake
Many candidates answer correctly but can't explain the 'why'. Always be prepared to justify your answer with a concrete example or use case from your C++ experience.
Previous
What is a class and an object in C++?
Next
What is the difference between new/delete and malloc/free in C++?