Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I forbid implicit conversion to base class?

Tags:

c++

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?

like image 841
Sarien Avatar asked Mar 18 '13 12:03

Sarien


2 Answers

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.

like image 94
mity Avatar answered Oct 21 '22 06:10

mity


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.

like image 45
Some programmer dude Avatar answered Oct 21 '22 06:10

Some programmer dude