Train Heartnet
Train Heartnet

Reputation: 815

How to dynamically update members that depend on other members?

Suppose I have a class MyClass:

class MyClass{
    private:
        vector<vector<float>> _vec;
    public:
        MyClass(vector<vector<float>> arg){
            _vec = arg;
            // shape is a 2-element vector where shape[0] = #elems in _vec 
            // and shape[1] = #elems in _vec[0]
            shape.push_back(_vec.size());
            shape.push_back(_vec.begin()->size());
        }
        vector<int> shape;
};

Now suppose I have a member function func of MyClass:

MyClass MyClass::func(){
    MyClass res(this->_vec);
    // delete the first element of `res._vec` 
    res._vec.erase(res._vec.begin());
    return res;
}

Now, if I do:

MyClass A = {{1, 2}, {3, 4}}; // A.shape[0] = 2, A.shape[1] = 2
MyClass B = A.func(); // B._vec is {{3, 4}} but B.shape[0] is still 2

Here, B._vec changes, but B.shape is not "updated" accordingly.

How can I dynamically update MyClass.shape as and when MyClass._vec changes? One way to do this is to instead make a member function MyClass.shape() which whenever called checks the current MyClass._vec. But is there a better way of doing this?

Upvotes: 0

Views: 73

Answers (1)

eerorika
eerorika

Reputation: 238401

How can I dynamically update MyClass.shape as and when MyClass._vec changes?

Write a function that updates shape, and call it whenever you change _vec.

But is there a better way of doing this?

Don't use shape member at all, but instead call _vec.size() and _vec.begin()->size() when you need those values. This way there is nothing to update, no redundant duplicate waste of memory, and the user of the class cannot break the apparently missing invariant.

Upvotes: 3

Related Questions