Vector(const Vector& other) // Copy constructor { x = other.x; y = other.y;
Why is the argument a const?
Definition. Copying of objects is achieved by the use of a copy constructor and an assignment operator. A copy constructor has as its first parameter a (possibly const or volatile) reference to its own class type. It can have more arguments, but the rest must have default values associated with them.
Copy constructor is used to initialize the members of a newly created object by copying the members of an already existing object. Copy constructor takes a reference to an object of the same class as an argument.
A copy constructor cannot receive value by call by value method. While we invoke copy constructor an object of same class must be passed to it. But the object passed need to be copied in formal arguments.
Constructors and destructors can never be declared to be const . They are always allowed to modify an object even if the object itself is constant.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With