3

Why is it that when the g_Fun() executes to the return temp it will call the copy constructor?

class CExample 
{
private:
 int a;

public:
 CExample(int b)
 { 
  a = b;
 }

 CExample(const CExample& C)
 {
  a = C.a;
  cout<<"copy"<<endl;
 }

     void Show ()
     {
         cout<<a<<endl;
     }
};

CExample g_Fun()
{
 CExample temp(0);
 return temp;
}

int main()
{
 g_Fun();
 return 0;
}
TemplateRex
  • 69,038
  • 19
  • 164
  • 304

2 Answers2

7

Because you return by value, but note that calling the copy constructor is not required, because of RVO.

Depending on the optimization level, the copy-ctor might or might not be called - don't rely on either.

Community
  • 1
  • 1
Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
0

A copy constructor may called whenever we return an object (not its reference) because its copy needed to be created which is done by default copy constructor.

CExample g_Fun()
{
 return CExample(0);    //to avoid the copy constructor call
 }
Arpit
  • 12,767
  • 3
  • 27
  • 40
  • See http://stackoverflow.com/questions/12953127/what-are-copy-elision-and-return-value-optimization – Luchian Grigore Jan 24 '13 at 19:49
  • ya agree with you completely. from last few days the stack overflow changes my mind about copy constructor. the book is http://www.informit.com/store/c-plus-plus-without-fear-a-beginners-guide-that-makes-9780132673266 – Arpit Jan 24 '13 at 19:50
  • It's still not correct. The copy constructor can be called, it doesn't have to. – Luchian Grigore Jan 24 '13 at 19:54
  • but in this case he is creating the object then returning it. – Arpit Jan 24 '13 at 19:56
  • yes, and? Read up on RVO - http://stackoverflow.com/questions/12953127/what-are-copy-elision-and-return-value-optimization – Luchian Grigore Jan 24 '13 at 19:58