Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A pair of function call operators

Tags:

c++

operators

I have a function object A with a pair of function call operators (line 4 and 5):

class A{
public:
    A(int x) : _x(x){}
    int  operator () () const { return _x; }  // line 4
    int & operator () () { return _x; }   // line 5
private:
    int _x; 
};

Similar pair of call operators is used here. The question is: do I need line 4 at all? Does the operator defined at line 4 will ever by called? In the following case:

A a(7);
a() = 8;
cout << a() << endl;

always the operator from line 5 is called.

like image 383
cpp Avatar asked Mar 23 '23 22:03

cpp


2 Answers

Yes line 4 will be used, example:

 A a(3);  
 const A b(2);
 a(); // from line 5
 b(); // from line 4
like image 53
P0W Avatar answered Apr 06 '23 20:04

P0W


int  operator () () const { return _x; }

will be called when your object is const.

Also return a reference out is not the best design, it breaks data hiding rule, set/get functions are better choices. And you will be confused when your line 4 is called or when line 5 is called.

I suggest rewrite to:

class A{
public:
    explict A(int x) : x_(x) {}
    //int  operator () () const { return x_; }  // leave operator() for functor.
    operator int() const { return x_; }         // use conversion function instead 
    void setX(int x) { x_ = x; }
private:
    int x_;   //suggest use trailing `_`
};
like image 32
billz Avatar answered Apr 06 '23 18:04

billz