Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Field base access works for virtual methods #19578

Open
dlangBugzillaToGithub opened this issue Jun 5, 2019 · 3 comments
Open

Field base access works for virtual methods #19578

dlangBugzillaToGithub opened this issue Jun 5, 2019 · 3 comments

Comments

@dlangBugzillaToGithub
Copy link

FeepingCreature (@FeepingCreature) reported this on 2019-06-05T21:29:02Z

Transferred from https://issues.dlang.org/show_bug.cgi?id=19943

Description

The following code outputs "A":

import std.stdio;

class A {
    int a;
    void foo() { writefln("A"); }
}
class B : A { 
    int a;
    override void foo() { writefln("B"); }
}

void main() { (new B).A.foo(); }

This defeats the entire point of classes. This is a side effect of https://dlang.org/spec/class.html#fields , which specifies that (new B).A.a accesses the "int a" of the base class. That's fine, but this feature should not work for virtual methods, which the subclass explicitly overrides. Only the subclass should be allowed to access super methods.
@dlangBugzillaToGithub
Copy link
Author

b2.temp commented on 2019-06-06T14:38:31Z

I see this more as a feature.

It is occasionally useful and without that it would painfully hard (as seen in other languages that don't support this, some trickery with delegates and cast must be used) to call a less derived virtual method from a more derived type.

A use case is when you derive a class from a framework that you don't control and that its protection attributes or its class hierarchy have flaws. E.g: Some useful things are done in Framework.A, Only a small thing you want to avoid is done in Framework.B but your Own.C must derive from Framework.B because the rest is ok and you don't want to copy and paste 95% of Framework.B

@dlangBugzillaToGithub
Copy link
Author

default_357-line (@FeepingCreature) commented on 2019-06-06T15:26:49Z

To me, the problem isn't that you're able to do it from Own.C, the problem is that you're able to do it from random.foo(), a function that is unrelated to the A inheritance hierarchy.

@dlangBugzillaToGithub
Copy link
Author

b2.temp commented on 2019-06-06T18:45:52Z

Okay I see. Maybe that outside this should behave like a cast, which then behaves like you expect, i.e the field can be read but virtual dispatching is not shortcut.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant