I have a class Point and a class Rect. I want to have two constructors for the Rect: One with a Point and a dimension (width, height) and one with two Points (top left, bottom right). Now it turns out that Point also can be seen as a dimension, so instead of creating a Dimension class I want to use my Point, basically like this:
class Point{...};
typedef Dimension Point;
class Rect{
public:
Rect(Point, Point);
Rect(Point, Dimension);
}
So the question is: Does the compiler make a difference between Point and Dimension? I tried it, the message ist “call of overloaded Rect(Point, Point) is ambiguous.”.
How should I do that? Preferably without inheritance 🙂
EDIT
I understood now that it’s the same to the compiler. But there is another scenario wher I need that.
I have a Point. The coordinates can be in a carthesian system (x, y) or GPS coordinates (lon, lat). It’s perfectly ok for me to call the components x0 and x1 so I want to use only one class.
Now I want to calculate the distance between the two points and my idea is as follows:
typedef PointLonLat Point;
typedef PointXY Point;
double distance(PointLonLat, PointLonLat);
double distance(PointXY, PointXY);
PointLonLat p1(10, 10);
PointLonLat p2(11, 11);
double dist = distance(p1, p2); // the correct implementation is used
I know it doesn’t work like that. But would the answer to that also be “make two classes”?
If
pointanddimensiondon’t have identical behaviour, then yourtypedefis a logic error. If they do, then you don’t need two constructors.In response to your edit
For the example you’ve provided, what you have is two classes that store the same amount of data but have different behaviour. It’s analagous to
std::size_tandvoid*– they’re both the same number of bits to the underlying hardware, but the language’s type system gives them totally different meanings.Your example could be solved by using two different classes, or by using a template class to avoid duplication like this: