wizurd
wizurd

Reputation: 3739

Initialize parent class with empty constructor in initializer list?

Are there any dangers in not initializing an empty constructor parent class in the child initialization list?

Example:

class Parent
{
  public:
    Parent(){}
    ~Parent(){}
};

class Child : public Parent
{
  public:
    Child(): Parent()
    {}
    ~Child(){}
};

Reason for the question: I often see code where a "Parent" class with an empty ctor is not initialized in the child ctor initialization list.

Upvotes: 0

Views: 183

Answers (1)

Kerrek SB
Kerrek SB

Reputation: 477040

Suppose Parent doesn't have a user-provided constructor, e.g. if it is an aggregate:

struct Parent
{
    int x;
    int get_value() const { return x; }
};

Now there's a difference (cf. [dcl.init]/(8.1)), since value-initialization of Parent will zero-initialize the member x, whereas default-initialization will not:

struct GoodChild : Parent { GoodChild() : Parent() {} };

struct BadChild : Parent { BadChild() {} };

Therefore:

int n = GoodChild().get_value(); // OK, n == 0

int m = BadChild().get_value();  // Undefined behaviour

Upvotes: 1

Related Questions