Re: reg constructors/copy constructors inheritance
* srp113:
Hello,
I have a base class A, and class D derived from A. I declare a
constructor(ctr) for B() but in definition I dont explicitly call
constructor for A. Compiler however seems to take care of this and
when I construct an object of D, it calls A's ctr first followed by
D's ctr. I tried to see if same holds true for copy constructors: I
defined copy constructor for A and D, and D's copy ctr didnt include
any calls for calling A's copy ctr. In this case though, what happens
is A's default ctr (NOT copy ctr) is called and then B's copy ctr. Why
this discrepancy?
For the question of "why" you'd better ask in [comp.std.c++].
But regarding what the rules are, not why the are: the automatically generated
calls do not depend on the arguments to the constructor in question.
Copy constructors are treated specially in some ways, namely (1) that a copy
constructor can be automatically generated, (2) that a templated constructor is
never a copy constructor (i.e. you can still get an automatically generated one)
and (3) that copy constructor calls can be elided in certain cases even when the
copy constructor has some side effect, i.e. that the compiler is free to treat a
copy constructor as if it really just copied and nothing else.
But copy constructors are not treated specially with regard to initialization of
bases and members.
So, if you define a copy constructor without using an initializer list to call
base class and member copy constructors, those will default-initialized -- and
if they cannot be default-initialized the compiler will protest very loudly.
In general if you define a constructor (default/
copy) in derived class is it better to include an explicit call to
corr. base classes constructor?
For a copy constructor: yes, assuming that by "call" you mean to call it via an
initializer list, like
struct D: A
{
D( D const& other ): A( other ) { ... }
};
Cheers & hth.,
- Alf
PS: I think you meant to write either just "D" or just "B".