www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - Interaction of inheritance with property functions

reply =?UTF-8?B?THXDrXM=?= Marques <luis luismarques.eu> writes:
I had something like this:

class Bits
{
     int width()
     {
         return _width;
     }

     void width(int _width)
     {
         this._width = _width;
     }

     int _width;
}

class Bool : Bits
{
     // make sure a Boolean is always 1 bit
     override int width()
     {
         assert(_width == 1);
         return _width;
     }
}

I was surprised that I could not do this:

B b = new B;
b.width = 42;

Instead, I had to do this:

B b = new B;
(cast(Bits) b).width = 42;

Or I had to add a redundant setter function to Bool.

Shouldn't the property functions' resolution logic take into 
account the inherited functions? I had assumed that was the case 
(and I was confused by misleading error messages), and that seems 
like the more intuitive semantics to me.
Jun 07 2018
parent Adam D. Ruppe <destructionator gmail.com> writes:
On Friday, 8 June 2018 at 01:07:17 UTC, Luís Marques wrote:
 Shouldn't the property functions' resolution logic take into 
 account the inherited functions? I had assumed that was the 
 case (and I was confused by misleading error messages), and 
 that seems like the more intuitive semantics to me.
It is just the overload and hijacking rules. If you overload one, you need to bring the base class functions in too with alias width = Bits.width; in the child class. read this for rationale: https://dlang.org/articles/hijack.html
Jun 07 2018