On Apr 25, 12:07 pm, Jess <w...@hotmail.comwrote:
Quote:
When I define default constructors, I tend to use constructor
initializers for member data. However, I was told the order in which
members are initialized is determined by the order of declaration in
the class, instead of the order they appear in the constructor
initializer. This would introduce interdependencies. Therefore, it
is safer to avoid such interdependence by assigning values to these
members inside the constructor body rather than initializing them in
the intializer. Could someone explain to me why this is the case?
Moreover, what kind of error could possibly happen due to the
"interdependency"?
There are cases where one attribute needs to be passed into a
superclass constructor or into another attribute's constructor and
these can cause problems.
Where you're passing between attributes then you should order them
correctly in the class definition. Where you have to pass into the
superclass I've done something like this (heavily abridged):
// Super's constructor needs an int pointer to use
class Super { Super( int * ); };
// We store the int here
class Holder { int m_attribute; };
// We can now get the int constructed before Super needs it
class Sub : Holder, Super { Sub(); };
// Pass the int to Super
Sub::Sub()
: Holder(), Super( &m_attribute ) {}
As I understand it the order of the super-classes in the definition of
Sub is important, not the order of the calls in the definition of
Sub's constructor. This is analogous to the case with the attribute
order in the class definition.
K