I need to use C++. C++11 would be interesting, but I’d prefer without. I have the following class structure.
class Wheel { /*...*/ };
class MtbWheel : public Wheel { /*...*/ };
class Bike { Wheel front_wheel; };
class Mountainbike : public Bike { MtbWheel front_wheel; };
Now, this completely works: The Mountainbike overrides front_wheel, and thus can use an MtbWheel. Softwaretechnically, I am not happy, though.
- What I would prefer is disallowing to override front_wheel, or at least restrict overwriting by classes that do not inherit class Wheel.
- Instead of overriding front_wheel, I’d like only to “add” properties to it.
EDIT: Is there a solution without virtual functions, but with templates instead?
Your
front_wheelmember inMountainbikeclass does not overridefront_wheel, it hides it.Mountainbikeclass actually has twofront_wheelmembers, but the one from theBikeclass is hidden by the one declared inMountainbike. Meaning that ifBikeaccessesfront_wheel, it will access an object of typeWheel, while whenMountainbikeaccessesfront_wheel, it will access an object of typeMtbWheel– but these two wheel objects don’t know of each other!Better OO design would be to make
front_wheele.g. a pointer inBike(or even better a smart pointer), and initialize it in the constructor ofMountainbiketo hold an object of a class derived fromWheelwhich fits best toMountainbike. That way, when accessing front_wheel, one way or the other virtual functions come into play of course.An alternative solution, as per Steve Jessop’s suggestion in the comments below, making use of templates instead of using polymorphism, would be:
That way, no virtual functions are involved when operating on front_wheel. There are some points to consider with such a solution, however:
Bikewith different WheelType parameters, they do not have the same base class (see Steve Jessop’s comment, and point 1), and therefore also can’t be accessed polymorphically.WheelTypebeing passed as template parameter to Bike; only the implicit interface is defined by the methods and members used fromBike. That should be no problem however, since the compiler can still verify that implicit interface.