Heykuki News

TopNewBestAskShowJobs
TopNewBestAskShowJobs
Why should the copy constructor accept its parameter by reference in C++?
1 point
shivajikobardan
3 years ago

    #include <iostream>
    #include <stdlib.h>
    using namespace std;
    class Complex
    {
    private:
        int real;
        int img;
    
    public:
        Complex()
        {
            real = img = 0;
        }
    
        Complex(int r, int i)
        {
            real = r;
            img = i;
        }
    
        Complex(Complex &c)
        {
            real = c.real;
            img = c.img;
        }
    
        void putComplex()
        {
            cout << real << "+i" << img<<endl;
        }
    };
    int main()
    {
        system("cls");
        Complex c1;
        Complex c2(3, 5);
        Complex c3(c2);
        c1.putComplex();
        c2.putComplex();
        c3.putComplex();
    
        return 0;
    }
    
I don't understand how copy constructor works. 1) What happens when complex c3(c2) is called? Step by step? obviously, in short real gets c2.real and img gets c2.img, I'm asking for in depth explanation of behind the scenes.

2) Step by step what will happen if I remove the "&" from "c" in copy constructor definition? I've heard that it goes to infinite recursion, but I don't understand how.

I'll be happy with any references to read or answers. https://stackoverflow.com/questions/2685854/why-should-the-copy-constructor-accept-its-parameter-by-reference-in-c I've already read this answer and failed to understand from there.

6 comments