5

Possible Duplicate:
What is the scope of a while and for loop?

for (int32 segNo = 0; segNo < 10; ++segNo)
{
    my_Object cm;
}

Will the constructor and destructor of object cm be called on each pass through the loop?

If so, will the destructor be called before or after the loop variable is incremented?

Community
  • 1
  • 1

3 Answers3

8

Yes. And the destructor is called before the increment. I know, short answer, but that's it.

Nikos C.
  • 50,738
  • 9
  • 71
  • 96
6
#include <iostream>
struct Int {
  int x;
  Int(int value):x(value){}
  bool operator<(int y)const{return x<y;}
  void increment() { std::cout << "incremented to " << ++x << "\n";}
};
struct Log {
  Log() { std::cout << "Log created\n";}
  ~Log() { std::cout << "Log destroyed\n";}
};

int main()
{
    for(Int i=0; i<3; i.increment())
    {
        Log test;
    }
}

Result:

Log created
Log destroyed
incremented to 1
Log created
Log destroyed
incremented to 2
Log created
Log destroyed
incremented to 3
Yakk - Adam Nevraumont
  • 262,606
  • 27
  • 330
  • 524
5

The life of the object is inside of those curly braces.

The default constructor gets called on line 3 of your code. The destructor would be called when you get to the }. Then your loop is incremented, then the conditional is checked. If it returns true then another object is created (and the constructor called).

Boumbles
  • 2,473
  • 3
  • 24
  • 42