destructor called twice for single object

Hi everyone,


(This is my first step to interact and need your help for learning cpp)

Inspite having only one object been created the destructor is been called twice.

have used the friend function,
can anyone please clarify my doubt.




#include<iostream>

using namespace std;
class student
{

int i;
friend void myfriend(student);
public:
student(int val) {i = val;}
~student() {cout<<"exiting"<<endl;}
};

void myfriend(student A) { cout<<"value="<<A.i<<endl; }
main()
{
student B(10);
myfriend(B);
}


output --./a.out


value=10
exiting
exiting
Thanks
santosh
Because function myfriend(student) creates a temporary object A, which must be destroyed when function finishes. You need to pass student by reference instead of by value:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include<iostream>

using namespace std;
class student
{

int i;
friend void myfriend(student&);
public:
student(int val) {i = val;}
~student() {cout<<"exiting"<<endl;}
};

void myfriend(student &A) { cout<<"value="<<A.i<<endl; }

int main()
{
student B(10);
myfriend(B);

}
Thanks Null!
Topic archived. No new replies allowed.