1

I'm just going through the basic OOP concepts in C++ and came across the following:

class A{
    public:
    int i(20); //line 1
};
int main()
{
  int j(20);
  cout<<j<<endl;
  A obj;
  cout<<obj.i<<endl;
}

I get the following error at line1 when compiling (tried in both gcc and MSVC++),

expected identifier before numeric constant

I know how to assign default value for a non-static member (which can be done from C++11 on wards in different ways), but I couldn't get the reason why only this kind of default value initialization is not possible as doing the same initialization (for normal variables) anywhere else is valid.

What could be the reason for such restriction?

Edited:

From the links and answer provided, it is because "it might read as function declaration in some cases. Because of this ambiguity, it is not allowed."

But consider the following case:

//global scope
struct B{
    int j;
};

int B = 10;

int object(B);

This is also a similar case, where int object(B) might be understood as a function object taking B object as argument and with int return type. I tried this in gcc and MSVC++ and object is treated as an int variable. Why it is not restricted in this case?

infinite loop
  • 1,309
  • 9
  • 19

1 Answers1

2

Using parentheses was deemed to be too confusing since it would read very similarly to a function declaration. Think about the case of a default constructor:

class A{
    public:
        int i();  // function declaration -- did you mean to
                  // use the default constructor instead?
};

There are other ways to do it though:

class A{
    public:
        int i = 20;
        int i{20};
        int i = {20};

};
Vaughn Cato
  • 63,448
  • 5
  • 82
  • 132
  • 1
    () does not works well in some cases. Think parameter-less constructor. If there were no problem with the (), the standard would not have adopted {} as an alternative way to construct objects. – Phil1970 Aug 12 '17 at 15:30
  • @Phil1970: Thanks, the default constructor is a good example. I've added that to my answer. – Vaughn Cato Aug 12 '17 at 15:39
  • But a parameter-less variable declaration is always treated as function declaration rather than an object in C++ ryt? `classtype obj()` , such things are always treated as function declaration. I understood the case @VaughnCato. But kindly go through my updated question – infinite loop Aug 12 '17 at 15:52
  • @infiniteloop: I believe many people would like to get rid of using parentheses for local variables if they could. – Vaughn Cato Aug 12 '17 at 17:52