Private visible?
Lucas Goss
lgoss007 at gmail.com
Sat Jul 15 07:12:39 PDT 2006
Walter Bright wrote:
> Lucas Goss wrote:
>> Walter Bright wrote:
>>>
>>> Sometimes it is valuable to be able to say "you can't do this
>>> operation with this type". I don't see why this ability should be
>>> restricted to C++.
>>
>> Can someone come up with an example or explain why this would be
>> valuable? To make sure we're on the same page, we're talking about:
>>
>> ----
>> class Base {
>> public:
>> virtual int Number() = 0;
>> };
>> ...
>> class Child : public Base {
>> private:
>> int Number() { return 1; }
>> };
>
> I think it's a bug that the compiler allows this. It should be illegal
> code, because it breaks encapsulation.
Um, maybe I didn't make it clear enough, or maybe I'm not understanding.
The above is C++ code that went with this code:
(1)
Child c;
int num = c.Number(); //error: cannot access private member
(2)
Child* cp = new Child();
num = cp->Number(); //error: cannot access private member
(3)
Base* bp = new Child();
num = bp->Number(); // num = 1
So the compiler does error with the first two attempts, but the third
compiles and runs fine. I was just trying to find an example of
'poisoning' a base class that you mentioned. To me it doesn't sound like
very good practice (maybe that's why C# and I think Java disallow such
practice). I just wanted to make sure I'm understanding correctly.
Lucas
More information about the Digitalmars-d
mailing list