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.
Yes line 4 will be used, example:
A a(3);
const A b(2);
a(); // from line 5
b(); // from line 4
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 `_`
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With