tags:

views:

223

answers:

3

Have 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 make cannot be 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) { ..}
}

Is making the method non static in the abstract class or have derived classes have static methods a good approach from a design perspective.

+3  A: 

You can make the destructor a pure virtual function:

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

You just need to make sure to provide an implementation for the destructor anyway:

foo::~foo() {}

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

But this doesn't help make the static function virtual...
Patrick
Yes, but I couldn't tell what the question was. It sounded like he was asking how to make an abstract class.
+1  A: 

The question, as posted by others is whether the method should be virtual or static.

Polymorphism is based on the idea that you are calling a behavior of the particular object instance regardless of what type of reference you have to it.

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

Now, if method behavior changes from base to derived and you want the behavior of the real instance you are referring to, then you need polymorphism and thus a virtual method. The fact that the method may or not use member data is irrelevant, the important part is that it is a behavior bound to the particular instance.

On the other end, static methods are bound to the class. That is, it is a behavior of the class you are dealing with not a behavior of the instance being referred. As such, even if the syntax above can be used it will call the static method in class base since that is the class that you are dealing with.

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

David Rodríguez - dribeas
A: 

Wraping the static functions in a non static virtual function allows polymorphism when you have an instance and static calls when you don't (I can't think of any use cases where you'll only need polymorphism when you don't already have an instance). You loose the compile time error if you forget to put an implmentation of the static virtual in a derived class and it isn't very pretty but not much else you can do. It is a shame that this oversight is not being fixed in the C0x standard but it is relatively narrow requirement so I guess there isn't the demand

Patrick