My college course book states that :
When a constructor is declared for a class, initialization of the class objects becomes mandatory.
Link to the specific page of the book.
We can declare do-nothing constructors and hence initialization is most certainly not mandatory, or is it?
If not, does the author mean that stylistically we should initialize class members if we explicitly declare constructors, that is, is it meant as a rule or a guideline?
We must initialize members in constructor if:
And should initialize members if we dont't want any strange behaviour if:
When a constructor is declared for a class, initialization of the class objects becomes mandatory.
It's true, but initialization doesn't have to be explicit. Note the term objects
instead of member
.
Class-type members will be default-intialized if you don't explicitly do it.
class A {};
class B
{
A a;
int x;
B()
{
//a is initialized here, although you didn't do it explicitly
//x is not initialized, nor is it mandatory to initialize it
//but x is not an object
}
};
Of course, "mandatory" is a strong word. It's not mandatory to initialize x
, but you can't do anything with it until you do. :)
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