1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

construct and destroy

Discussion in 'C++' started by MartijnMulder, Sep 20, 2006.

  1. MartijnMulder

    MartijnMulder New Member

    Joined:
    Sep 20, 2006
    Messages:
    7
    Likes Received:
    0
    Trophy Points:
    0
    I created the following program to monitor the creation and destruction of instances:
    Code:
    #include<iostream>
    #include<math.h>
    
    //struct Object
    struct Object
    {
    
     //data member randomnumber
     int randomnumber;
    
     //constructor
     Object()
     {
      randomnumber=(int)rand()%1000;
      std::cout<<"\nObject created: "<<randomnumber;
     }
    
     //destructor
     ~Object()
     {
      std::cout<<"\nObject destroyed: "<<randomnumber;
     }
    
    };
    
    //struct AnotherObject
    struct AnotherObject
    {
    
     //data member object
     Object object;
    
     //constructor
     AnotherObject()
     {
      object=Object();
      object=Object();
      object=Object();
     }
    
    };
    
    //main
    int main(int argc,char**argv)
    {
     AnotherObject a;
     return 0;
    
    }
    and it gives the following output:

    Object created: 41
    Object created: 467
    Object destroyed: 467
    Object created: 334
    Object destroyed: 334
    Object created: 500
    Object destroyed: 500
    Object destroyed: 500

    I need the random numbers to differentiate between instances. I do not
    understand that instance '500' is destroyed twice and the first instance,
    '41' is destroyed never.
     

Share This Page