开发者

what is the advantage of a c++ class having static methods with exact same signature as the interface methods

What is the advantage of defining static methods with exact same signature as the in开发者_开发百科terface method in the class which implements it .

class IInterface
{
public:
  virtual void fn()=0;
}

class Impl :IInterface
{
public:
  ~Impl();
  static  void fn();
}

Impl::~Impl{
}

Impl::fn(){
 //do something
}


There is no advantage of having such static method. static methods don't override virtual methods (which are always non-static).

In fact it has disadvantage, that you cannot implement the actual method to override the base method. Because one cannot have same method signature in a single class (one static and another non-static).

class Impl :IInterface
{
public :
~Impl();
staic void fn();
void fn() {} // error: invalid (can't have same signature)
};


There is no advantage.

Your derived class Impl still is as an Abstract class since it does'nt & can't override the pure virtual function. You cannot create any objects of it.

A static function cannot override a virtual function from Base class because dynamic polymorphism uses the this to evaluate the function call at run time, while static functions do not pass the this pointer, because they are not specific to any object.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜