What do constructors and destructors do?
Assesses fundamental understanding of C++ conventions, runtime behavior, and memory/performance considerations.
Hiring managers look for precision, avoidance of ambiguous jargon, and ability to explain trade-offs under real production conditions.
A constructor runs when an object is created and initialises its members. A destructor runs when it is destroyed and releases resources. Constructors share the class name and have no return type; destructors are ~Class(), take no arguments and there is exactly one.
class Buffer {
public:
explicit Buffer(std::size_t n)
: data_(new char[n]), size_(n) {}
~Buffer() { delete[] data_; }
Buffer(const Buffer&) = delete;
Buffer& operator=(const Buffer&) = delete;
private:
char* data_;
std::size_t size_;
};
Prefer the member initialiser list over assignment in the constructor body. It initialises directly instead of default-constructing then assigning, and it is required for const and reference members. Initialisation order follows declaration order, not the order in the list, which can surprise you.
A destructor that reliably frees resources is what makes RAII work, so cleanup happens on scope exit and during stack unwinding from an exception.
Candidate Response Strategy & Interview Tips
- Start with a concise one-sentence summary: Deliver a direct, confident answer first before expanding into nuances.
- Demonstrate real-world trade-offs: Discuss where this approach excels and when you would avoid it in production systems.
- Discuss complexity & edge cases: Proactively explain time/space complexity or boundary conditions (null values, scale limits).
- Prepare for interviewer follow-ups: Technical hiring panels frequently probe deeper into concurrency, backward compatibility, or alternative libraries.