Demonstrating the order in which constructors and destructors are called. : destructor « Class « C++ Tutorial

Home
C++ Tutorial
1.Language Basics
2.Data Types
3.Operators statements
4.Array
5.Development
6.Exceptions
7.Function
8.Structure
9.Class
10.Operator Overloading
11.Pointer
12.File Stream
13.template
14.STL Introduction
15.string
16.vector
17.list
18.bitset
19.set multiset
20.valarray
21.queue stack
22.deque
23.map multimap
24.STL Algorithms Modifying sequence operations
25.STL Algorithms Non modifying sequence operations
26.STL Algorithms Binary search
27.STL Algorithms Sorting
28.STL Algorithms Merge
29.STL Algorithms Min Max
30.STL Algorithms Iterator
31.STL Algorithms Heap
32.STL Algorithms Helper
C / ANSI-C
C Tutorial
C++
Visual C++ .NET
C++ Tutorial » Class » destructor 
9.3.4.Demonstrating the order in which constructors and destructors are called.
#include <string>
#include <iostream>
using std::string;
using std::cout;
using std::endl;

class MyClass 
{
public:
   MyClassint, string )// constructor
   ~MyClass();             // destructor
private:
   int objectID;
   string message; 
};

MyClass::MyClassint ID, string s )
{
   objectID = ID;
   message = s; 

   cout << "Object " << objectID << " constructor runs " << message << endl;
}
MyClass::~MyClass()

   cout << "Object " << objectID << " destructor runs " << message << endl; 
}

void createvoid );

MyClass first1"(global before main)" );

int main()
{
   MyClass second2"(local automatic in main)" );
   static MyClass third3"(local static in main)" );
   
   create()// call function to create objects

   MyClass fourth4"(local automatic in main)" );
   return 0;
}
void createvoid )
{
   cout << "\nCREATE FUNCTION: EXECUTION BEGINS" << endl;
   MyClass fifth5"(local automatic in create)" );
   static MyClass sixth6"(local static in create)" );
   cout << "\nCREATE FUNCTION: EXECUTION ENDS" << endl;
}
Object 1 constructor runs (global before main)
Object 2 constructor runs (local automatic in main)
Object 3 constructor runs (local static in main)

CREATE FUNCTION: EXECUTION BEGINS
Object 5 constructor runs (local automatic in create)
Object 6 constructor runs (local static in create)

CREATE FUNCTION: EXECUTION ENDS
Object 5 destructor runs (local automatic in create)
Object 4 constructor runs (local automatic in main)
Object 4 destructor runs (local automatic in main)
Object 2 destructor runs (local automatic in main)
Object 6 destructor runs (local static in create)
Object 3 destructor runs (local static in main)
Object 1 destructor runs (global before main)
9.3.destructor
9.3.1.A simple constructor and destructor.
9.3.2.Close stream in destructor
9.3.3.virtual destructor methods
9.3.4.Demonstrating the order in which constructors and destructors are called.
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.