Initializing and Constructing Arrays of Objects in C++ -
this question has answer here:
- how use arrays in c++? 5 answers
when declaring array of objects, objects constructed @ initialization, or have constructed after initialization? here example of trying explain:
lets have class:
class object{ public: int x = 4; };
and array:
object objects[8];
if access of variables within objects, have construct objects first, or done in array? if did this:
cout << objects[4].x;
would print out 4?
in c++11 code valid, performs in-class initialization, , indeed, cout << objects[4].x;
print out 4
. in previous c++ versions (c++98/03), code invalid, , you'd need default constructor initialize variable x
, like
class object{ public: int x; object(int x = 4): x(x){} }
Comments
Post a Comment