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.
Suppose Parent
doesn't have a user-provided constructor, eg 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.