Question

I'm having this problem with C++ classes. I would like to get pointer to myBar object and store it in quxBar. The reason is I would like to be able to check the value using quxBar->getX() but I would also like to prevent from accidentally modyfing it from Qux so I tried using Bar const*.

class Bar
{
private:
    int x;
public:
    void setX(int X) { x = X; };
    int getX(){ return x };
}

class Foo
{
private:
    Bar *myBar;
public: 
    Bar const* getPointerToBar(){ return myBar; };            
}

class Qux
{
    void myMethod();
    Bar const* quxBar;
    Foo *mainFoo;    
}

void Qux::myMethod()
{
    quxBar = mainFoo->getPointerToBar();
    std::cout << quxBar->getX();
    quxBar->setX(100);  // HERE!!!
    std::cout << quxBar->getX(); // returns 100
}

Unfortunatelly it doesn't work since I'm still able to perform quxBar->setX(100) with no compilation error.

Probably my approach is totally wrong, but using current "skills" :) I have no idea how to fix it.

Thanks in advance for any help and suggestions.

Was it helpful?

Solution

I don't think this is your actual code, firstly due to the syntax errors it has, and secondly due to the fact that it actually is correct (mostly). More specifically, with this piece of code, quxBar->setX(100); would result in compilation error.

However, quxBar->getX() would also be a compilation error, you need to tell the compiler that can be called on const objects, you do this by adding const at the end of the function signature:

int getX() const { return x; }

Perhaps in your actual code you had Bar* const quxBar instead of Bar const* quxBar; they mean two different things: The former is a const pointer to Bar, while the later is a pointer to const Bar. Eg. in the earlier case, only the pointer itself can't be modified, but the object it points to can.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top