Home > Software engineering >  C Add non-virtual static method in interface is normal?
C Add non-virtual static method in interface is normal?

Time:08-05

I thought interface can only include pure virtual functions in C . However, recently my college showed me the following code:

class IAddition {
 public:

     virtual bool MethodA() = 0;

     static bool StaticMethodA(IAddition* interface) {
           return interface->MethodA();
     }

     static std::string GetStr() { 
         return "A";
     }
};

The interface can be compiled but I feel the code weird. I can't understand what is a static method of an interface? Is this very normal in C programs?

CodePudding user response:

I thought interface can only include pure virtual functions in C

There is no such requirement imposed by the C standard.

Is this very normal in C programs?

Yes(assuming by normal you mean well-formed), this is a valid C program. We're allowed to use virtual member function with static as well as non-static member functions within a class.

CodePudding user response:

As blankettripod point out in comment and Jason Liam in other answear C language do not have interface concept. So purely from C standard perspective this is fine.

But in many best C practices interface means:

class or a struct without any fields and only with public pure virtual functions inside (except for destructor which must be implemented and should be virtual).

See also Cpp Core Guidelines I.25: Prefer empty abstract classes as interfaces to class hierarchies.

So your IAddition fails this definition because of this static methods. Many developers will not have problem with that.
On other hand in many projects where coding standard rules are more strict and respected, this is no longer an interface and should be fixed. There are many rationales, for example if this API is ported to other languages (like Java or C# where interfaces are part of language features) this extra methods will be a real technical problem.

  •  Tags:  
  • c
  • Related