Constructors for arrays of objects

Let us consider a simple program
class A
{
   int a;
public:
   A(int num)
   {
      a = num;
   }
};
int main()
{
     A objects[10];
    ----
   -----
}
Now this program will not compile but gives an error in line 1 of main function where we are trying to define an array of A.
Why? The reason is, when an array of objects is to be created, these objects call default constructor of the class. As our class A does not have a default constructor, we get a compilation error.
One method of solving this problem is provide a default constructor to our class. That is a constructor of the type A()
Let us change

class A
{
   int a;
public:
   A(int num=0)
   {
      a = num;
   }
};
int main()
{
     A objects[10];
    ----
   -----
}
Now our program would compile. But you may ask where is the default constructor we are supposed to provide. The only constructor itself is the default constructor as it is provided with a default value of 0. In such cases, if a parameter is provided, then it is taken as num. If not, num is taken as 0.
And please note that this type of default value for parameter can be provided for any of the methods. 


Other method is provide an initialiser list to the arry

int main()
{
     A objects[10]={1,2,3,4,5,6,7,8,9,10};
    ----
   -----
}

Now our program compiles and objects[0] will be initialized with 1, objects[2] with 2 and so on. 

Or we can even provide the initializer list with constructor parameters
Here objects[0] will have a as 10 and objects of 0 will be initialized with 1. 

Comments

Popular Posts