views:

86

answers:

1

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.

+5  A: 

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.

reko_t
+1 for getting things the right way around.
sje397
Thanks, actually there wasn't any problems with "`Bar* const quxBar` instead of `Bar const* quxBar`". There was some problem with QList pointer I used in original code.
Moomin