alias this & cast
Ali Çehreli via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Thu Sep 11 10:07:57 PDT 2014
On 09/11/2014 09:18 AM, andre wrote:
> I am not sure. b is C but everything not in super class B is hidden.
> Using cast I can cast b to a full C.
>
> The cast "cast(C)b" has the same information about b like the cast
> "cast(A)b": The memory area of b knows compatitibility to C and also the
> alias.
That's only because 'b' really is a C.
> For me, using alias this, the object b has 3 represenations: A, B and C.
Correct but it cannot be known whether any B is an A:
void foo(B b)
{
// ...
}
Can that 'b' used as an A? Who knows...
It may be desirable that the compiler did static code analysis and saw
that the 'b' in your code is always a C, therefore can be casted to an
A. Compilers do not and most of the time cannot do that.
Consider one line added to you program:
>>> class A{}
>>>
>>> class B{}
>>>
>>> class C : B
>>> {
>>> A a;
>>> alias a this;
>>>
>>> this()
>>> {
>>> a = new A();
>>> }
>>> }
>>>
>>> void main()
>>> {
>>> B b = new C();
Add this:
takesBbyReference(b);
Now nobody knows whether the object has changed to something other than
C. For example:
class Z : B
{}
void takesBbyReference(ref B b)
{
b = new Z;
}
Now the first assert fails as well:
>>> assert(cast(C)b);
Ali
More information about the Digitalmars-d-learn
mailing list