C++ Constructor & Destructor

The following piece of code shows the birth and death of an object

under various circumstances: when the constructor and destructor are called.

 

#include <iostream>

using std::cout;

using std::endl;

 

class CScopeTest

{

private:

      static int count;

      int index;

public:

      CScopeTest() {index = count++; cout<<"ctor"<<index<<endl;}     

      ~CScopeTest() {cout<<"dtor"<<index<<endl;}           

     

};

int CScopeTest::count = 1;

 

void f()

{

    CScopeTest t3;

}

 

CScopeTest t1;

 

int main()

{

    cout<<">> main()\n";

    CScopeTest t2;

    static CScopeTest t4;

    f();

    cout<<"<< main()\n";

    return 0;

}

 

Result:

ctor1
>> main()
ctor2
ctor3
ctor4
dtor4
<< main()
dtor2
dtor3
dtor1

Advertisements
Post a comment or leave a trackback: Trackback URL.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: