I got stuck with pointer to const QList of pointers to Foo
. I pass pointer to myListOfFoo
from Bar
object to Qux
. I use pointer to const to prevent making any changes outside Bar
class. The problem is that I'm still able to modify ID_
executing setID
in Qux::test()
.
#include <QtCore/QCoreApplication>
#include <QList>
#include <iostream>
using namespace std;
class Foo
{
private:
int ID_;
public:
Foo(){ID_ = -1; };
void setID(int ID) {ID_ = ID; };
int getID() const {return ID_; };
void setID(int ID) const {cout << "no change" << endl; };
};
class Bar
{
private:
QList<Foo*> *myListOfFoo_;
public:
Bar();
QList<Foo*> const * getMyListOfFoo() {return myListOfFoo_;};
};
Bar::Bar()
{
this->myListOfFoo_ = new QList<Foo*>;
this->myListOfFoo_->append(new Foo);
}
class Qux
{
private:
Bar *myBar_;
QList<Foo*> const* listOfFoo;
public:
Qux() {myBar_ = new Bar;};
void test();
};
void Qux::test()
{
this->listOfFoo = this->myBar_->getMyListOfFoo();
cout << this->listOfFoo->last()->getID() << endl;
this->listOfFoo->last()->setID(100); // **<---- MY PROBLEM**
cout << this->listOfFoo->last()->getID() << endl;
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
Qux myQux;
myQux.test();
return a.exec();
}
Result of above code is:
-1
100
and what I'm trying to achieve is:
-1
no change
-1
There is no such problem when I use QList<Foo>
instead of QList<Foo*>
but I need to use QList<Foo*>
in my code.
Thanks for help.