QT Sdk - practive, can one private object access another one?
-
Hey
I'm studying Qt public/private logic. I was wondering ( as I'm blind) if a QWidgetPrivate, is able to access another QWidget object QWidgetPrivate member? If so, how? where? Or does it have to use public QWidget members to set data/etc and its unable to talk directly to Private class?
Regards
Dariusz -
Hi,
No it can't. The private implementation (PIMPL) is done so that the internals can be rewritten without affecting the public API.
From a C++ point of view, it follows the exact same rules with regards to access levels.
-
@SGaist mmm thats what I'm trying to wrap around.
If a QWidgetPrivate need to set a flag/variable on another QWidgetPrivate (I'm using QWidgetPrivate as an "example" nothing to do with QWidget, might as well call it QApplePrivate), then if public api does not have a setter, then public api has to change no? Say if I do somethingQWidget->setParent(QWidgetPtr)
when we do
{ Q_D(QWidget) dptr->setParent(widget) } setParent(widget){ widget->getPrivate()->setNewNonPublicApivariable(10); }
The private function can only set/get variables from public QWidget, which kinda mean if I want to set a new variable that does not exist in public, then we have to change public api ?
Would it not make sense if a private class can access other widget's private classes? Like widget->getPrivate(), so that it can set data on it ?I mean, I could make getPrivate() function, but then... should I? If I expose private, then even user from public API can access it... which I can imagine would be a little "bad" ? Any ideas?
Or is that just a limitation?
It seems like "private" can only affect itself, and not build a secondary layer of connections/links between objects as it always has to rely on public functions...? -
@Dariusz said in QT Sdk - practive, can one private object access another one?:
Would it not make sense if a private class can access other widget's private classes?
No. Private is there for a reason. Private stuff should not be accesed directly by the outside world.
If there is no public API yet for something and it is really needed, then it needs to be added. But this is not a reason to break encapsulating by allowing direct access to private APIs.
Also, in C++ you can't access private members/methods from other classes without making these classes friends. Nothing Qt can do about (and it also should not).
And as @SGaist pointed out: the PIMPL design pattern is there to prevent ABI from changing if internal implementation changes. Means: if you change something in the private implementation without changing public API, then the user code does not have to be rebuilt. Since you can't restrict access to private APIs to private classes (like what your example shows: widget->getPrivate()) also non-private classes would be able to access those interfaces and (even worse) user code.