Why is the copy-constructor argument const?

前端 未结 8 2027
时光说笑
时光说笑 2020-11-29 00:30
 Vector(const Vector& other) // Copy constructor 
 {
    x = other.x;
    y = other.y;

Why is the argument a const?

相关标签:
8条回答
  • 2020-11-29 01:10

    Its not specific to copy constructor. In any function if you are not going to modify the internal state of the object then object will be passed as const.

    Vector(const Vector& other) 
    {
         //Since other is const, only public data member and public methods which are `const` can be accessed.
    }
    
    0 讨论(0)
  • 2020-11-29 01:11

    when we try to copy one object into another using copy constructor,we need to maintain the original copy of original object (which we are copying) so while passing object we make it constant and we pass it as a by reference.

    0 讨论(0)
  • 2020-11-29 01:17

    In order to not be able to change other (by accident)?

    0 讨论(0)
  • 2020-11-29 01:20

    The idea of a copy constructor is that you are copying the contents of the other object into the this object. The const is there to ensure that you don't modify the other object.

    0 讨论(0)
  • 2020-11-29 01:22

    Because you are not going to modify the argument other inside the copy ctor as it is const.

    When you did x = other.x it essentially means this->x = other.x. So you are modifying only this object just by copying the values from other variable. Since the other variable is read-only here, it is passed as a const-ref.

    0 讨论(0)
  • 2020-11-29 01:23

    You've gotten answers that mention ensuring that the ctor can't change what's being copied -- and they're right, putting the const there does have that effect.

    More important, however, is that a temporary object cannot bind to a non-const reference. The copy ctor must take a reference to a const object to be able to make copies of temporary objects.

    0 讨论(0)
提交回复
热议问题