www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Default values in derived class

reply JN <666total wp.pl> writes:
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.
Dec 28 2019
parent reply Mike Parker <aldacron gmail.com> writes:
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.
Dec 28 2019
parent reply Johan Engelen <j j.nl> writes:
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
Dec 28 2019
parent JN <666total wp.pl> writes:
On Saturday, 28 December 2019 at 22:12:38 UTC, Johan Engelen 
wrote:
 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
That makes sense. I think the compiler/linter should be warning against such cases though, because it's easy to make mistakes this way.
Dec 28 2019