I would like to clearly distinguish between 3D and 2D points in my code. The obvious solution would be to have separate classes.
On the other hand conversions from 3D points with z = 0 to 2D points are quite common. Therefore I would like to use a common base class so I can do those conversions in-place in memory. To keep the types apart clearly I would like to forbid the implicit conversion to that base class. Is that doable?
Or is there maybe a different way to create different types with similar function like this?
You might derive the child classes privately:
class PointBase {
// ...
};
class Point2D : private PointBase {
// ...
};
class Point3D : private PointBase {
// ...
};
Side effect of this approach is that also any public members of the PointBase
would be inaccessible from outside, so the subclasses would have to make them accessible explicitly, either by providing proxy methods for them, or specifying them with the keyword using
. That's why I would go this way only if the common logic in PointBase
is considerable and having it implemented on a single place brings more benefit then the mentioned disadvantage.
This doesn't answer your question, but to solve your problem you could make a method in the 3D class returning a 2D point when requested.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With