A pair of function call statements

I have a function A object with a pair of function call statements (lines 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; }; 

A similar pair of call statements is used here . The question is, do I need line 4? Is the statement defined on line 4 by a call? In the following case:

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

the statement from line 5 is always called.

+4
source share
2 answers

Line 4 will be used, for example:

  A a(3); const A b(2); a(); // from line 5 b(); // from line 4 
+4
source
 int operator () () const { return _x; } 

will be called when your const object.

Also returning the link is not the best design, it violates the rule of hiding data, the set/get functions are the best choice. And you will be confused when your line 4 is called or when line 5 is called.

I suggest rewriting:

 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 `_` }; 
+3
source

Source: https://habr.com/ru/post/1495169/


All Articles