using an interface (abstract class) on c++ i have the need to force any class than inherits the interface to implement the operator ==.
consider this situation:
class IBase
{
virtual void someFunc() const = 0;
}
class CInheritClass : public IBase
{
virtual void someFunc() const;
virtual bool operator== ( const CInheritClass& obj ) const;
}
void main()
{
CInheritClass instance;
}
class CInheritClass must implement someFunc since it inherits Ibase, implementing virtual bool operator== ( const CInheritClass& obj ) const; is not mandatory.
i would like to modify IBase class in a way that any inheritor X will have to implement
virtual bool operator== ( const X& obj ) const
the following code will works:
template<class X>
class IBase
{
virtual void someFunc() const = 0;
virtual bool operator== ( const X& obj ) const = 0;
}
class CInheritClass : public IBase<CInheritClass>
{
virtual void someFunc() const;
virtual bool operator== ( const CInheritClass& obj ) const;
}
but i am after a solution that does not use templates cause every class that wishes to implement IBase must inherit IBase with itself as the template class class X : public IBase<X> and that is confusing and unclear to any future developer that might have a look on my code.
any idea ?
Use a pure virtual function declaration
A example of implementation :
The input type should be the base class, if not you will not be able to do polymorphically call comparison on base objects
For the idea of inherits from a template: warning, the base class is no longer the same between 2 derived class.
=> The purpose of the base class changed : With template you just share code, force user to implement function and prevent duplicate code between the 2 derived class
It really depend what you are trying to do. It can be a good design, or not…