Junior — Middle
How is the sequence of constructor calls implemented when creating an object in inheritance?
sobes.tech AI
Answer from AI
When creating an object in an inheritance hierarchy, constructors are called in order from the base class to the derived class. First, the constructor of the most basic class is called, then down the chain to the derived classes. This guarantees that all parts of the object will be correctly initialized.
For example, in C++:
class Base {
public:
Base() { std::cout << "Base constructor\n"; }
};
class Derived : public Base {
public:
Derived() { std::cout << "Derived constructor\n"; }
};
int main() {
Derived obj;
return 0;
}
The output will be:
Base constructor
Derived constructor
This shows that the constructor of the base class is called first, then the derived class.