CONSTRUCTOR CALLS...

In this code:
Class X{
public:
X()
{
cout<<"Constructor\n";
}
~X()
{
cout<<"Destructor\n";
}
X(const X&){
cout<<"Copy Constructor\n";
}
};


X fun(){
return X();
}

main()
{
X b;
X a=fun();
}

Actual Output: Constructor
Constructor
Destructor
Destructor

Whereas I Expected output as: Constructor
Constructor
Destructor
Copy Constructor
Destructor
Destructor

{ first contructor for obj b; second for nameless object in fun() and third copy constructor}

Pls Explain.....
Compiler optimizations most likely, it probably figures out that you are just making a default constructed X and doesn't actually bother calling the function.
Return Value Optimization.

The X(); instance created in fun() is constructed directly in a's place rather than in a temporary location.
This is why initialization at the point of declaration is sometimes more efficient than assignment.
I was thinking if it's sane to rely on such behaviour or not. As for me, I've decided, that if it ever becomes important, such tests should be added to automatic testing system, which check it + should do on several compilers. Anyway, I guess it would be a bad construct which relies.

The following is a bit offtopic, but related -- for the case, when you don't want some constructor to work, I dare posting:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
struct noConstructor
{
private:
 //noConstructor(); // redundant anyway!
 noConstructor(const noConstructor&);
};

struct X
{
 X(){}

private:
 X(const X&);
};

/*
X get()
{
 return X(); // error: X::X(const X&) is private
}
*/

int main()
{
 X x0;
 //X x = get();

 //noConstructor nc; // error: no matching function for call to noConstructor::noConstructor()

 return 0;
}
Topic archived. No new replies allowed.