I usually program in C# but am trying to do a bit of C++ and am struggling somewhat trying to implement interfaces in C++.
In C# I’d do something like this:
class Base<T>
{
public void DoSomething(T value)
{
// Do something here
}
}
interface IDoubleDoSomething
{
void DoSomething(double value);
}
class Foo : Base<double>, IDoubleDoSomething
{
}
In C++ I’ve implemented it like this:
template <class T>
class Base
{
public:
virtual void DoSomething(T value)
{
// Do something here
}
};
class IDoubleDoSomething
{
public:
virtual void DoSomething(double value) = 0;
};
class Foo : public Base<double>, public IDoubleDoSomething
{
};
The problem is that I cannot instantiate Foo because it is abstract (doesn’t implement DoSomething). I realise I can implement DoSomething and just call the method on Base but I was hoping there is a better way of doing this. I have other classes which inherit from base with different data types and I have other classes which inherit from IDoubleDoSomething which don’t use Base.
Any help appreciated.
As others have noted, the two functions in the base classes are unrelated (despite having the same name and argument types), as they have no common base class. If you want them to be related, you need to give them a common base class.
Also, in general, if you want multiple inheritance to work properly, you need to declare your non-private base classes as
virtual. Otherwise, if you ever have common base classes (as you often need for this style of code), bad things will happen.So given that, you can make your example work as follows: