Explore key concepts of the object lifecycle, including creation, copying, and destruction. This quiz helps you understand constructors, destructors, copy semantics, and lifecycle behaviors important for reliable and maintainable code.
Which of the following is called when a new object is created from a class without passing any arguments?
Explanation: The default constructor is called when an object is created without any arguments and without copying from another object. The copy constructor is used when creating an object as a copy of another. The destructor is called when the object is destroyed, not created. The move assignment operator is used for assigning temporary resources, not initializing an object.
When is the copy constructor invoked in an object’s lifecycle, such as in the statement 'MyClass b = a;'?
Explanation: The copy constructor is used when a new object is created as a copy of an existing object, for example, 'MyClass b = a;'. Assignment after objects have been initialized uses the copy assignment operator, not the copy constructor. Destruction involves the destructor, not the copy constructor. Creating an object without parameters triggers the default constructor.
At what point in an object's lifecycle is the destructor typically called?
Explanation: The destructor is automatically called when an object goes out of scope or is explicitly deleted, ensuring any resources are properly released. It is not called immediately after creation—that is when constructors run. During object copying, either the copy or move constructor is triggered. A destructor is not called before construction.
What risk is associated with only implementing a shallow copy in classes that manage dynamic resources?
Explanation: A shallow copy leads to multiple objects sharing a single resource, like a pointer, which can cause resource conflicts when one object modifies or deletes the resource used by another. Memory leaks can occur if resources aren’t deallocated, but shallow copying more commonly leads to double deletion or dangling pointers. Construction errors occur during construction, not copying. Destructors are still called, but they might operate on already-freed memory.
In a program with local objects, what is the correct order in which destructors are called when exiting a scope?
Explanation: Destructors of local objects are called in the reverse order to their creation, following the Last-In-First-Out (LIFO) principle. The order is not based on variable names or object sizes. Calling destructors in creation order would risk destroying prerequisites needed by objects still in use.