Thread overview
Why isn't that a compilation error? - define a variable in a subclass with the same name of a superclass method
Nov 10, 2022
Hipreme
Nov 10, 2022
Hipreme
Nov 10, 2022
Ali Çehreli
November 10, 2022
import std;

class Test
{
    float[3] _position = [0,0,0];
    float[3] position()
    {
        writeln("Get");
        return _position;
    }
    float[3] position(float[3] value)
    {
        writeln("Set");
        return _position = value;
    }
}

class STest : Test
{
    float[3] position;
}

void main()
{
    STest t = new STest;
    t.position = [1,2,3];
}

It basically ignores the old method to just use the new variable.

If I try:

t.position([1,2,3]);

I get the error: onlineapp.d(26): Error: function expected before (), not t.position of type float[3]

There's something really misleading

November 10, 2022

On 11/10/22 8:36 AM, Hipreme wrote:

>

It basically ignores the old method to just use the new variable.

If I try:

t.position([1,2,3]);

I get the error: onlineapp.d(26): Error: function expected before (), not t.position of type float[3]

There's something really misleading

When you derive a type, and override a name, the old name is masked or hidden. You can alias the original name in, but I don't think it would work for overloading a field with a function.

-Steve

November 10, 2022

On Thursday, 10 November 2022 at 14:30:30 UTC, Steven Schveighoffer wrote:

>

On 11/10/22 8:36 AM, Hipreme wrote:

>

It basically ignores the old method to just use the new variable.

If I try:

t.position([1,2,3]);

I get the error: onlineapp.d(26): Error: function expected before (), not t.position of type float[3]

There's something really misleading

When you derive a type, and override a name, the old name is masked or hidden. You can alias the original name in, but I don't think it would work for overloading a field with a function.

-Steve

That could trigger an error or at least a warning, just silently hiding that can lead to bugs

November 10, 2022
On 11/10/22 07:02, Hipreme wrote:
> On Thursday, 10 November 2022 at 14:30:30 UTC, Steven Schveighoffer wrote:

>> When you derive a type, and override a name, the old name is masked or
>> hidden.

Yes, this is know as "name hiding" and well known in C++ circles. It hides not only functions but member variables as well.

> That could trigger an error or at least a warning, just silently hiding
> that can lead to bugs

The opposite can cause bugs as well and that's why such a feature exists: Imagine a case where foo(42) call was being dispatched to the subclass's foo(double) member function. Without your knowledge, the base class adds a foo(int) to their existing foo(string). Now your foo(42) call would silently be dispatched to the base class function.

Name hiding makes it explicit where you want your calls go to.

Ali