Array of Objects to call constructor
I am a relatively a new user to C++. I am not that good a software programming. Recently while reading I read a question which stated "If we create Arrays of Object then which Constructor will be called?" I have no idea about which constructor will be called in this question. First of all , can we call constructor by creating an array of objects?
Re: Array of Objects to call constructor
Yes, a constructor will be called. In C++ a constructor is called whenever we create an object of the class. In this case the Default Constructor if the class will be called.
Here is an example to clearify the above statement:
eg.
Code:
class temp
{
public:
temp();
...
};
void main()
{
temp t[6];
temp* x = new temp[5];
...
}
The first Array of objects t[6] calls the default constructor 6 times and the second will also call the default constructor but 5 times.
Re: Array of Objects to call constructor
Its by default that the C++ compiler will always call the default constructor first. As the name suggests its the default constructor and the compiler has no other options before the default constructor. And Yes, we can call default constructor by creating array of objects. Lets assume your class does not have a default constructor.
Code:
class def
{
int x;
public:
def(int a);
{
x=a;
}
};
int main()
{
def d[3];
..
..
}
The code line def d[3] will generate an error as there is no default constructor in the class.
Re: Array of Objects to call constructor
Even I was faced with a similar problem when I started learning C++. I never knew anything about array of objects, but was asked a question that can we call the default constructor by creating an array of objects. But now I know, yes we can. Infact when we create an array of objects in C++ the comipler will first call the default constructor. Thus we need a default constructor when we create an array of objects. If the default constructor is not present the compiler genarates an error.