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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
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; } |