Reputation: 2358
I have an array of objects:
Square sq[81];
I think it uses the default constructor to created each.
When I go though a for loop to initialize each, it calls the destructor for each Square
object in the array.
for (int k=0; k<9; k++) {
for(int j=0; j<9; j++) {
sq[count++] = Square(k, j);
}
}
When Square(k, j)
is called, is it deleting the object in sq[]
and creating a new one?
Upvotes: 1
Views: 2578
Reputation: 14685
Let's take the following sample program: http://codepad.org/S1iH4cWD
You can see several important steps:
main
, every object in Square sq[81]
is default constructed.sq
- which overwrites what was there - and then the temporary is destructed.main
, every object in Square sq[81]
is destructed, in reverse order of construction.So you had it almost right, except objects in sq will only be deleted after main
ends. It is the temporary (the object on the right side of the =
) that is destructed.
You may find this program helpful: http://codepad.org/JPE8uYVO It tracks different values for initialization versus assignment.
Upvotes: 0
Reputation: 385144
sq[count++] = Square(k, j);
When Square(k, j) is called, is it deleting the object in sq[] and creating a new one?
No.
Square(k, j)
creates a new temporary object and =
copies it into the old one. The temporary object is then destroyed as it is not longer required and goes out of scope.
BTW, you're not actually initialising anything in the loop (other than that temporary, I mean); you're just assigning, after-the-fact.
Upvotes: 9
Reputation: 477020
The elements of sq[]
aren't getting destroyed. Rather, you call the assignment operator of each element to assign it the new value Square(k, j)
, and the temporary object gets destroyed at the end of the assignment.
If you want to avoid the redundant default construction plus assignment, you could/should use a vector:
std::vector<Square> sq;
sq.reserve(81);
for (...) for (...) sq.push_back(Square(k,j));
If you further want to avoid the redundant temporary, use C++11 and say,
for (...) for (...) sq.emplace_back(k, j);
Upvotes: 3