Why is the copy-constructor argument const?

前端 未结 8 2118
时光说笑
时光说笑 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: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.

提交回复
热议问题