Programming language that supports inheriting value types – Education Career Blog

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?

,

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.

,

In ruby you can go a step further. You can actually modify built in types.

class Float
  class self.heading(val)
    raise RangeError unless (0.0...360.0) === val
    val
  end
end

,

Ada allows this to a limited extent: specifically, your example can be expressed in Ada as

type Heading is digits 10
    range 0.0..360.0;

Pascal had a similar feature that was, IIRC, restricted to integers.

I don’t know of any languages that allow unrestricted inheritance from primitive types like float. Object-oriented inheritance by definition involves inheriting from a class, which something like C++’s float by definition is not.

,

D, java, and Objective-C allow deriving from built-in types. In fact most object-oriented languages with built-in types defined to inherit from Object permit inheritance from the built-in types. (I’m sure there’s a counterexample and we’re about to find out about it in the comments…)

Leave a Comment