digitalmars.D.learn - Default values in derived class
- JN (19/19) Dec 28 2019 import std.stdio;
- Mike Parker (7/26) Dec 28 2019 Expected. Member variables do not override base class variables.
- Johan Engelen (8/40) Dec 28 2019 What Mike is saying is that `Base` has one `b` member variable,
- JN (5/12) Dec 28 2019 That makes sense. I think the compiler/linter should be warning
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
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
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: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) ``` -Johanimport 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
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) ``` -JohanThat 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