Hello. I'm having some troubles. Please examine the following code:
#include <iostream>
using namespace std;
class myClass
{
public:
myClass() { cout << "in myClass default constructor.\n"; }
myClass(const myClass &ob) { cout << "in myClass copy constructor.\n"; }
~myClass() { cout << "in myClass destructor.\n"; }
};
myClass myFunc()
{
myClass ob;
return ob;
}
int main()
{
myClass myOb = myFunc();
return 1;
}
Output:
in myClass default constructor//called when ob is initialized
in myClass copy constructor//called when copying to the temporary returned object by myFunc()
in myClass destructor//called when myFunc() returns
in myClass destructor//called when main() returns
I have some questions:.
The line:
myClass myOb = myFunc();
1. In this line the copy constructor is not called, for the initialization of the myOb object? How is myOb initialized?
2. Why,when myFunc() has already returned, the destructor for the returned object is not called?
Thank You.
At Line 26 you call myFunction()
It enters the function at Line 18
At Line 19 you have declared myClass ob;
So it will create 'ob' using default constructor and you see the output statement of default constructor
Next step two steps happens at line 21,
First it copies 'ob' to 'myOb' , for coping it will use the copy constructor and you see the statement of copy constructor
Then it returns back to main and destructor the 'ob' is automatically called so you see statements of the destructor. Whenever an object is out of scope or when you delete an object the destructor is automatically called you don't have to explicitly call a destructor.
The last destructor statement you see is when you come out of main from 'myOb'