Saturday, 24 November 2018

Initialization of class data members in C++

There are two ways to initialize data members of class in constructor:
  • In the initialization list of constructor 
  • In the body of constructor
In the initialization list of constructor :

class student {
   int id;
   string name; 
   public :
     student(int a, string b) : id(a), name(b) {}
};

text highlighted in yellow is initialization list.

In the body of constructor :

class student {
   int id;
   string name; 
   public :
     student(int a, string b) {
        id = a;
        name = b;
      }
};
Both ways will work fine but there is a very important difference between both. To understand this difference let us first understand how objects are created.

When an object of class is created, its constructor is called which in turn first allocates memory and then initialize the data. When memory is allocated, for sure each data member has got some value in its memory which can be some real value or some garbage value.

If we use first method to initialize data members, it will initialize data members while allocating memory whereas in the second method, it will first allocate memory and all the data members will have some garbage value and then in the body of constructor, it initialize data members.

Hence first method is better than second one as it is initializing while allocation and the latter does these two parts separately.

This is why constant data members has to be initialized in the initialization list itself. They can't be initialized in the body of constructor because constant data members can be initialized just once. If we write them in body of constructor it has already been initialized by some garbage value and hence compiler does not let you assign some another value.

e.g.


class student {
   const int id;
   string name; 
   public :
     student(int a, string b) {
        id = a; // ERROR
        name = b;
      }
};

This piece of code will not compile.We will have to initialize id in the initialization list itself.

No comments:

Post a Comment

what is array

Array is one of the simplest and most  sophisticated data structures. In array data is stored at contiguous memory locations. E.g. say you h...