In the header file, define the base class:
class BaseClass { public: BaseClass(params); };
Then define the derived class as an inheriting BaseClass:
class DerivedClass : public BaseClass { public: DerivedClass(params); };
In the source file, define the BaseClass constructor:
BaseClass::BaseClass(params) {
By default, a derived constructor calls only the base default constructor with no parameters; therefore, in this example, the base class constructor is NOT automatically called when the derived constructor is called, but can be achieved by simply adding the syntax of the base class constructor after the colon ( : . Define a derived constructor that automatically calls its base constructor:
DerivedClass::DerivedClass(params) : BaseClass(params) { //This occurs AFTER BaseClass(params) is called first and can //perform additional initialization for the derived class }
The BaseClass constructor BaseClass called before the DerivedClass constructor, and the same / different params parameters can be redirected to the base class, if necessary. This can be nested for deeper derived classes. The resulting constructor should call EXACTLY ONE base constructor. AUTOMATICALLY destructors are called in REVERSE order, which was called by the constructors.
EDIT: There is an exception to this rule if you inherit from any virtual classes, usually to achieve multiple or diamond inheritance. Then you SHOULD explicitly call the base constructors of all the virtual base classes and explicitly pass parameters, otherwise they will only call their default constructors without any parameters. See virtual inheritance - constructor omissions
MasterHD May 12 '15 at 21:42 2015-05-12 21:42
source share