Calling a constructor to reinitialize variables doesn't seem to work?

Posted by Matt on Stack Overflow See other posts from Stack Overflow or by Matt
Published on 2010-03-27T20:39:31Z Indexed on 2010/03/27 20:43 UTC
Read the original article Hit count: 133

Filed under:
|

I wanted to run 1,000 iterations of a program, so set a counter for 1000 in main. I needed to reinitialize various variables after each iteration, and since the class constructor had all the initializations already written out - I decided to call that after each iteration, with the result of each iteration being stored in a variable in main.

However, when I called the constructor, it had no effect...it took me a while to figure out - but it didn't reinitialize anything!

I created a function exactly like the constructor - so the object would have its own version. When I called that, it reinitialized everything as I expected.

int main()
{
 Class MyClass()

 int counter = 0;

 while ( counter < 1000 )
 { stuff happens }

 Class(); // This is how I tried to call the constructor initially.
          // After doing some reading here, I tried:
          // Class::Class(); 
          // - but that didn't work either 
 /* Later I used...
 MyClass.function_like_my_constructor; // this worked perfectly
 */
}

...Could someone try to explain why what I did was wrong, or didn't work, or was silly or what have you? I mean - mentally, I just figured - crap, I can call this constructor and have all this stuff reinitialized. Are constructors (ideally) ONLY called when an object is created?

© Stack Overflow or respective owner

Related posts about c++

Related posts about constructor