2

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?

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
BaridunDuskhide
  • 107
  • 1
  • 5
  • imagine asking the compiler to parse `int x(n);` inside `template class S : public B` where it is not known whether `n` is an `int`, or a typename from `B` – M.M Aug 22 '21 at 12:13

1 Answers1

6

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.

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
  • 1
    More emphasis should be put on the ambiguity with function declaration here. It's actually the core reason why it's not allowed. – Marcin Poloczek Aug 22 '21 at 12:25