Sobes.tech
Middle+

If an exception is thrown in the constructor, will the destructor be called?

sobes.tech AI

Answer from AI

No, the destructor will not be called.

If an exception occurs during the execution of a class constructor, the object is considered not fully constructed. In such cases, C++ does not call the destructor for this partially constructed object. Destructors are only called for fully constructed sub-objects (base classes or class members).

Example:

#include <iostream>
#include <stdexcept>

class MyClass {
public:
    MyClass() {
        std::cout << "MyClass constructor" << std::endl;
        throw std::runtime_error("Constructor error");
    }

    ~MyClass() {
        std::cout << "MyClass destructor" << std::endl; // This code will not be executed
    }
};

int main() {
    try {
        MyClass obj; // Exception will be thrown here
    } catch (const std::runtime_error& e) {
        std::cerr << "Caught exception: " << e.what() << std::endl;
    }
    return 0;
}

Program output:

MyClass constructor
Caught exception: Constructor error

Destructor ~MyClass() is not called.