user3425832
user3425832

Reputation: 111

const function in C++

const Integer opeator+(const Integer& left, const Integer& right){

    return Integer(letf.i + left.right);
}

Why does the function return non-const object Integer if type of function is const Integer?

Upvotes: 2

Views: 104

Answers (2)

Shoe
Shoe

Reputation: 76240

Why does the function return non-const object Integer if type of function is const Integer?

It does return a constant Integer, that is a copy of the Integer rvalue inside the function body. Also notice that you probably meant to say right.i instead of left.right, operator+ instead of opeator+ and left.i instead of letf.i.

Upvotes: 3

Vaughn Cato
Vaughn Cato

Reputation: 64298

The function is returning a copy of the Integer specified in the return statement. It doesn't matter if the value is const or not, since it is being copied into a const Integer.

It is similar to this:

const Integer result = Integer(5);

The Integer on the right side doesn't need to be const, since its value is being copied into result.

Upvotes: 3

Related Questions