Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why the ISO C++ standard forbids the initialization for members? [closed]

Why i can't do that

class A {
  public:

    int x = 10;

  ...
};

and I have to do that ?

class A {
  public:

    int x;

  A(){
    x = 10;
    ...
  }

  ...
};

It's because C++ is trying to be more type safe than languages like C ? There are other reasons ?

like image 579
axis Avatar asked Dec 26 '22 16:12

axis


1 Answers

This has nothing to do with type safety, both examples are as safe.

When creating a language you need to define what is allowed and what is not. Since writing a blacklist would be a never-ending experience, a language is usually written in a white-list fashion, adding more and more possible things.

However, one should not allow things without clearly weighing the consequences. Whenever you want to allow something new, you need to check:

  • the ease of implementation
  • the interaction with other existing features and known probable extensions

Furthermore, it also means that there is more to learn for those wishing to use the language.

What you are asking for here is, however, relatively easy. It can be seen as the counterpart, for classes, to functions default arguments. This has been adopted in C++11 because it was the simplest way to guarantee a coherence of the default values when writing multiple constructors.

Personally, when using C++11, I recommend initializing all built-in types this way (if only to 0), much like I recommend initializing them when declaring local variables: this way you cannot forget to initialize them in one of the constructors.

like image 162
Matthieu M. Avatar answered Jan 13 '23 07:01

Matthieu M.