Domanda

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?

È stato utile?

Soluzione

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

Altri suggerimenti

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
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top