gw7...@aol.com wrote:
Suppose I have the following code fragment:
class base {
private:
int m;
public:
base(int x) { m = x; }
};
class derived : public base {
private:
otherclass o;
public:
derived(int x) : base(x) { }
};
When I create a derived, is otherclass' constructor run or not?
It is: non-POD types are default-constructed after base classes if they
are omitted from the initializer list. Compare this FAQ:
http://parashift.com/c++-faq-lite/ctors.html#faq-10.6
I did
an experiment and it was. However, I'd understood that it wouldn't be.
I thought that *if* I didn't define a default constructor for base
and/or derived, the computer would write one for me which initialised
all the members,
No members are initialized except what you initialize in the
constructor. Default constructors are called for non-POD types, but if
their constructors don't initialize their POD members, then they don't
get initialized either. Consider:
struct A
{
int i_, j_;
A() : i_(0) {} // i_ is initialized, j_ is not
};
struct B : A
{
int m_, n_;
A a_;
B() : m_(0) {} // Base class is implicitly default-constructed,
// a_ is implicitly default constructed,
// m_ is initialized, n_ is not
};
int main()
{
B b;
// ...
}
After B's constructor completes, the following is true:
* b.i_, b.m_, and b.a_.i_ are initialized to 0
* b.n_, b.j_, and b.a_.j_ are all uninitialized
but that, in the above case where I have defined a
non-default constructor, it wouldn't start writing constructors for me
(other than a copy constructor). Can you put me straight on this
please?
The compiler is not generating a default constructor for base or
derived, but it is calling the default constructor for otherclass.
Cheers! --M