Junior — Middle
What happens to an object if an exception occurs inside its constructor and it is not handled?
sobes.tech AI
Answer from AI
If an exception occurs in a C++ constructor and it is not handled within the constructor:
- The constructor is interrupted, and the object is considered not created.
- Memory allocated for the object is automatically released.
- The destructors of already created members of the object (e.g., fields that are objects) are called to properly release resources.
- The exception is propagated to the calling code, which can catch and handle it.
Thus, the object will not be created, and the program will not receive an invalid object. This helps avoid the use of partially initialized objects.