Experimenting with Classes

I wrote this simple program to see how objects are instantiated and destroyed:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
using namespace std;

class A
{
    public:
        A(){cout<<"Initialized"<<endl;}
        ~A(){cout<<"Destroyed"<<endl;}
};

void print(A a)
{}

int main(void)
{
    A a;
    print(a);
}


I was surprised to see that output was:
Initialized
Destroyed
Destroyed

because I had expected it to be
Initialized
Initialized
Destroyed
Destroyed


Furthermore, if I changed the return type of the print function to A, the output showed another "Destroyed" statement.

However, If I changed the print function to
1
2
3
4
5
A print(A a)
{
    A b;
    return b;
}

the output was now:

Initialized
Initialized
Destroyed
Destroyed
Destroyed


It would be helpful if somebody could explain what's going in each of these three cases.
In your call to print(a) you're using the trivial, compiler-defined copy constructor to pass the argument to the 'print' function.

The signature and body of the implicitly-defined copy constructor in your case is
A( const A& otherA ) {};

If you were to explicitly define it as
A( const A& other ){cout<<"Initialized"<<endl;}

then you should get your expected result.
Thanks. It makes sense now.
Topic archived. No new replies allowed.