Search code examples
c++classc++11stdbind

Modifying an inherited member variable does not affect base class


I have the following two classes:

class A
{
public:

    A() : value(false) {}

    bool get() const
    {
        return value;
    }

protected:
    bool value;
};

class B : public A
{
public:

    void set()
    {
        value = true;
    }
};

Now I use them as follows:

B* b = new B;
std::shared_ptr<A> a(b);

auto func = std::bind(&B::set, *b);

std::cout << a->get() << std::endl;
func();
std::cout << a->get() << std::endl;

I expect a->get() to return true on the 2nd call, but func() hasn't modified its value. Why is that?


Solution

  • std::bind takes its paramters by value, so you are operating on copy of *b.

    You need to pass original object by std::ref:

    auto func = std::bind(&B::set, std::ref(*b));
    

    Live demo

    Or simpler form would be just pass pointer to bind:

    auto func = std::bind(&B::set, b);