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 ?
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With