Is there a keyword to access the base class
Stephen Jones
siwenjo at gmail.com
Tue Jun 18 15:19:28 PDT 2013
On Tuesday, 18 June 2013 at 22:15:51 UTC, Ali Çehreli wrote:
> On 06/18/2013 03:10 PM, Stephen Jones wrote:
>> I am trying to do this:
>>
>> import std.stdio;
>> import std.conv;
>>
>> class Bar{
>> }
>>
>> class Foo : Bar{
>> int val = 10;
>> }
>> class Foos : Bar{
>> int val = 20;
>> string str = "some more memory";
>> }
>>
>> void main(){
>> Bar[] bars;
>>
>> bars ~= new Foo();
>> bars ~= new Foos();
>>
>> foreach(Bar b; bars){
>> //writeln(b.val);//error: no property 'val' for type
>> 'mod.Bar'
>> }
>>
>> writeln(to!(Foo)(bars[0]).val);//works
>> }
>>
>> The problem is that I have to cast each Bar instance to its
>> base class
>> (Foo, Foos) before the compiler recognizes the val variable.
>> Is there
>> some syntax or keyword to allow me to specify that the b in
>> the foreach
>> loop refers to the base class not the super, such as
>> writeln(b.base.val);
>>
>> I know I can cast, but how do I know what base class each b in
>> the
>> foreach loop is?
>>
>
> val() must appear on Bar. I made it an interface:
>
> interface Bar{
> int val();
> }
>
> class Foo : Bar{
> int val_ = 10;
>
> int val() {
> return val_;
> }
> }
> class Foos : Bar{
> int val_ = 20;
> string str = "some more memory";
>
> int val() {
> return val_;
> }
> }
>
> Ali
Thanks Ali
More information about the Digitalmars-d-learn
mailing list