Hailiang Zhang
Hailiang Zhang

Reputation: 18930

Can a C++ class function tell whether the class member reference to an outside class has been updated since last call?

Say I have two classes:

class A:

class A
{
    private:
        int _i; 
    public:
        A(int i){_i=i;}
        void update(int t){_i=t;}
        friend class B;
};

class B:

class B
{
    private:
        A &_a;
    public:
        void respond();
        B(A &); 
};

B::B(A & a)
:_a(a)
{}

void
B::respond()
{
    /*  
    if (a._i has been updated after last call of B::respond)
    {
        do something
    }
    else
    {
        do nothing
    }
    */
}

Is there anyway to achieve the task described in B::respond() in C++/C++11? What about _i is replaced by an pointer and B::respond() needs to respond to the content of a pointer?

Note that I can't modify class A.

Upvotes: 0

Views: 88

Answers (3)

Lukas Boersma
Lukas Boersma

Reputation: 1082

There are two ways to achieve this:

  1. Save the value of a._i in the B::respond() function and compare against that value in the next B::respond() call.
  2. Set some internal flag when calling A::update. When calling B::respond(), check for that flag and unset it.

Upvotes: 2

Dimitrios Bouzas
Dimitrios Bouzas

Reputation: 42929

You could keep the value of member variable A::_i as member of class B:

class B
{
    private:
        A &_a;
        int _i;
    public:
        void respond();
        B(A &); 
};

B::B(A & a)
:_a(a), _i(a.i)
{}

And consequently:

void
B::respond()
{
    if (_i != a._i) {
       // do something
    }
    else
    {
       // do nothing
    }
    _i = a._i;
}

Upvotes: 1

coder543
coder543

Reputation: 801

There is no way to directly see if a member has been accessed or updated, but there are indirect techniques. You could do something as simple as having a bool _i_updated; in class A. Then, inside of the A::update(int) function, simply set _i_updated = true; every single time the function is called. B::respond could check if _a._i_updated { and then set _i_updated = false every time it finds it to be true.

Upvotes: 1

Related Questions