Hi to everyone,
I think my question might be elementary for most of you. I've recently begun to learn C++. Now I need to make an array of a class which needs to receive an initializer variable.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
class cStudent
{
public:
bool shouldBeGraduated;
int studentAge;
//cStudent(int age){}
cStudent(int age)
{
studentAge = age;
if (age > 18)
shouldBeGraduated = true;
else
shouldBeGraduated = false;
}
};
If I want to create a new instance, I should use this:
1 2
cStudent *st1;
st1 = new cStudent(15);
But I need to create an array of 500 instances of this class. I checked these, but I received just compile error
1 2
st1 = new cStudent[500](15);
st1 = new cStudent(15)[500];
Also I checked this one:
st1 = new cStudent[500]{ 12 }; // or { {12} };
In this case only the first element would receive the variable if the default constructor is uncommented. I don't know how to initialize an array of class instances just by one initializer.
Someone already answered your initial question. I noticed something else and it doesn't have anything to do with your question, and you might already know it, but in case you don't it could be helpful.
There is a different way to construct your class. It's slightly faster but in a class this simple it really makes no difference. It might be helpful to know in the future though.
Currently calling cStudent c(10); will do a few things. First the compiler will allocate space for 1 bool and one int but not assign any value, the same as calling
1 2
bool shouldBeGraduated;
int studentAge;
Then, the compiler gets to the body of the constructor and starts assigning values to your two variables. You can get around this in C++ with constructor initialization list.
Thank both of you for your responses. I checked the first solution and it worked properly. In the second response certainly will improve my codes in future large projects.