Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ references and return values

Tags:

c++

reference

I came across the following code:

class MyClass {

// various stuff including ...
   double *myarray;

   double &operator() (const int n){
      return myarray[n];
   }
   double operator() (const int n) const {
      return myarray[n];
   }

// various other stuff ...
}

So what is the practical difference in those two overloads of "()"? I mean, I know "The first one returns a reference to a double and the second one returns a double," but what does this mean practically? When would I use the one and when would I use the other? The second one (returning a double) seems pretty safe and straightforward. Is the first one ever dangerous in some way?

like image 646
bob.sacamento Avatar asked Apr 28 '16 15:04

bob.sacamento


1 Answers

They differ in that first one allows you to modify your array element, while the second one only returns value, so you can:

with: double &operator()

MyClass mm;
mm(1) = 12;

but also:

std::cout << mm(1);

with: double operator()

// mm(1) = 12; // this does not compile
std::cout << mm(1); // this is ok

also, returning a reference is more common when using operator[], like when you use std::vector::operator[].

btw. its common to have two versions of operator() - one const and second non-const. Const version will be called on const objects, while the second one on non const. But usually their signature is :

double& operator() (const int n);
const double& operator() (const int n) const;
like image 99
marcinj Avatar answered Sep 20 '22 18:09

marcinj