Comment

Comment by kazinator

For all the creeping featuritis that C++ is acquiring like a dirty snowball, doesn't it have a solution for this yet?

    virtual u32 CornerCount() = 0;
you should be able to declare a virtual data member

    virtual u32 CornerCount;  // default value zero
how this would be implemented is that it simply goes into the vtable. ptr->CornerCount retrieves the vtable from the object, and CornerCount is found at some offset in that table, just like a virtual function pointer would be.

There is no need to pull out a function pointer and jump to it.

In C I would do it like this

   // Every shape has a pointer to its own type's static instance of this:

   struct shape_ops {
      unsigned (*area)(struct shape *);
      unsigned corner_count;
   }


   // get_area looks like this:

   unsigned shape_area(struct shape *s)
   {
      return s->ops->area(s);
   }

   // the corner count isn't calculated so it's just

   unsigned shape_corner_count(struct shape *s)
   {
      return s->ops->corner_count;
   }
Everyone can override corner_count with their value. What you can't do is implement a calculation which determines the corner count dynamically, but that can be a reasonable constraint.
parent kazinator 3 years ago

Discussion

Live from the official Hacker News API

A modern reader for Hacker News · SvelteKit + Skeleton