|
|
Warp wrote:
> But an outside code could do something along the lines of:
>
> OuterClass::_InnerClass obj; // Assuming the compiler doesn't restrict this
>
> obj.someFunction();
That's correct. And no, the compiler doesn't restrict it. I don't know I've
even heard of a source code tool that warns you about it, altho that would
seem fairly easy to write, methinks.
Just FYI, the syntax for that would be
obj = OuterClass._InnerClass()
obj.someFunction()
OuterClass._InnerClass returns the class itself, since the class is just
assigned as the value of the variable. Invoking that value with () does the
equivalent of C++'s "new". Then you assign whatever the constructor returned
to obj. Depending on the existence of different functions inside the
_InnerClass class, you get things like overridden "new" or overridden
constructors.
And, technically, a constructor doesn't *have* to return an instance of the
class you invoked, if you override "new" in the class and have it return
something of a different class. So it's even uglier. :-) Just calling
obj = OuterClass()
could actually wind up assigning an OuterClass._InnerClass instance to obj.
Handy for factory functions, tho.
> The first line clearly breaks the privacy contract, but with the second
> line it's not so obvious anymore.
Correct.
On the other hand, it's the same result as if you did something like
obj = OuterClass::factory_method(...)
and factory_method returns an instance of _InnerClass. So it's not really
something you could enforce there at the compiler level. (As in, it would
be hard to enforce at the obj.someFunction() call, but easier at the
OuterClass._InnerClass access.)
I.e., I'm not sure I'd describe the second line as breaking the privacy
contract. It's just using a value obtained by breaking the privacy contract.
But that's just a matter of wording, really.
> It's calling a public member of _InnerClass,
> but it's intended to be "public" only for OuterClass
Not necessarily. If OuterClass returns an instance of _InnerClass (like, if
OuterClass is a collection and _InnerClass is an iterator over the
collection) it might make sense.
> (because _InnerClass is
> part of the private implementation of OuterClass), not for anything else.
If OuterClass never returns instances of _InnerClass, yes, that would be a
difficult violation of modularity to track down. It's certainly not the best
way of doing things if you're worried about that sort of thing.
--
Darren New, San Diego CA, USA (PST)
My fortune cookie said, "You will soon be
unable to read this, even at arm's length."
Post a reply to this message
|
|