"Destructors for a derived class object are called in the reverse order of the constructors for the object. This is a general rule that always applies. Constructors are invoked starting with the base class constructor and then the derived class constructor, whereas the destructor for the derived class is called
first when an object is destroyed, followed by the base class destructor."
But why, or is it just because, so programmers know which one and modify their destructor accordingly??
I believe it is because in a class hierarchy, the derived classes may be using variables or data located i base classes. Is it not logical to initialize these first to ensure that the derived classes do not use invalid data? When we then destroy the objects; would it be logical to destroy "base" data whilst the derived destructor may still use this data in its destructor?
I believe this is the logical reasoning behind this rule. Think about it.
If the base class portion of a derived class were destroyed before the derived class version, the class instance would be in an undefined state. It would only be half-alive when the derived class destructor was called.
Maybe the base class has a container of some sort. The derived class writes the data in the container to a file when it's destructor is called. How does it write that data to file if the container no longer exists?
but wouldnt the container be destroyed right after? Literally right after?
Yes, which is why it has to write the data beforehand. If destructors were called in the same order as constructors, then you would be trying to write the data after the container was already destroyed. Too bad so sad, you don't have any valid data and all you get is garbage.
But the base class destructor would destroy the container right there and then after it writes to it, not right after but when the derived class constructor ends.
Please list the order in which you expect the destructors to be called in relation to the base class, the derived class, and the map inside the base class.
In this "If the base class portion of a derived class were destroyed before the derived class version, the class instance would be in an undefined state. It would only be half-alive when the derived class destructor was called. "
What does it mean half alive? And how would it be in undefined state?
I know alot of my questions are stupid, I aint a very smart person...
What about the t1 and t2? Yes, they are both of type T, but each calls constructor separately. Is there any ordering, or is it just random?
You construct box.u before calling box.B(), but also construct box.t[12] after calling box.A(). If you would create plain A ball;, what would be the order of ball.A() and ball.t1.T(), or does it matter?
Consider
1 2 3 4
A::A() : t2( 42 )
{
t1 = 7;
}
Does that set some requirements for the order of construction?