Question

Why do we pass object of a class by reference. When I remove ampersand (&) I get following error.

"Copy constructor of class A may not have parameter of type A"

What does this mean? may be compiler is not considering given a copy constructor and using default one.If this is that case why default one is being called. In short why we use ampersand and what will happen? if we don't.

class A
{
public:
    A()
    {

    }



    A(A& tmp)
    {
        id = 2*tmp.id;
    }

public:
    int id;
};


int main()
{
    A obj;
    obj.id = 10;

    A obj1(obj);  
    cout << obj1.id;
}
Était-ce utile?

La solution

In C++, functions can take their parameters by value or by reference. If they take their parameters by value, that value must be copyable. If a copy constructor could take its parameter by value, then you would need a copy constructor to pass it its parameter, which would cause an endless loop.

Consider:

class MyInt
{
    int m;

public:

    MyInt(int i)
    {
        m = i;
    }

    MyInt(MyInt j)
    {
          j.m++;
          m = j.m;
    }
};

MyInt a(1);
MyInt b(a);

How can the compiler make this work? If it uses the default copy constructor, then why would it ever need to call my constructor? And if it uses my constructor, how does it prevent a.m from being incremented (which is clearly wrong, a should not be changed when it is passed by value) given that there's no code to give the constructor its own copy?

Autres conseils

Imagine what would happen if you don't:

1) The parameter is now passed by value to the copy constructor

2) In order to pass it by value it invokes the copy constructor

3) Goto 1

There are three ways to pass variables into functions/methods in C++: Pass by value, pass by address, and pass by reference (which is actually pass by address in a pretty wrapper). Pass by address and pass by reference are the simplest in that what gets passed into the underlying function/method is actually the memory address of where the object your passing lies. In order to pass by value, though, a copy of the source object must be made. That's the job of the copy constructor.

In order for the copy constructor to accept an instance of A, you must be able to make a copy of A, which requires a copy constructor, a recursive requirement.

It's the copy constructor that's called when you pass an object by value. So if your copy constructor requires the instance to be copied before it can run, how can it ever run?

The ampersand tells it to pass it by reference, so no copy is made.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top