Custom constructor with arrays

Started by
1 comment, last by okonomiyaki 20 years ago
I have a quick question. The program is working fine but my log messages show something interesting. I have an array of custom objects, but I want to call a custom constructor. This is what I do:


object temp[5];

for(int i=0; i<5; i++)
    temp[i] = temp(i);

  
Is there a better way to do that? Anyway, it first says 5 default constructors were called (inital declaration). Then it says that the custom constructor was called, and then the destructor was called, and it does this 5 times. Is it something with tearing down the first instantiation and making a new object? The interesting part is that the destructor prints out information processed by the custom constructor.. so it has to be the same object. But the program runs fine! Just curious as to what's going on underneath. edit: Watch out for the [i] tags in your code blocks. [edited by - SiCrane on April 21, 2004 11:32:02 PM]
Advertisement
What''s happening is that the array gets constructed with 5 elements, each one default constructed. Then in your loop a temporary object is called with the constructor that accepts an int parameter. Then the assignment operator is called for the array element, assigning the value of the temporary to the element in the array. The temporary then gets destroyed (its destructor called).
Ah that totally makes sense now. I knew it was something like that, just couldn''t put my finger on it. I shoulda known about the assignment operation. just a little different than I''m used to (I usually use pointers).

Glad to know! Thanks a lot!

This topic is closed to new replies.

Advertisement