Search code examples
c++named-parameters

Wrong value printed when implementing chaining methods


I am given a specific main

int main() {

  Widget w;

  w.set(3).print().set(2).print();

  w.print();
}

and I am required to write a class Widget such that the program prints 3,2,2.

my best attempt sofar prints a disappointing 3,2,3 :/

class Widget{
public:
  Widget(){m_i =0;};

  Widget(int i){m_i =i;};

  Widget set(int i){
    this->m_i = i;
    return *this;
    };

  Widget print(){
    std::cout<<this->m_i<<std::endl;
    return *this;
    };
  int m_i;
};

int main() {

  Widget w;

  w.set(3).print().set(2).print();

  w.print();
}

any idea on how to solve this? Thanks to everyone who is willing to give some advice :)


Solution

  • What you're missing is that the object returned from your functions needs to be a reference e.g. a Widget&, not a Widget. Currently, you're returning a whole new copy from each set() or print() call, which means that any further changes to that object are never applied to the original w object.