My interface declarations usually (always?) follow the same scheme. Here’s an example:
class Output
{
public:
virtual ~Output() { }
virtual void write( const std::vector<char> &data ) = 0;
protected:
Output() { }
private:
Output( const Output &rhs ); // intentionally not implemented
void operator=( const Output &other ); // intentionally not implemented
};
The boilerplate is always the same: public virtual destructor, a few pure virtual methods which make up the actual interface. protected default ctor, disabled copy construction and copy assignment. I started using two little helper macros which can be used to simplify the above to
ABSTRACT_BASECLASS_BEGIN(Output)
virtual void write( const std::vector<char> &data ) = 0;
ABSTRACT_BASECLASS_END(Output)
Unfortunately, I didn’t find a nice way to do this with just a single macro. Even better, I’d like to avoid macros entirely. However, the only thing which came to my mind was a code generator, which is a bit overkill for me.
What is the simplest way to declare an interface in C++ – directly in the language. Preprocessor use is acceptable, but I’d like to avoid external code generators.
Personally, I would remove the copy constructor declaration. You have pure virtual functions so instances of this class can’t be created by slicing in any case. If a derived class isn’t copyable because of the nature of a resource that it holds; it can mark itself as non-copyable.
Then I would get rid of the protected default constructor; it doesn’t do anything and you have to derive from this class in any case as you have pure virtual functions so it’s not preventing any usage.
Although marking the copy assignment operator prevents someone doing
*pBase1 = *pBase2(effectively a no-op), personally I’m not convinced that it’s worth the bother of trying to prevent it. As your class has no data members there’s no inherent danger in the compiler generated one, it’s really up to user to use pointers or references to base classes appropriately.I would just go with: