I have declared an int Array in my class and tries to initialize it through Constructor Initialization list but found error in doing so because this is not allowed in C++.
*********************************************************************************
I have written the following code.
*********************************************************************************
class A
{
private:
int Arr[3];
public:
A():Arr[0](1),Arr[1](2),Arr[2](3){}//produces error
}
*********************************************************************************
First we will discuss the behaviour of Array in C++
Whenever you declared an array lets say int Arr[3]; it will call the default constructor against each index like this...
Arr[0] //calls default constructor
Arr[1] //calls default constructor
Arr[2] //calls default constructor
if we have size N then it will call its default constructor N times.
*********************************************************************************
The above code produces error because whenever you declared an array you should initilize it also like this...
int Arr[]={1,2,3} //OK
int Arr1[3];
Arr[]={1,2,3};//Error
what we are doing is declaring and initializing it separately which is wrong.
Conclusion:
C++ does not support initialization of Arrays in the Constructor Initialization List because that is both syntactically and logically incorrect.If you have N size of items in you array you will never initiliaze it in Constructor Initialization List.
Subscribe to:
Post Comments (Atom)
It's informative one.
ReplyDeleteWhat would happen if the is user-defined?
Is this the same for user-define types?
Please clear my confusion.
Sam