Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the copy constructor called when we return an object from a method by value

why copy constructor is called when we return an object from a method by value. please see my below code in that i am returning an object from a method while returning control is hitting the copy constructor and then returning. i am not understood following things:
1) why it is calling copy constructor.
2)which object is passing implicitly to copy constructor,
3)to which object copy constructor will copy the content,
4)what is the necessity of copying the object content while returning. so plz help.

#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;

class ClassA
{
   int a, b;
     public:
   ClassA()
   {
     a = 10;
     b = 20;
   }
   ClassA(ClassA &obj)
   {
    cout << "copy constructor called" << endl;
   }
 };

 ClassA function (ClassA &str)
 {
  return str;
 }

 int main ()
 {
   ClassA str;
   function(str);
   //function(str);
   return 0;
 }
like image 316
nagaradderKantesh Avatar asked May 24 '13 09:05

nagaradderKantesh


People also ask

Why is copy constructor called?

When is a Copy Constructor Called in C++? A copy constructor is a member function that initializes an object using another object of the same class. The Copy constructor is called mainly when a new object is created from an existing object, as a copy of the existing object.

How copy constructor is related to an object returned by a function?

The copy constructor is invoked. It takes a reference to the local variable. It uses this reference to copy everything into the new object that will be used as the return value.

Why copy constructor is called when we pass an object as an argument?

Because passing by value to a function means the function has its own copy of the object. To this end, the copy constructor is called.

Why is a class's copy constructor called when an object of that class is passed by value into a function?

Why is a class's copy constructor called when an object of that class is passed by value into a function? Because the parameter variable is created in memory when the function executes, and is initialized with the argument object. This causes the copy constructor to be called.


1 Answers

The copy constructor is called because you call by value not by reference. Therefore a new object must be instantiated from your current object since all members of the object should have the same value in the returned instance. Because otherwise you would be returning the object it self, which would be returning by reference. In this case modifying the reference object would change the original as well. This is generally not a behavior one wants when returning by value.

like image 138
hetepeperfan Avatar answered Oct 27 '22 20:10

hetepeperfan