Aditya
Aditya

Reputation: 417

Why does the copy constructor (of a C++ class) get called when a function returns?

Here is a fragment of a program:

cls fun(cls a)
{
     cls v;
     v = a.scale(2.0);
     return v;
}
int main()
{
     cls a(0.0,1.0,2.0);
     cls a2;
     a2 = fun(a);
     return 0;
}

In the above code assume that the class definition of the class "cls" has the constructor function and the "scale" function already defined. My doubt is in the main function we have instantiated the object a2 and after that we are assigning it to the return value of the function. So, why will the copy constructor get called in this case? (I am following some resource to understand the OOP using C++ and it is mentioned over there that in the above case the copy constructor gets called.)

Also, in the above code if I write:

cls a2 = fun(a);

Then, from my understanding, the copy constructor must be called (because we are instantiating a2 as a copy of something). Now, the fun(a) returns a temporary object, but the parameter of the copy constructor function takes a reference value since we cannot take the reference value of a temporary object, shouldn't this give an error?

Upvotes: 0

Views: 147

Answers (1)

Bathsheba
Bathsheba

Reputation: 234655

The compiler generated copy constructor takes a const reference as the parameter.

An anonymous temporary is allowed to bind to a const reference, so compilation passes.

Note that the implied value copy created by return v; is elided in later C++ standards.

Upvotes: 1

Related Questions