constructor per copy in c ++

0

Good day! I wanted to make a query: I'm new to seeing c ++, but I've seen that when they create objects, when making the constructor by copy, when they define the method, what happens is the memory position of the object they copy, and from there they work with that. I wanted to ask why when it is defined write as if the memory position of the object were passed, instead of passing the object to itself, and then in the main it is shown as if the object itself were passed. For example:

    class vector {
    private:
        float x,y,z;
    public:
        vector();
        vector(float, float, float);
        vector(const vector &);
        float prim() const;
        float seg() const;
        float ter() const;
    }
    vector::vector() {
        x = 0;
        y = 0;
        z = 0;
    }

    vector::vector(float x2, float y2, float z2) {
        x = x2;
        y = y2;
        z = z2;
    }
    vector::vector(const vector &v) {
        x = v.prim();
        y = v.seg();
        z = v.ter();
    }

float vector::prim() const
{
    return x;
}

float vector::seg() const
{
    return y;
}

float vector::ter() const
{
    return z;
}
    int main(){
     vector a(4,2,1);
     vector b(a);
     return 0;
    }
    
asked by F. Riggio 21.09.2017 в 13:52
source

1 answer

1
  

when they define the method what happens to them is the memory position of the object they copy, and from there they work with that.

The memory position is not passed, but a reference (we are in C ++, not in C).

And this is done to avoid creating recursive copies of the object. If someone did this:

struct Test
{
  int var;

  Test(Test t)
  {
    var = t.var;
  }    
};

At the moment when the copy constructor had to be called, a temporary copy of the original object would have to be made beforehand to store it in t . When creating that copy, the copy constructor would be entered again and this would originate another copy, which would cause another call to the constructor ... and so on until the stack overflows.

When using references, copies are avoided and with this, this problem of recursive call.

Additionally, the reference is marked as constant to avoid that, by mistake, the original object may be modified.

    
answered by 21.09.2017 в 13:56