KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
If I want to make a class adaptable, and make it possible to select different algorithms from the outside -- what is the best implementation in C++? I see mainly two possibilities: Use an abstract base class and pass concrete object in Use a template Here is a little example, implemented in the various versions: Version 1: Abstract base class class Brake { public: virtual void stopCar() = 0; }; class BrakeWithABS : public Brake { public: void stopCar() { ... } }; class Car { Brake* _brake; public: Car(Brake* brake) : _brake(brake) { brake->stopCar(); } }; Version 2a: Template template<class Brake> class Car { Brake brake; public: Car(){ brake.stopCar(); } }; Version 2b: Template and private inheritance template<class Brake> class Car : private Brake { using Brake::stopCar; public: Car(){ stopCar(); } }; Coming from Java, I am naturally inclined to always use version 1, but the templates versions seem to be preferred often, e.g. in STL code? If that's true, is it just because of memory efficiency etc (no inheritance, no virtual function calls)? I realize there is not a big difference between version 2a and 2b, see C++ FAQ . Can you comment on these possibilities?
Tags (comma-separated)
Save Edits
Cancel