What are the pros and cons of using implicit interfaces (examples 2 and 3, templates) versus using explicit interfaces (example 1, a pointer to an abstract class) in the following example?
Code that does not change:
class CoolClass { public: virtual void doSomethingCool() = 0; virtual void worthless() = 0; }; class CoolA : public CoolClass { public: virtual void doSomethingCool() { } virtual void worthless() { } }; class CoolB : public CoolClass { public: virtual void doSomethingCool() { } virtual void worthless() { } };
Case 1: a non-templated class that accepts a pointer to a base class that provides an explicit interface:
class CoolClassUser { public: void useCoolClass(CoolClass * coolClass) { coolClass.doSomethingCool(); } }; int main() { CoolClass * c1 = new CoolA; CoolClass * c2 = new CoolB; CoolClassUser user; user.useCoolClass(c1); user.useCoolClass(c2); return 0; }
Case 2: a template class whose template type provides an implicit interface:
template <typename T> class CoolClassUser { public: void useCoolClass(T * coolClass) { coolClass->doSomethingCool(); } }; int main() { CoolClass * c1 = new CoolA; CoolClass * c2 = new CoolB; CoolClassUser<CoolClass> user; user.useCoolClass(c1); user.useCoolClass(c2); return 0; }
Case 3: a template class whose template type provides an implicit interface (this time, not based on CoolClass :
class RandomClass { public: void doSomethingCool() { }
Case 1 requires that the object passed to useCoolClass () be a child of CoolClass (and implement a worthless () ). On the other hand, cases 2 and 3 will take the any class, which has the doSomethingCool () function.
If users of the code have always had cool CoolClass subclasses, then case 1 makes intuitive sense, since CoolClassUser will always wait for the CoolClass implementation. But suppose this code will be part of the API structure, so I cannot predict whether users will want to subclass CoolClass or collapse their own class, which has the doSomethingCool () function.
Some related posts:
stack overflow
stack overflow
stack overflow
Chris morris
source share