Implicit conversions for value subtyping
Consider that we implement simple datatypes (i.e. simple "value
types") without virtual functions and all read only functions are
global functions (instead of class member functions). Let single
argument constructors be used to support implicit type conversions.
E.g. to emulate Square value is-a Rect value.
The following uses structs (public member variables) without
suggesting that is necessarily appropriate.
struct Square { int s; };
int side(Square sq) { return sq.s; }
struct Rect
{
Rect(Square s) : w(side(s)), h(side(s)) {}
int w, h;
};
int width(Rect r) { return r.w; }
int height(Rect r) { return r.h; }
int area(Rect r) { return width(r) * height(r); }
void Test()
{
Square s = {10};
int A = area(s);
}
The width, height and area functions defined on rectangle values are
also available for square values, which is just what we need, and
could be viewed as a form of inheritance. By declaring these
functions inline a modern compiler will typically eliminate
temporaries and be as efficient as a specialisation for Square.
Square inherits functions defined on rectangles but not the
implementation of rectangle (i.e. the member variables). In fact
Square can be implemented in any way we like. E.g. by recording the
perimeter.
struct Square { int perim; };
int side(Square sq) { return sq.perim/4; }
Note that the implicit conversions are still available if the read
only functions use const references. E.g. area could be declared like
this
int area(const Rect& r)
{
return width(r) * height(r);
}
Questions:
1) Is this a reasonable technique?
2) Is there a reason why C++ was designed so that const member
functions defeat the implicit conversions on *this?
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]