Why you do not initialize data members when you write a class?

Answer: When we declare/write a class, there is no memory allocation happens for data members of a class, so, we cannot store data into data members.

The memory gets allocated for data members only when we create objects of a class. So, initialization of the variable happens once object of the class get created.

Example:

In the below example, initialization of data member int a=2; cannot be done at the time of declaration.

class A{
	// int a=2; // compiler error,member variable can’t be initialized here
	 int b; //ok
public:
	 A(int _b){
		 this->b =_b;
		 cout<<"Object b initialized with value :"<b;
	 }
};


int main()
{	
	A obj(5);// initialize the object

	return 0;
}

NOTE: It's tested in Visual studio 8, where we get error.
Error	1	error C2864: 'A::a' : only static const integral data members can be initialized within a class.


Latest compilers like Visual studio 2015, don't flash error and the program works fine. 



Related Posts