0

The code below

#include <iostream>

class A
{
    public:

        int x;
        double y;

        A(int x_, double y_) : x(x_), y(y_)
        {
        }

        void display(void) const;
};

class B
{
    public:

        static A staticObject;
};

void A::display(void) const
{
    std::cout << x << ' ' << y << std::endl;
    B::staticObject.x = 42;
    B::staticObject.y = 3.5;
    std::cout << x << ' ' << y << std::endl;
}

A B::staticObject(19, 29.3);

int main(void)
{
    B::staticObject.display();
    return 0;
}

prints out

19 29.3
42 3.5

and this makes me wonder:

Is it always safe to let a const member function modify the object it is called from via other means?

Further, is there any worst-case scenario that could be prevented if that member function (here display) were not declared as const?

2
  • const member functions only apply to the current instance of the object. So when you get a non-const instance of the same object you can call non-const functions there. the const keyword only makes the this->pointer a const one. Commented Sep 15, 2016 at 13:28
  • What's the context of this design? Commented Sep 15, 2016 at 13:29

2 Answers 2

0

Your code is valid and works, because display() is const but only with respect to its containing class, A. This has no impact on its ability to modify fields accessed another way--in your case via non-const public access to the two fields.

However, this code is terrible and scary.

Sign up to request clarification or add additional context in comments.

Comments

0

what do you think as "safe"?

The only assumption you should make of a const member function is that it will not modify the current object it is in (this pointer). Constness though is not runtime enforced but during compilation time.

So when you "trick" your compiler with the help of static variables it cannot detect that you are actually accessing the same instance. The staticObject in B can also point to another A than the one it's being called from.

To be able to check it would require runtime checks which c++ does not do.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.