0

Why can't we use direct initialization within a class definition? For example, we can use a int z = 5; statement, but can't use int y(10); within the class definition below.

class Myclass {      
  int y(); // "error: expected ',' or '...' before numeric constant
  int z=5;
};
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
terto
  • 107
  • 4
  • 4
    Are you initializing a member variable named `y`, or declaring a member function `y` that takes no arguments and returns `int`? – Chris Apr 07 '23 at 20:06
  • 2
    What's the difference between the *function* declaration `int y();` and the *variable* definition `int y();`? If you can't tell, then how would the compiler? – Some programmer dude Apr 07 '23 at 20:06

2 Answers2

4

Per member initialization:

Non-static data members may be initialized in one of two ways:

  1. In the member initializer list of the constructor.
struct S
{
    int n;
    std::string s;
    S() : n(7) {} // direct-initializes n, default-initializes s
};
  1. 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.
struct S
{
    int n = 7;
    std::string s{'a', 'b', 'c'};
    S() {} // default member initializer will copy-initialize n, list-initialize s
};

So, you can use curly braces instead of parenthesis:

int y{10};

This will invoke direct initialization in this case:

T object { arg }; (2) (since C++11)

Direct initialization is performed in the following situations:
...
2) initialization of an object of non-class type with a single brace-enclosed initializer (note: for class types and other uses of braced-init-list, see list-initialization) (since C++11)

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
1

You should use value initialization here as @Remy Lebeau already mentioned. But you can also use the zero initialization described in the link: int y{};