4

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?

asheeshr
  • 4,088
  • 6
  • 31
  • 50
  • 3
    side note : throw out that book and get some good one specified by SO, I've seen it before. Filled with crap practice, crap theory .... – Mr.Anubis Aug 22 '12 at 14:51
  • 1
    Agreed with Mr. Anubis. I have only read that page and I am already confused with the terminology... – David Rodríguez - dribeas Aug 22 '12 at 15:03
  • I am almost done with it. I agree with you on that. It skims over just about everything that actually needs a little thinking or depth. There arent any books recommended by SO explicitly for OOP with C++ [basic to intermediate], though. @Mr.Anubis – asheeshr Aug 22 '12 at 15:26
  • http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list – Mr.Anubis Aug 22 '12 at 16:52

2 Answers2

7

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
ForEveR
  • 55,233
  • 2
  • 119
  • 133
6

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

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
  • 1. I dont think he is referring to class objects which are class members, but POD variables. But i see your point. 2. Exactly my problem with this statement, "mandatory" ... – asheeshr Aug 22 '12 at 15:07
  • @AshRj that's why I specified "class-type", in case this isn't what he meant. – Luchian Grigore Aug 22 '12 at 15:07