Hi, all... I'm working with Qt not for a long time, but recently a thought came to my mind.
QObject
has public function children()
and a few other ones, which return pointer to a child object(s).
So any client of custom class can break encapsulation.
How can I protect my code from such barbaric treatment?
Why did Qt developers leave such functionality in public section? What purpose did they try to achieve?
The only one argument about such functions I can imagine is connected with 'garbage collection' in Qt (when one delete parent QObject
derived class instance all children instances are automatically deleted). But I think it could be done with Qt's metaObject
system (I'm not sure in the mechanism, however, access to child objets shouldn't be public, on my opinion).
- Also, consider situation when someone attempts to use child object in separate thread, which is forbidden in Qt... but I don't see any restrictions in light of using
QObject::children()
.
//------------------------------------------------------------------------------------------------
further explanation according to some comments:
While you have access with QObject::children()
to private members of the class, e.g.
class MyClass: public QWidget{ private: QLabel* m_lbl1; };
...
MyClass* p = new MyClass;
QLabel* pLbl = p->findChild<QLabel>();
there is no need to declare member m_lbl1 as private one:
class MyClass: public QWidget{ public: QLabel* m_lbl1; };
and it's very bad. because if you have at least 10^5 lines of code in your solution and more that 1 developer, sooner or later someone can manually change state of any child member of MyClass
and you can achieve any kind of bug (e.g. behavior which is not possible according to MyClass
implementation).
@Merlin069: is pImpl a common approach in Qt's development?