1

making some simple tries about initializations (and default constructors) of object and primitives in C++, I found a behaviour that I don't understand, so I need an help.

Let's first talk about primitives types.

The code I tested is the following:

int main() {

    int i(5);
    cout<<i<<endl;

    int j();
    cout<<j<<endl;

    int k;
    cout<<k<<endl;

    return 0;
}

The result I get is this:

5
1
6487956

Obviously I was especting the first result (initialization in object style), and also the third (not initialized value), but the second? About the second, I was especting a default initialization, instead I get a warning that told "the address of 'int j()' will always evaluate as 'true'"... Infact the printed result is 1, but what kind of sintax is the empty round brackets near a primitive variable?

And now about the object, the case is similar... The code is:

class Pluto {
public:
    int a;
    int b;
    Pluto() {
        a = 0;
        b = 0;
        std::cout<<"Constructor call"<<std::endl;
    }
}

int main() {
    Pluto p();
}

I have a class with a default constructor inside which I've put a print to underline its invocation, then I declare an object with a similar sintax to the previous case, and I was expecting a call to the default constructor, while I get nothing in output, so the constructor was not called. In a next test, I try to access the members of the object, but I get the error "Field 'a' could not be resolved".

I'm sure that the anwer to my question is stupid and obvious, but now I really can't find it, so thanks to who will help me.

CorDiM
  • 13
  • 3

1 Answers1

2

j is a function, because anything that can be parsed as a function declaration, is parsed as one.

That's often called the “most vexing parse” of C++.

As a function it doesn't convert implicitly to void* (which is a data pointer), but it does convert to bool, and it's not null, so you get logical true, which is presented as 1 because that's the default presentation of boolvalues.

I.e., you get this conversion chain: functionfunction pointerboolean (which is true because the pointer is not null) and → presentation as 1.

You can change the presentation of boolean value by using the std::boolalpha manipulator, like cout << boolalpha;. Then instead of 1 you get the output true. I prefer this mode.


A simple solution where you want or need to specify default initialization, is to use curly braces:

int j{};
Cheers and hth. - Alf
  • 142,714
  • 15
  • 209
  • 331
  • 1
    As a pure technicality, with `int j();` there is no other possible parse (the grammar prevents parsing this as a variable declaration, so no ambiguity arises in the first place). – T.C. Dec 03 '16 at 11:23
  • It's obvious! I can't believe that I don't saw it before... I'm sorry for the trivial question, and thank you for the explanation, also for the printed value 1. – CorDiM Dec 03 '16 at 13:15