I am executing the following code C++ code on
(Ubuntu 5.4.0-6ubuntu1~16.04.4) 5.4.0 20160609
class x {
public :
int data ;
x(int v) {cout<<"1 args constr\n" ; data = v ;}
x(const x& o) {cout<<"copy constr\n" ;}
x &operator=(const x&o) {cout<<"assignment opr\n" ;}
~x() {cout<<"destr\n" ;}
} ;
x fun() {
cout<<"in func\n" ; //#1
x o(-19) ; //#2
cout<<"returning...\n";
return o ; //#3
}
main() {
x ob = fun() ; //#4
cout<<ob.data<<endl ;
}
And getting the following output: in func 1 args constr returning... -19 destr
What I am not able to understand is :
- why are the constructor and destructor called ony once
- why is the copy constructor not invoked when I am returning by value
As per my understanding, ob is created in the scope of main. Thus the constructor and destructor for ob should be called in the scope of main.
Likewise, o is created in the scope of fun. And thus there should be one constructor and destructor invocation for o in the scope of fun