Casting from interface to real class?

Bill Baxter dnewsgroup at billbaxter.com
Mon Jan 21 01:51:05 PST 2008


Oliver wrote:
> Hi Bill,
> 
> Bill Baxter Wrote:
> 
>> Bill Baxter wrote:
>>> Is it possible to do a dynamic cast from an interface to a real class?
>>>
>>> SomeClass k = cast(SomeClass)anInterface;
>>>
>>> will that succeed if anInterface started life as a SomeClass?
> 
> 
> I hope I understood your question correctly, here is an example.
> 
> --------------------
> import std.stdio;
> 
> interface Expr {
>     Expr type();
>     void print();
> }
> 
> Expr steSymbol;
> 
> class Symbol : Expr { 
> public:
>     this(char [] name) { this.itsName = name; }
>     char [] getName() { return this.itsName; }
>     Expr type() {return steSymbol;}
>     void print() {writefln(this.itsName);}
> private:
>     char [] itsName;    
>     int itsInt;
> }
> 
> int main ( char [][] arg ) { 
>     Expr e;
>     steSymbol = new Symbol("Symbol");
>     e = new Symbol("x");
>     steSymbol.print();
>     e.print();
>     e.type().print();
>     Symbol s = cast(Symbol)e;
>     s.print();
>     writefln((cast(Symbol)e).getName());
>     return 0;
> }
> 
> 

Yep, that's exactly what I was hoping I could do but thinking I 
couldn't.  But it does work.  Happy day.

--bb


More information about the Digitalmars-d-learn mailing list