Class with static function to be made an abstract base class in C ++

Use a use case where

Class foo {

public:

  static std::string make(std::string a) { .. }

}

      

I want to make foo an abstract base class, but obviously cannot be done in this abstract base, since virtual functions cannot be static.

Like this

Class foo {

public:
   static virtual std::string make (std::string) = 0; //error this cannot be done 

}

Class fooImpl: foo{

public:
   std::string make(std::string a) { ..}
}

      

Makes a method non-stationary in an abstract class or has derived classes, static methods is a good design approach.

0


source to share


3 answers


You can make the destructor a pure virtual function:

class foo {
  public:
    virtual ~ foo () = 0;
}

In any case, you need to make sure to provide a destructor implementation:



foo :: ~ foo () {}

Edit:
So you have a class that can be derived from, but itself cannot be instantiated.

+3


source


The question posted by others is whether a method should be virtual or static.

Polymorphism is based on the idea that you invoke the behavior of a specific instance of an object no matter what type of reference you have.

base& somefunction(); // may return base or derived objects
base &b = somefunction();
b.method();

      



Now, if the behavior of a method changes from base to derivative, and you want the behavior of the real instance you are accessing, then you need polymorphism and therefore a virtual method. The fact that a method may or may not use element data is irrelevant, the important part is that this behavior is associated with a specific instance.

On the other hand, static methods are bound to a class. That is, it is the behavior of the class you are dealing with, not the behavior of the passed instance. So, even though the syntax above can be used, it will call a static method in the classbase, since that is the class you are dealing with.

There is no reason to determine that any design variation you are dealing with is better than another without a deeper knowledge of the domain. I hope the above reasoning helps you make a decision.

+1


source


Interrupting static functions in a non-stationary virtual function allows polymorphism when you have an instance and static calls when you don't (I can't think of any use cases when you need polymorphism when you don't already have an instance). You lose a compile-time error if you remember to attach the implication of the static virtual in the derived class, which is not very pretty, but not much more that you can do. It is a shame that this control is not fixed in the C0x standard, but it is relatively narrow, so I think there is no requirement

0


source







All Articles