2

I have seen a Class like this:

class Vec2D {
    int i_;
    int j_;
    vector<double> vec;

public:
    Vec2D(int i, int j): i_(i),j_(j) {vec.assign(i_*j_,0);} 
    double & operator() (int i, int j){return ver[j_*i+j];} // overloading
    double * operator()(){return &(vec[0]); }               // ???
};

I understand double & operator() is for operator overloading.

As for double * operator()(){return &(vec[0]); }, obviously it is used to return a pointer to the first element, but I don't understand the mechanism, is it an overloading or a function pointer?

p.i.g.
  • 2,815
  • 2
  • 24
  • 41
lorniper
  • 626
  • 1
  • 7
  • 29
  • Possible duplicate of [Function call operator](http://stackoverflow.com/questions/4689430/function-call-operator) – Karoly Horvath Dec 09 '15 at 12:53
  • @KarolyHorvath it seems to me the link question is more concerned with "double operator()()" rather than double *operator()() – lorniper Dec 09 '15 at 12:56
  • @KarolyHorvath but it is confusing, the linked answer suggested it is used as a functor, is it both operator overloading and functor ? – lorniper Dec 09 '15 at 13:14
  • 1
    it's operator overloading that allows the object to be used as a functor. – Karoly Horvath Dec 09 '15 at 13:27

1 Answers1

4

operator() is the function call operator.

double * operator()(){return &(vec[0]); }  

Defines a function call operator for Vec2D that returns a double * and takes no input. You would use that in your code as

Vec2D foo;
double * bar = foo();

You then overload the function call operator with

double & operator() (int i, int j){return ver[j_*i+j];} 

This defines a function call operator for Vec2D that returns a double & and takes in 2 ints. It would be used like

Vec2D foo;
double & bar = foo(0, 0);
NathanOliver
  • 171,901
  • 28
  • 288
  • 402
  • it seems to me both are about operator overloading, the only differences are 1- "double *()(){}" returns a pointer. 2- the second parenthsis takes no arguments. ? – lorniper Dec 09 '15 at 13:00
  • @lorniper Yes these are overloaded functions. One takes two parameters the other none. Function overloading does not care about the return types. The function parameters have to be different to overload a function. – NathanOliver Dec 09 '15 at 13:02
  • Thanks ! So replace "double * operator()()" with "double * operator() (int i, int j)" would be illegal in this case ? – lorniper Dec 09 '15 at 13:04