Hatted Rooster
Hatted Rooster

Reputation: 36503

Track member variable value change

I want to track when a particular member variable changes value so I can print it out. Now, the obvious solution to do this is to add a tracking function in the member's Set method, like so :

class Foo
{
public:
    Foo() {}

    void SetBar(int value)
    {
        //Log that m_bar is going to be changed
        m_bar = value;
    }
private:
    int m_bar; // the variable we want to track
};

The problem I'm facing is that I'm working on a huge project and some classes have a lot of methods that internally change member variables instead of calling their Setters.

m_bar = somevalue;

Instead of :

SetBar(somevalue);

So I'm wondering if there's a faster/more clean method to achieve what I want than just changing every m_bar = to SetBar(. An assignment operator overload only for that member variable perhaps?

Upvotes: 6

Views: 1588

Answers (1)

Micha Wiedenmann
Micha Wiedenmann

Reputation: 20853

If it is possible for you to change the data type of the member, you can change it to a logger type.

Example:

#include <iostream>

template <class T>
class Logger
{
  T value;

public:

  T& operator=(const T& other)
  {
    std::cout << "Setting new value\n";
    value = other;
    return value;
  }

  operator T() const
  {
    return value;
  }

};

class Foo
{
public:
    Foo() {}

    void SetBar(int value)
    {
        //Log that m_bar is going to be changed
        m_bar = value;
    }

private:

#if 1
    Logger<int> m_bar; // the variable we want to track
#else
    int m_bar; // the variable we want to track
#endif

};

int main()
{
  auto f = Foo();
  f.SetBar(12);
}

Online example at ideone.

Upvotes: 5

Related Questions