alias this private?
Ali Çehreli
acehreli at yahoo.com
Sun Dec 9 11:38:27 PST 2012
On 12/09/2012 11:23 AM, js.mdnq wrote:
> but b is not private, only the internal representation of it. e.g.,
> `alias Value_ this` is public. I do realize that it sort of makes Value_
> and b one and the same but they are not quite the same.
>
> To me, it breaks encapsulation. writeln(c.b) is accessing b, not Value_.
> b is a "virtual type" in the sense that it wraps Value_. While it seems
> to do something funky like change the protection of Value_ from private
> to public it doesn't. There is no way to access Value_ when it is
> private. i.e., we can't do c.b.Value_;
That's great. Value_ must remain private.
> To drive the point home. We could/should be able to completely
> encapsulate `Value_` by overriding opAssign and add getters and setters
> so that `Value_` is actually never even used(although pointless then).
That is possible in D.
> Another way to see this:
>
> struct sPassword
> {
> private:
> string Password;
> public:
> alias this Password;
> opAssign
> opCast
> opCmp
> opGet { return "******"; }
> Change(old pass, new pass) { if ... }
> Validate(pass) { pass == Password; ... }
> }
>
> sPassword myPass;
> writeln(myPass) same as writeln(myPass.Get()) which prints ******
You may have a point but at least I need to see how the existing
features of D are not acceptable. The following already does what you want:
struct sPassword
{
private:
string Password_;
public:
alias opGet this;
string opGet() { return "******"; }
}
void main()
{
sPassword myPass;
assert(myPass == "******");
}
(Aside: Although its name may suggest so, opGet is not an operator
function.)
> In any case, it just seems to me that we should be able to use private
> this way. If we want the additional functionality we just make it public.
Yes, private it good.
> (it does sort of seem sPassword is like a readonly type but it's more
> than that as it encapsulates completely)
>
> Now, if Password was public instead of private, anyone could do
> myPass.Password to get the password.
Yeah, not a good idea.
Ali
More information about the Digitalmars-d-learn
mailing list