Search code examples
programming-languages

Programming language that supports inheriting value types


I develop in C++, and sometimes I wish I could say something like this:

class Heading : public float    // this line won't compile
{
public:
  Heading( float const value_ )
  : float(value_)               // this line won't compile
  {
    assert( value_ >= 0.0f );
    assert( value_ <= 360.0f );
  }
};

Instead, I have to do something like:

class Heading : public float
{
public:
  Heading( float const value_ )
  : value(value_)
  {
    assert( value >= 0.0f );
    assert( value <= 360.0f );
  } 
private:
  float value;
};

Are there any programming languages out there that allow you to extend value types?


Solution

  • Python.

    Everything's an object. So extending float is simple.

    class Heading( float ):
       def __init__( self, value ):
           assert 0.0 <= value <= 360.0
           super( Heading, self ).__init__( value )
    

    And yes, 0.0 <= value <= 360.0 is legal syntax.