Coming from JavaScript and Python, I'm trying to understand the nuances and purpose around C++ class constructors.
In the example below, why is it allowed to initialize attributes without a constructor?
class MyClass {
public:
int a = 1;
int b = 2;
};
Does the default constructor include the above definitions/initializations? What is the difference to the following two examples?:
1.
class MyClass {
public:
int a;
int b;
MyClass(){
a = 1;
b = 2;
}
};
- JavaScript/Python style (Is this even possible?)
class MyClass {
public:
MyClass(){
// Some kind of variable declaration and definition like:
// this.a = 1;
// this.b = 2;
}
};
To me having the option of initialization without a constructor sounds like an overkill and is confusing. In both Python and JavaScript one usually declares and initializes all variables from the constructor, and only from there only.
What is the best practice here?