Search code examples
c++methodsstaticvirtual

How to enforce a static member on derived classes?


I have a base class, Primitive, from which I derive several other classes--Sphere, Plane, etc.

Primitive enforces some functionality, e.g intersect(), on its subclasses through pure virtual functions. The computation of intersect depends on instance data, so it makes sense to have it as a member method.

My problem arises in the following: I want every derived instance to be able to identify its type, say through a std::string type() member method. As all instances of the same class will return the same type, it makes sense to make type() a static method. As I also want every Primitive subclass to implement this method, I would also like to make it a pure virtual function, like intersect() above.

However, static virtual methods are not allowed in C++. C++ static virtual members? and Can we have a virtual static method ? (c++) ask similar questions but they do not include the requirement of enforcing the function on derived classes.

Can anyone help me with the above?


Solution

  • You could have a non-static virtual method calling the static one (or returning a static string), appropriately implemented in each derived class.

    #include <iostream>
    #include <string>
    
    struct IShape {
      virtual const std::string& type() const =0;
    };
    
    struct Square : virtual public IShape {
      virtual const std::string& type() const { return type_; }
      static std::string type_;
    };
    std::string Square::type_("square");
    
    int main() {
    
      IShape* shape = new Square;
      std::cout << shape->type() << "\n";
    
    }
    

    Note that you will have to implement the type() method for every subclass anyway, so the best you can do is for the string to be static. However, you may consider using an enum instead of a string, do avoid unnecessary string comparisons in your code.

    Now, going back to the fundamentals of the problem, I think the design is somewhat flawed. You cannot really have a general intersection function that operates on all kinds of shapes, because the types of shapes resulting from intersections vary greatly, even for the same type of shape (two planes can intersect in a plane, a line, or not intersect at all, for example). So in trying to provide a general solution, you will find yourself performing these kind of type checks all over the place, and this will grow unmaintainably the more shapes you add.