Re: reg constructors/copy constructors inheritance
On Feb 17, 1:13 am, srp113 <sunilsreenivas2...@yahoo.com> wrote:
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?
There's no discrepancy. If a base class has a constructor (of
any type), then all derived class constructors will call a
constructor of the base class. If you don't specify arguments
for it in the initialization list, it will call the default
constructor for the base class; the one without arguments. A
copy constructor is no exception to this rule. (Obviously, in
the case of a copy constructor, this is rarely what we want, but
it's still up to you to define something else.)
(Copy constructors are a bit special in other ways: if you don't
declare one, the compiler will, and if the compiler declared
copy constructor is used, the compiler will also define it. And
the compiler defined copy constructor copies all of the base
classes and members---using their copy constructors.)
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?
It depends. If I want the base class default constructed, I'll
usually just skip it, unless the base class is a POD. But
anytime you want anything other than default construction, you
have to explicitly mention the class in the initialization list.
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34