demaxSH
demaxSH

Reputation: 1825

why sometime a function return a const, or const reference

First, why return const? say I have

friend const MyVec operator-(const MyVec& left, const MyVec& right)

so is returning const makes me cannot do:

mva - mvb = mvc;

Second, why return const reference? if there is:

friend const MyVec& operator++(MyVec& v)

with const I cannot: (++mva) = mvc

if it is

MyVec& operator++(MyVec& v)

I can:++(++mva) // with increment twice.

am I understanding right?

Upvotes: 5

Views: 8110

Answers (2)

Zan Lynx
Zan Lynx

Reputation: 54393

There is not any good reason to return a const object. However, there are many good reasons to return pointers or references to const objects.

The program might have an object that is very expensive to copy, so it returns a reference. However, the object should not be changed through that reference. For example, it might be part of a sorted data structure and if its values were modified it would no longer be sorted correctly. So the const keeps it from being modified accidentally.

Arithmetic operator functions should not return const objects, because of exactly the problems in your question.

Dereferencing an iterator should return a const reference. That is if it is operating on a collection of const objects or possibly on a const collection. This is why class functions sometimes have two copies of a function with the second copy using a const on the function itself, like this:

T& operator[](size_t index);
const T& operator[](size_t index) const;

The first function would be used on non-const objects and the second function would be used for const objects.

Upvotes: 7

iammilind
iammilind

Reputation: 70094

Yes your understanding is correct. To avoid accidental assignments, one can return an object by const or const reference.

With operator -, you return an object by value. To avoid it getting edited accidently, one can return by const value, because anyways the object will be mostly a temporary.

For operator ++, conventionally it returns reference, however to avoid situations as (++ x) = y; you can return it by const reference.

Upvotes: 3

Related Questions