0

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.

1
  • 3
    The default constructor is called implicitly if you don't explicitly call a constructor in the initialization list. Commented Sep 5, 2014 at 21:15

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

3 Comments

Specifically, according to C++11 the base will be default-initialised when the initialiser is not given ([C++11: 12.6.2/8]), and default-initialising an aggregate does nothing useful. By contrast, including Parent() in the ctor-initialiser will end up value-initialising its members ([C++11: 12.6.2/7]).
Downvoter, care to explain your objection? I'd be happy to improve on unclear or missing points (or just edit it yourself).
@T.C.: That makes sense, thanks. I've edited the post to reflect that. (Cleaning up the comments.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.