digitalmars.D - Why isn't that a compilation error? - define a variable in a subclass
- Hipreme (34/34) Nov 10 2022 ```d
- Steven Schveighoffer (5/15) Nov 10 2022 When you derive a type, and override a name, the old name is masked or
- Hipreme (4/21) Nov 10 2022 That could trigger an error or at least a warning, just silently
- =?UTF-8?Q?Ali_=c3=87ehreli?= (11/16) Nov 10 2022 Yes, this is know as "name hiding" and well known in C++ circles. It
```d 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: ```d 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
Nov 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: ```d 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 misleadingWhen 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
Nov 10 2022
On Thursday, 10 November 2022 at 14:30:30 UTC, Steven Schveighoffer wrote:On 11/10/22 8:36 AM, Hipreme wrote:That could trigger an error or at least a warning, just silently hiding that can lead to bugsIt basically ignores the old method to just use the new variable. If I try: ```d 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 misleadingWhen 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
Nov 10 2022
On 11/10/22 07:02, Hipreme wrote:On Thursday, 10 November 2022 at 14:30:30 UTC, Steven Schveighofferwrote:Yes, this is know as "name hiding" and well known in C++ circles. It hides not only functions but member variables as well.When you derive a type, and override a name, the old name is masked or hidden.That could trigger an error or at least a warning, just silently hiding that can lead to bugsThe 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
Nov 10 2022