Ed King
Ed King

Reputation: 1863

Is it okay to modify a private member variable in an overridden method?

I'm getting frustrated with some odd behaviour and wonder whether I'm assuming something is fine when it's not. Is the following valid, i.e., can I modify m_flag in the overridden foo()? If so, something more sinister is happening, as I'm seeing m_flag as one thing and then only report its something else when I come to step through B::foo() when I know I haven't actively modified it.

class A {
public:
    virtual void foo() {
       // Do something.
    }
};

class B : public A{
public:
    virtual public void foo() {
        m_flag++;
    }
private:
    volatile uint8_t m_flag;
};

Upvotes: 0

Views: 88

Answers (2)

risingDarkness
risingDarkness

Reputation: 708

can I modify m_flag in the overridden foo()?

No. Because in the code you posted, class B does not inherit from class A. This means, there is no foo() to override.

class B does itself declare m_flag so you are fine modifing it in B::foo().

Please note that, as others have already stated, the increment operator on bool is deprecated.

Upvotes: 1

James Kanze
James Kanze

Reputation: 153977

Yes, but...

The type of m_flag is bool. Incrementing a bool was deprecated from the start, and has somewhat surprising semantics: it is the equivalent of setting the value to true.

(The reason for this strange behavior dates back to the early days of C, when there wasn't any bool type. One particular idiom was something like:

int argsSeen = 0;
//  ...
if ( arg1Present ) {
    argsSeen ++;
    //  ...
}
//  And so on for each of the possible args...
if ( argsSeen ) {
    //  whatever...
}

The idea was that by allowing the incrementation, code using this idiom could change argsSeen to type bool, and not break.

Upvotes: 1

Related Questions