How many times is the constructor called in the following code

How many times is the constructor called in the following code? and explain why.

Apple func()
{
Apple w;
Return w;
}

void main()
{
Apple x;
Apple y;
Apple z;
z = func();
}
Last edited on
0 because the code doesn't compile for me.

Is this just a question on your take-home quiz?
That's a matter of how smart the compiler optimizes the code. If the compiler is "dumb", there would be up to 4 constructor callings. A smart compiler would detect that the code does nothing and optimizes all stuff away.
shanno8 wrote:
How many times is the constructor called in the following code?


Why don't you just try it?

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

class Apple
{
public:
   Apple() { std::cout << "Hello!\n"; }
};

Apple func()
{
   Apple w;
   return w;   // Ahem: "return", not "Return"
}

int main()     // Ahem: "int main()", not "void main()"
{
   Apple x;
   Apple y;
   Apple z;
   z = func();
}

Last edited on
Topic archived. No new replies allowed.