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.