Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it mandatory to initialize class members if a constructor is explicitly defined?

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?

like image 283
asheeshr Avatar asked Dec 11 '22 23:12

asheeshr


2 Answers

We must initialize members in constructor if:

  1. Member has no default constructor.
  2. Member is reference/const-reference.
  3. Member is const. (Thanks to Mr.Anubis)

And should initialize members if we dont't want any strange behaviour if:

  1. Member is pointer
  2. Member is standard pod-type
like image 80
ForEveR Avatar answered Dec 14 '22 11:12

ForEveR


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. :)

like image 25
Luchian Grigore Avatar answered Dec 14 '22 13:12

Luchian Grigore