Why is object initialization different inside a struct?

Viewed 74

I have created a class Point, here is the corresponding hpp file.

#ifndef POINT
#define POINT
class Point
{
 protected:
 int x;
 int y;
 public:
 Point(int x = 10, int y = 10);
 void movePoint(int moveX, int moveY);
 void printCoordinates();
};
#endif

I noticed that in the main, I can declare an object and initialize it this way:

Point myPoint(1, 1);

If I want to create a structure containing two points, it won't let me initialize it this way, instead, I have to use curly brackets, this way:

struct segment
{
 Point point1 = {0, 0};
 Point point2 = {15, 15};
};

Why is that?

1 Answers

Because default member initializer (since C++11) only supports equal-sign initializer and braced initializer.

(emphasis mine)

Through a default member initializer, which is a brace or equals initializer included in the member declaration and is used if the member is omitted from the member initializer list of a constructor.

So you can

struct segment
{
 Point point1 = {0, 0};        // equal-sign initializer
 Point point2 = Point(15, 15); // equal-sign initializer
 Point point3 = Point{30, 30}; // equal-sign initializer
 Point point4 {45, 45};        // braced initializer
};

Point myPoint(1, 1); as default member initializer might cause ambiguity trouble with function declaration.

Related