Interesting observation in copy constructor

The following code makes an interesting observation w.r.t copy constructors. copy ctor need not be called even when = is used in object definition, a neat optimization by calling the ctor directly..


#include
using namespace std;

class Foo{
public:
Foo(const Foo&){ cout << "in cpy ctor" << endl; }
Foo(int a) { cout << "in ctro:" << a << endl;}
};

int main()
{
Foo f = 1; // Does this call copy constructor??
Foo f2(3);
Foo g = f;
}


When Executed :
in ctro:1
in ctro:3
in cpy ctor

No comments: