Junior
How are the constructor and destructor called in C++?
sobes.tech AI
Answer from AI
The constructor is called automatically at the moment of object creation:
- When declaring a local variable:
MyClass obj; - When dynamically allocating memory:
MyClass* ptr = new MyClass(); - When passing an object by value to a function.
- When returning an object by value from a function.
- When creating a temporary object.
- When initializing array elements:
MyClass arr[3]; - When creating an object as a member of another class.
- When inheriting, the constructors of the base classes are called first.
The destructor is called automatically at the moment of object destruction:
- When the object goes out of scope (for local variables).
- When explicitly deleting an object created with
new:delete ptr; - When the program terminates (for static and global objects).
- When deleting array elements created with
new[]:delete[] arr; - When destroying an object that contains other objects as members.
- When inheriting, the destructors of derived classes are called first.
The order of calls depends on the type of object storage and inheritance hierarchy. For local objects, the constructor call order corresponds to the order of declaration, and destructors — the reverse order. For base and derived classes: first the base constructor, then the derived; destructors in reverse order.
#include <iostream>
class Base {
public:
Base() {
std::cout << "Base constructor" << std::endl;
}
~Base() {
std::cout << "Base destructor" << std::endl;
}
};
class Derived : public Base {
public:
Derived() {
std::cout << "Derived constructor" << std::endl;
}
~Derived() {
std::cout << "Derived destructor" << std::endl;
}
};
int main() {
// Call constructor and destructor of a local object
{ // Scope for local_obj
Base local_obj;
} // local_obj is destroyed here, destructor is called
// Call constructor and destructor of a heap object
Derived* heap_obj = new Derived(); // Calls Base, then Derived constructor
delete heap_obj; // Calls Derived, then Base destructor
return 0; // Global and static objects are destroyed here
}