Bob
Bob

Reputation: 137

const member function modifies static object of own class

I saw multiple answered questions here about const member function allowed to modify static members. But not sure if my question falls into same category. In my example static member function modifies static object of the class, not static member of the class. Why my example works?

class Base
{
public:
    virtual const Base& fun (const Base& n) const = 0;
};

class Child : public Base
{
    int content;
public:
    Child(int i = 0) : content(i) {}
    const Base& fun (const Base& n) const;
};

const Base& Child::fun (const Base& n) const
{    
    static Child static_child;
    static_child.content = content + static_cast<const Child&>(n).content;
    cout << "static child content is " << static_child.content << endl;
    return static_child;
}

int main() {
    Child c(10);
    Base* b = &c;
    b->fun(*b).fun(*b);
}

The output will be

static child content is 20
static child content is 30

So const function successfully changed Child object. Moreover, on the second call it successfully changed this object. Thanks.

Upvotes: 2

Views: 61

Answers (1)

Barry
Barry

Reputation: 302767

So const function successfully changed Child object. Moreover, on the second call it successfully changed this object.

Neither call changed this. c.content remains 10 at the end of the program. The const qualification on the member function simply prevents you from modifying non-mutable, non-static members of the class instance itself. But you're not doing that - you're modifying a member of a local static. That's not something that's promised by const qualification and is, as you observe in your program, perfectly legal.

Upvotes: 3

Related Questions