about destroying objects

Why would the destructor call 4 times ?

the first one is for " ok " object i get that , the second is for lets object , and the third is for the date object inside people's class , but what about the 4th ?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
  #include<iostream>
#include<stdexcept>
#include<string.h>
#include<vector>
using namespace std;

class birthday{
	
		int day;
		int mounth ,year;
		public:
			birthday(int d,int m,int y)
			{
				day=d;
				mounth=m;
				year=y;
				
			}
			
			void print(){
				cout<<day<<"/"<<mounth<<"/"<<year;
			}
			void set(int x){
				year=x;
			}
			
			~birthday(){
			cout<<"I was here "<<endl;
		}
	
};

class people{
	string name;
	birthday date;
	
	public:
		people(string x,birthday y): date(y)
		{
			name=x;
		}
		
		void print(){
			cout<<name<<" ";
			date.print();
		}
		
		void set(int x){
			date.set(x);
		}
		
		
~people(){
			cout<<"I was here too"<<endl;
		}
};


int main(){
birthday ok(1,1,1);
people lets("Au",ok);

lets.print();


cout<<endl;

lets.print();



cin.get();
cin.get();
	return 0;

}
Line 38: You're passing birthday by value. A temporary instance gets constructed on the stack, then destructed when you're done calling lets' constructor at line 61.
oh , I forgot about the last in first out , so the birthday object inside of people gets destroyed first then the " lets " object , then the ok object , but the last one ?
Oh , I tried to pass it by reference and it's gone now , but I'm left with the last three , which is still confusing

"
I was here too

I was here

I was here

"

shouldn't it be :

I was here -- which is the object inside of people

I was here too -- which is lets object

I was here -- which is ok object ?
Last edited on
help guys , please.
An object which is contained by another object must be constructed before the containing object is finished being constructed and must be destructed before the containing object is finished being destructed.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>

struct A
{
    A() { std::cout << this << " constructed via A()\n"; }
    A(const A&) { std::cout << this << " constructed via A(const A&)\n"; }
    ~A() { std::cout << this << " destructed via ~A()\n"; }
};

struct B
{
    A a;

    B(const A& a) 
        : a(a) { std::cout << this << " constructed via B(const A&)\n"; }

    ~B() { std::cout << this << " destructed via ~B()\n"; }
};

int main()
{
    A a;
    B b(a);
}


http://ideone.com/tb5M5I

Notice how the destruction is done in the opposite order of construction. Keep in mind that one construction/destruction occurs inside another one.
Last edited on
Thank you ^^
Topic archived. No new replies allowed.