Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Const and Non-Const Operator Overloading

I have a topic I'm confused on that I need some elaborating on. It's operator overloading with a const version and a non-const version.

// non-const double &operator[](int idx) {     if (idx < length && idx >= 0) {         return data[idx];     }     throw BoundsError(); } 

I understand that this lambda function, takes an index and checks its validity and then returns the index of the array data in the class. There's also a function with the same body but with the function call as

const double &operator[](int idx) const 

Why do we need two versions?

For example, on the sample code below, which version is used in each instance below?

Array a(3); a[0] = 2.0; a[1] = 3.3; a[2] = a[0] + a[1]; 

My hypothesis that the const version is only called on a[2] because we don't want to risk modifying a[0] or a[1].

Thanks for any help.

like image 411
James Wilks Avatar asked Oct 08 '13 01:10

James Wilks


People also ask

What is const in operator overloading?

Overloading on the basis of const type can be useful when a function returns a reference or pointer. We can make one function const, that returns a const reference or const pointer, and another non-const function, that returns a non-const reference or pointer.

What is const operator C++?

In C++ programming, when we implement the methods for classes, we usually add const specifier to make sure that the members of the class instance will not be modified by the method.


2 Answers

When both versions are available, the logic is pretty straightforward: const version is called for const objects, non-const version is called for non-const objects. That's all.

In your code sample a is a non-const object, meaning that the non-const version is called in all cases. The const version is never called in your sample.

The point of having two versions is to implement "read/write" access for non-const objects and only "read" access for const objects. For const objects const version of operator [] is called, which returns a const double & reference. You can read data through that const reference, but your can't write through it.

like image 200
AnT Avatar answered Sep 23 '22 15:09

AnT


To supply a code example to complement the answer above:

Array a(3); a[0] = 2.0;  //non-const version called on non-const 'a' object  const Array b(3); double var = b[1];  //const version called on const 'b' object  const Array c(3); c[0] = 2.0;  //compile error, cannot modify const object 
like image 44
echo Avatar answered Sep 20 '22 15:09

echo