⚙️ C++ Beginner

What are constructors and destructors in C++?

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.