How do I setup a class that represents an interface? Is this just an abstract base class?
While it's true that virtual
is the de-facto standard to define an interface, let's not forget about the classic C-like pattern, which comes with a constructor in C++:
struct IButton
{
void (*click)(); // might be std::function(void()) if you prefer
IButton( void (*click_)() )
: click(click_)
{
}
};
// call as:
// (button.*click)();
This has the advantage that you can re-bind events runtime without having to construct your class again (as C++ does not have a syntax for changing polymorphic types, this is a workaround for chameleon classes).
Tips:
click
in your descendant's constructor.protected
member and have a public
reference and/or getter.if
s vs. state changes in your code, this might be faster than switch()
es or if
s (turnaround is expected around 3-4 if
s, but always measure first.std::function<>
over function pointers, you might be able to manage all your object data within IBase
. From this point, you can have value schematics for IBase
(e.g., std::vector
will work). Note that this might be slower depending on your compiler and STL code; also that current implementations of std::function<>
tend to have an overhead when compared to function pointers or even virtual functions (this might change in the future).