Constructors And Initialization Of Derived Classes

Constructors

** Example **

class Base
{
public:
    int m_nValue;
 
    Base(int nValue=0)
        : m_nValue(nValue)
    {
    }
};
 
class Derived: public Base
{
public:
    double m_dValue;
 
    Derived(double dValue=0.0)
        : m_dValue(dValue)
    {
    }
};
 
int main()
{
  Derived cDerived(1.3);
 
  return 0;
}

What happens when cDerived is instantiated:

  1. Memory for cDerived is set aside (enough for both the Base and Derived portions).
  2. The appropriate Derived constructor is called
  3. The Base object is constructed first using the appropriate Base constructor
  4. The initialization list initializes variables
  5. The body of the constructor executes
  6. Control is returned to the caller

Initializing base class members

C++ prevents classes from initializing inherited member variables in the initialization list of a constructor.

C++ gives us the ability to explicitly choose which base class constructor to be called.

Example
class Derived: public Base
{
public:
double m_dValue;

Derived(double dValue=0.0, int nValue=0)
: Base(nValue), // Call Base(int) constructor with value nValue!
m_dValue(dValue)
{
}
};

Inheritance Chains

Example

#include <iostream>
using namespace std;
 
class A
{
public:
    A(int nValue)
    {
        cout << "A: " << nValue << endl;
    }
};
 
class B: public A
{
public:
    B(int nValue, double dValue)
    : A(nValue)
    {
        cout << "B: " << dValue << endl;
    }
};
 
class C: public B
{
public:
    C(int nValue, double dValue, char chValue)
    : B(nValue, dValue)
    {
        cout << "C: " << chValue << endl;
    }
};
 
int main()
{
    C cClass(5, 4.3, 'R');
 
    return 0;
}

Constructors can only call constructors from their immediate base class.

Destructors

When a derived class is destroyed, each destructor is called in the reverse order of construction. In the above example, when cClass is destroyed, the C destructor is called first, then the B destructor, then the A destructor.

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-Share Alike 2.5 License.