0

I encountered unexpected behavior of default constructor. Having this class

class Data {
public:
    Data() { std::cout << "default ctor"; }
};

and calling

Data(x);

calls the default constructor, whereas calling

double x;
Data(x);

produces conflicting declaration 'Data x'.

I suppose it is some kind of vexing parse, but I don't see the logic behind that. Can you please explain how the g++ compiler sees that?

Jan Turoň
  • 31,451
  • 23
  • 125
  • 169
  • 2
    From the error message, it sounds like it seeing it as `Data x;`, a declaration of a new local variable named `x` of type `Data`. Is that what all that you are looking to know or is there more? – David Grayson Dec 21 '18 at 19:49
  • In the first example you’re creating a data variable named x. – vandench Dec 21 '18 at 19:50
  • To the downvoter: I really don't know how to put the question better if you encounter some strange behavior and don't even know what to search for. – Jan Turoň Dec 21 '18 at 19:55

1 Answers1

3

The issue here comes from way back when C was introduced. When you write

type(name);

it is parsed as declaring a variable like

type name;

That means in

Data(x);

you declare a variable named x that is of type Data and in

double x;
Data(x);

you declare a variable name x with the type double and then try to declare a variable named x with the type Data. You can't redefine a variable like that so you get an error.


If you want to just declare a temporary Data then the syntax would be

Data();
NathanOliver
  • 171,901
  • 28
  • 288
  • 402
  • To make this make sense so that you'll remember it as something rational and not some weird rule, start by imagining if you did `Data (*x)[10];`. What error would you expect? Now think through `Data (*x);`. What would make sense there? Then you're ready to think about `Data (x);` and lastly `Data(x);`. – David Schwartz Dec 21 '18 at 19:53
  • @DavidSchwartz Isn't `Data (*x)[10];` legal? `x` should be a pointer to an array of ten `Data`. – NathanOliver Dec 21 '18 at 19:55
  • Yes, precisely. And so `Data (*x);` is legal too. And so is `Data (x);`. Hence, in all these cases, you'll get precisely the error the OP got because they're all legal. – David Schwartz Dec 21 '18 at 19:56