Is it OK for an abstract base class have non-abstract methods?

c++, coding-style

Solution

If you're calling it an interface (i.e. which you seem to be by your use of the naming convention "IFoo") then it should be a pure interface (no implementations).

If it's merely an abstract class then a mix of pure virtual and implemented methods is perfectly reasonable.

Problem

An abstract base class (interface class) usually has all its member functions abstract. However, I have several cases where member functions consisting of calls to the abstract methods of the interface are used. I can implement them in a derived-but-still-abstract class, or I can implemented the methods as non-abstract, non-virtual methods of the interface class. Are there any problems design-wise with implementing the methods in the interface class? Is it bad style, and if so, why? Does the same hold for static methods? For example ``` class IFoo { public: virtual ~IFoo(); virtual double calcThis( InputType p ) const = 0; virtual double calcThat( InputType p ) const = 0; double calcFraction( InputType p ) { return calcThis( p ) / calcThat( p ); } static BarType bar( InputType p ); }; class MyFoo : public IFoo { public: // implements IFoo virtual double calcThis( InputType p ) const; // implements IFoo virtual double calcThat( InputType p ) const; }; ``` versus ``` class IFoo { public: virtual ~IFoo(); virtual double calcThis( InputType p ) const = 0; virtual double calcThat( InputType p ) const = 0; }; class FooBase : public IFoo { public: virtual ~FooBase(); double calcFraction( InputType p ) { return calcThis( p ) / calcThat( p ); } static BarType bar( InputType p ); }; class MyFoo : public FooBase { public: // implements IFoo virtual double calcThis( InputType p ) const; // implements IFoo virtual double calcThat( InputType p ) const; }; ```

Original source