Default values in derived class

Johan Engelen j at j.nl
Sat Dec 28 22:12:38 UTC 2019


On Saturday, 28 December 2019 at 20:47:38 UTC, Mike Parker wrote:
> On Saturday, 28 December 2019 at 20:22:51 UTC, JN wrote:
>> import std.stdio;
>>
>> class Base
>> {
>>     bool b = true;
>> }
>>
>> class Derived : Base
>> {
>>     bool b = false;
>> }
>>
>> void main()
>> {
>> // 1
>>     Base b = new Derived();
>>     writeln(b.b); // true
>> // 2
>>     Derived d = new Derived();
>>     writeln(d.b); // false
>> }
>>
>>
>> Expected behavior or bug? 1) seems like a bug to me.
>
> Expected. Member variables do not override base class 
> variables. b is declared as Base, so it knows nothing about 
> Derived’s member variable even though you instantiated it with 
> an instance of Derived. There’s no vtable for variables. If you 
> want it to print false, then you either have to cast b to 
> Derived or provide a getter function in Base that Derived can 
> override.

What Mike is saying is that `Base` has one `b` member variable, 
but `Derived` has two (!).

```
writeln(d.b); // false
writeln(d.Base.b); // true (the `b` member inherited from Base)
```

-Johan



More information about the Digitalmars-d-learn mailing list