Accept an object by reference in copy constructor in C++ ?


Is it necessary to accept a reference in copy constructor?

Yes, It is necessary to accept an object by reference in copy constructor because if an object is accepted by value then the copy constructor will fall in recursive loop.

//C++ program for copy constructor:

#include<iostream>
using namespace std;
class copyDemo
{
int x;
public:
       copyDemo(copyDemo v) //taking object as value
        {
         x=v.x;
        }
};

int main()
{
copyDemo c;
copyDemo c1(c);// this will invoke copy constructor
return 0;
}

//explanation

The statement copyDemo c1(c);  causes the copy constructor to get called.
The value of c is passed If the copy constructor collects c in v by value then
the statement  copyDemo v would become as
copyDemo v=c;
here v is getting created and initialized so again copy constructor will get called and will go in recursive call loop.

//C++ program for copy constructor

1 comment:

  1. Is it necessary to accept/receive/collect an object by reference in copy constructor in C++ ?
    Is it necessary to accept/receive/collect an object by reference in copy constructor in C++ ?
    Is it necessary to accept/receive/collect an object by reference in copy constructor in C++ ?
    Is it necessary to accept/receive/collect an object by reference in copy constructor in C++ ?
    Is it necessary to accept/receive/collect an object by reference in copy constructor in C++ ?
    Is it necessary to accept/receive/collect an object by reference in copy constructor in C++ ?
    Is it necessary to accept/receive/collect an object by reference in copy constructor in C++ ?

    ReplyDelete