If subclass doesn’t define any ctor, compiler will implicitly define
a default ctor, then this ctor will call base class default ctor.
If subclass has a ctor, but the subclass’s ctor doesn’t explicitly
call base specify ctor, ctor of subclass will call base default
ctor.(without any parameter.) If base ctor only has specify ctor,
no default ctor, produce compiler error.
If you want explicitly call base specify ctor, use initialization list
syntax.
Constructor should NOT be virtual. When you use inheritance,
1) The base-class object is constructed first 2) The derived-class constructor can pass base-class information to a
base-class constructor via a member initializer list or compiler call default
base class ctor implicitly. 3) The devived-class constructor should initialize the data member of it’s
own
If a base class has a destuctor, but sub class doesn’t have, compiler
will produce an implicit default destructor, and this implicit
default destructor will call base class destuctor.
If you define a subclass destructor, It will call base destructor
automaticlly, you don’t need to call it explicitly.
The question is, How can you make sure you sub class destructor
will be called if you use a base class pointer or reference, answer
is below:
Base class destructor should be virtual? Why ? When you use base class
pointer to a derive_class object, if the destructor is not virtual, It will only
call base class destructor. No dynamic binding (polymorphism) is involved
at all. Don’t call base desctructor explicitly, It will called automatically in
the reverse order of construction. And you should give a base desctructor a
definition, Or linker will report error it even you don’t call it in your source
code.
Assignment operator and copy ctor in inheritance:
Default Assignment operator and copy constructor inderived class which are implicitly produced by compilerwill call default base Assignment operator and copyconstructor.
If derived class has no new operation. Don’t need to definederived class Assignment operator and copy constructor,implicit one will call base one automatically
If derived class has new operation. You have to definederived class Assignment operator and copy constructor,it will not invoke Assignment operator and copyconstructor in base class any more. Inside, manuallyinvoke base class Assignment operator and copy ctor
Detail can be found in C++ primer p760. Syntax looks like below:
see effective C++ Item 16.
For copy ctor, just init list syntaxt. For assignment operator, use
two different methods depends on if base class declare its own
assignment operator(). Source code is below: