Re:“Clean” Code, Horrible Performance
by kazinator on Tuesday February 28, 2023 @08:41PM
(#34977676)
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.
Re:“Clean” Code, Horrible Performance
by gyy52380 on Wednesday March 01, 2023 @04:32AM
(#34980407)
There is only one vtable object per base class; all shapes share the same vtable pointer and your virtual CornerCount would be shared across all Shape instances. You are describing a potential implementation for class static variables.
There is no need to pull out a function pointer and jump to it.
In C I would do it like this
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.