Why non-static data members of class cannot be given default values using '( )'?

126 Views Asked by At

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?

1

There are 1 best solutions below

4
Vaughn Cato On

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};

};