I would like to have several types that share the same implementation but still are of different type in C++.
To illustrate my question with a simple example, I would like to have a class for Apples, Oranges and Bananas, all having the same operations and same implementation. I would like them to have different types because I want to avoid errors thanks to type-safety.
class Apple {
int p;
public:
Apple (int p) : p(p) {}
int price () const {return p;}
}
class Banana {
int p;
public:
Banana (int p) : p(p) {}
int price () const {return p;}
}
class Orange ...
In order not duplicating code, it looks like I could use a base class Fruit and inherit from it:
class Fruit {
int p;
public:
Fruit (int p) : p(p) {}
int price () const {return p;}
}
class Apple: public Fruit {};
class Banana: public Fruit {};
class Orange: public Fruit {};
But then, the constructors are not inherited and I have to rewrite them.
Is there any mechanism (typedefs, templates, inheritance...) that would allow me to easily have the same class with different types?