I am using an abstract factory to create user interface components such as dialogs. The abstract factory used is returned from a currently selected generic "INode" which is the base class for several different types of node. So for instance, if I want to add a new node of the same type as the selected node, the scenario goes something like this:
(please note this is semi-pseudo code)
User clicks node and the node gets stored for later use:
void onTreeNodeSelected(INode *node)
{
selectedNode = node;
}
User clicks "add" on the user interface:
void onAddClicked()
{
IFactory *factory = selectedNode->getFactory();
Dialog *dialog = factory->createAddDialog(parentWidget);
dialog->show();
}
Which all seems fine. The problem comes when I want to edit the selected node:
void onEditClicked()
{
IFactory *factory = selectedNode->getFactory();
Dialog *dialog = factory->createEditDialog(selectedNode, parentWidget);
dialog->show();
}
Oh dear.. I'm passing in an INode object. At some point I'm going to have to downcast that to the correct node type so the dialog can use it properly.
I've studied the "PostgreSQL Admin 3" source code, and they do something similar to this. They get round it by doing something like this:
FooObjectFactoryClass::createDialog(IObject *object)
{
FooObjectDialog *dialog = new FooObjectDialog((FooObject*)object);
}
Yeck.. cast!
The only way I can think around it and still able to use my factories is to inject the node itself into the factory before it is returned:
FooNode : INode
{
FooNodeFactory* FooNode::getFactory()
{
fooNodeFactory->setFooNode(this);
return fooNodeFactory;
}
}
So then my edit event can do this:
void onEditClicked()
{
IFactory *factory = selectedNode->getFactory();
Dialog *dialog = factory->createEditDialog(parentWidget);
dialog->show();
}
And it will use the injected node for context.
I suppose if there is no injected code, the createEditDialog could assert false or something.
Any thoughts?
Thanks!
A common solution is "double-dispatch", where you call a virtual function on one object, which in turn calls a virtual function on the other, passing this, which now has the correct static type. So, in your case, the factory can contain "create" functions for the various types of dialogues:
class IFactory
{
public:
....
virtual Dialog* createEditDialog(ThisNode*, IWidget*);
virtual Dialog* createEditDialog(ThatNode*, IWidget*);
virtual Dialog* createEditDialog(TheOtherNode*, IWidget*);
....
};
then each type of node has a virtual createEditDialog that dispatches to the correct factory function:
class INode
{
public:
....
virtual Dialog* createEditDialog(IWidget* parent) = 0;
....
};
class ThisNode : public INode
{
public:
....
virtual Dialog* ThisNode::createEditDialog(IWidget* parent)
{
return getFactory()->createEditDialog(this, parent);
}
....
};
Then you can create the correct dialogue as
void onEditClicked()
{
Dialog *dialog = selectedNode->createEditDialog(parentWidget);
dialog->show();
}
In my opinion, using C-style casts (although C++ style would be preferred) is perfectly acceptable as long as your code is properly commented.
I'm not a big fan of DI (dependency injection) because it makes some code hard to follow and, in your case, I would rather look at a dynamic_cast<>() or something than try to follow injected code over multiple source files.
I would sugest two things.
First: there is nothing wrong with casting. If you want to be safe, you could use RTTI (type_id stuff) or some virtual functions in the INode class which could return some info which would let you know if it is safe to cast.
Second: you could check to see what the createEditDialog function needs, and put those in virtual functions in either INode, or an inherited class which would be the type createDialog expects.
In general, I see nothing really wrong with the problem you describe, and it is hard to give more suggestions without seeing the whole code, which I assume is unfeasible.
Your approach of injecting the node into the factory is generally a pattern I've found useful, but there are often times when you don't have a reference to the target object when you're creating the factory like you do here. So this might work fine for you in this case and it's simpler than handling this kind of problem in the general case.
For the more general case, you need to work with the notion of interfaces and establish a mechanism by which your INode object can publish which interfaces it supports and provide access to those interfaces for clients. Doing this completely dynamically leads to a COM-like approach that requires dynamic registration and casting. But you can also do this in a statically typed manner if you have a relatively stable set of interfaces you want to expose and can afford to edit the INode interface when you need to add a new component interface.
So this would be an example of how to do the simple statically typed approach:
struct INode
{
virtual INodeSize* getNodeSizeInterface() = 0;
virtual INodeProperties* getNodePropertiesInterface() = 0;
virtual INodeColor* getNodeColorInterface() = 0;
... // etc
}
Now each INode implementation can return some or all of these component interfaces (it would just return NULL if it didn't implemen them). Then your dialogs operate on the component interfaces to do their work instead of trying to figure out which actual implementation of INode was passed in. This will make for much more flexible mapping between dialogs and node implementations. A dialog can quickly determine whether it has a "compatible" INode object by verifying that it returns a valid object for each interface that the dialog is interested in.
I think a cast inside createEditDialog is not a bad thing in this case, even though you give up compile time checks. If the type of the node does not change at runtime, you could use templates instead of an abstract INode-class.
Otherwise, your proposed solution is the one that I would think of as well. I would, however, rename the Method to something like "getSelectedNodeDialogFactory" (i know, long name) so that it is clear that the factory returned is specific to that node. Are there other dialogs that need to know the concrete type of the INode object? Does createAddDialog need a parent or a predecessor node, maybe? Those could all go in the factory-with-selected-node class.
Related
I have a database with table X: let's call it clients. I also have a form related to editing table X contents. It may open it on it's own (to browse/edit) as well as from other forms when it is necessary to "pick" a record from table X.
How do I go about telling the parent that a particular QModelIndex has been picked straight out of on_tableView_doubleClicked(const QModelIndex &index) signal handler?
Currently, I had only one "dad" form, so I knew which type of pointer to put in child form (so it can hold a pointer to parent) and just casted a pointer of it's type.
if (parent) daddy = qobject_cast<InvoiceEd*>(parent);
Now I want to add a call from another form, I realized that I have to cast different pointer out of QWidget* pointer, and I don't know how to determine what's "in disguise" under QWidget* parent pointer. How can I do that?
I suggest using an interface and dynamic_cast to pass the information about the selected item:
InvoiceEdInterface.hpp:
class InvoiceEdInterface {
public:
virtual void SetSelectedItem (SelectedItemClass i_selected_item) = 0;
};
InvoiceEd.hpp:
class InvoiceEd: public InvoiceEdInterface {
public:
void SetSelectedItem (SelectedItemClass i_selected_item) override {
// Process setting selected item.
}
};
DataForm.hpp
class DataForm {
...
void on_tableView_doubleClicked(const QModelIndex &index) {
auto invoice_ed {dynamic_cast< InvoiceEdInterface* >(parent ())};
if (invoice_ed) {
invoice_ed->SetSelectedItem (...);
}
}
...
};
The idea behind the solution is pretty simple: if the parent widget implements the specified interface, that the SetSelectedItem() is called. Otherwise, nothing happens.
Note, however, that the proposed solution may not be Qt-ish. With Qt, you may add a signal that informs about the selected item. When the DataForm object is created in parent widget to select some item, the parent widget should establish a signal-slot connection. This solution is more flexible than the one, proposed above because it lets any object in the program get information about the selected item.
Both of the proposed solution work dynamically without the limitations of the template-based solution.
There is a code in some existing method implementation to resolve the widget type:
// dataform.cpp
void DataForm::myEdit()
{
///
if (parent()) daddy = qobject_cast<InvoiceEd*>(parent());
}
and the author wants to make it more flexible e.g. specifically cast to certain widget type depending on the caller. That can be done. Let's pass the desired type to it:
class DataForm
{
public:
// was void myEdit()
template <typename T = InvoiceEd> // defaults to InvoiceEd
void myEdit()
{
///
T* daddy = qobject_cast<T*>(parent());
// now we operate with the proper pointer so that
// exact instance does virtual function calls etc.
}
///
};
pDataForm->myEdit(); // default case
pDataForm->myEdit<MutatedInvoiceEd>(); // specified case
P.S. The above is without criticizing the design which is questionable. In OOP we don't usually want to know the context the method was called from or the objects don't want to identify each other. You should in this case create two different methods for different uses or maybe provide an additional parameter (maybe with default value void myEdit(bool insideOfContainerEdit = true) so that the code knows about some principal use case. There a number of ways to handle that but we cannot see the entire code of yours.
But of course the very existence of templates in C++ makes us able to solve the problem to degree. I myself find help in templates to sometimes avoid writing more code or derive from the type etc. but overuse of such approach leads to a lot of headache. We ideally should either rely on inheritance with polymorphism or handle such cases entirely via templates with parameter types.
Context
The context is composed by three classes:
abstract parent (e.g. Player)
child (e.g. TapePlayer)
a holder (e.g. MyMachine)
The holder has a member variable that is a shared_ptr<...> to the parent class and a setter for it accepts shared_ptr<...>s of children classes.
My getter looks something like this
shared_ptr<Parent> getChildPtr() {
return parentPtr;
};
but it returns a pointer to the parent, and cannot access child methods.
If I want to do something like the following
holder.getChildPtr()->childMethod();
// ERROR! No member named 'childMethod' in 'Parent'
How should I implement the getter to get the pointer to the child instead of the parent class?
Code
The whole code looks something like this:
class Player {
public:
Player(){};
virtual ~Player{};
virtual void play() = 0;
}
class TapePlayer : public Player {
public:
TapePlayer(){};
virtual ~TapePlayer{};
void play() { ... };
void rewind() { ... };
}
class MyMachine {
public:
MyMachine(); //
~MyMachine();
void setPlayer(shared_ptr<Player> p) {
playerPtr = p;
}
shared_ptr<Player> getPlayer() {
return playerPtr;
};
private:
shared_ptr<Player> playerPtr;
}
MyMachine machine; // the holder
shared_ptr<TapePlayer> tapePtr(new TapePlayer()); // pointer to child
machine.setPlayer(tapePtr); // set holder with pointer to child
machine.getPlayer()->rewind(); // -- ERROR! No member named 'rewind' in 'Player'
// if I want to get the player of that machine to rewind I need
// to dynamic_cast<TapePlayer>() ...
I'm pretty sure there's a better way of doing this than casting to children types. Any ideas?
EDIT
This was a very simplified example. What I'm actually trying to do is this:
My holder class is named Clip. A clip plays something, be it an
image, a video, a sequence of images, some kind of processing with
OpenCv, a vector shape... anything that can be displayed.
All these types of things are Players.
I don't care what type of player the clip holds. I just want it to show it to me. But, some players need tweaking at runtime, like the OpenCv one, that needs tweaking parameters for optimal processing. I cannot implement all methods of all subclasses in the parent class, that would make no sense to me. Why does a video need to have the methods for tweaking OpenCv parameters?
All I need is that both have 'playable' methods, and be able to store them in a map<string, PlayerPtr> to access them at any time or change the player the clip is holding.
The point is that this kind of ruins the polymorphism - even with dynamic_cast, you still need to check that the result is not 0 (i.e. check the actual type) and as you might already know, dynamic_cast is famous for being very slow (and requiring RTTI information built in the executable).
Is there any reason you couldn't add a pure virtual rewind() method to your Player interface? Then you'd just call it and the inherited class could do whatever it decides in that case. Other subclasses might implement it as empty (or it can be even empty by default in the Player itself, so that the subclasses do not have to implement it if they don't need to). Perhaps even some more "generic" virtual function like reset(), restart() etc. which would just call rewind() for the TapePlayer under the hood.
You can of course go even more fancy with more complex solutions like visitor/observer (TapePlayer being RewindObserver and observing a rewind event) etc.
EDIT:
So to address the edit comments - if the different types need tweaking, then again, you can just have a single virtual method tweak() (pure or with default empty impl) and do whatever tweaking is needed. Otherwise you'd anyway end up with a long list of ifs and call tweak methods depending on the actual type.
If the tweaking requires some special parameters, then the situation can be difficult ... one option could be to have a tweaking parameters interface (and call the tweak method with that), but if the params can't be unified you'd need a dynamic cast in the tweak method anyway to cast to the correct params type (this basically leads to double dispatch which in C++ requires casting at some point) ... but anyway that would still require to create different param classes in the calling site which is not that nice.
It also depends when you actually need to setup the tweaking parameters - if it is enough to setup everything when creating the instance (and the tweaking params do not change afterwards), or if it is needed to change them later on. If only needed to setup at startup, then you can have factory classes for the different object types and the factory can setup the params.
(technically you could handle even the necessity of changing the params a similar way, by keeping the setting object types for various player types, the players would keep reference to them as well, assigned when the objects are created, and once they need to be changed, you'd change the settings and call tweak() or update() or similar func to inform the objects that some setting changed and needs to be re-applied)
I have a pretty simple game engine. It uses several singletons(I'll enumerate some of them).
Resource Manager
Render Engine
Events Manager
Factory
etc
These singletons have many calls from one to another. I'll take Events Manager sample usage:
Any object derived from Listener can add itsel as a listener for some events just like this EventsManager->RegisterListener(this, &SomeClass::SomeMethod); (event type is deduced by SomeMethod parameter)
Any other object can fire an event like this EventsManager->PushEvent(SomeEvent);
After some synchronization the event reaches to all listeners. This is very a simple usage for EventsManager when it is singleton.
Similar behavior is with other singletons. I want to remove the singletons, but my main problem is that I want to keep the code simple to use from the "user point of view" as it is now. I read some techniques of doing this, but most of the make the initialization/usage of the classes more complicated. I know this topic was discused many times on SO, but no answer is appropriate for my programming philosophy - to keep everything as simple as possible.
I don't want to have complicated definition/initialization for my classes like:
SomeClass<EventManager, RenderEngine,...>
or
SomeClass::SomeClass(EventsManager, RenderEngine...)
Can you please give me some advice on this topic?
You could have a global "game" object that creates an instance of each of the classes that are currently singletons
For the specific example of your EventManager; your Listener base class could provide implementations of a register method and a push method that derived classes can call.
A skeleton definition:
class Listener
{
public:
virtual void ReceiveMessage( ... ) = 0;
protected:
void Register()
{
GetEventManagerSomehow()->RegisterListener( this, etc );
}
void PushEvent( etc )
{
GetEventManagerSomehow()->PushEvent( etc );
}
}
To solve the specific problem of detecting resource leaks in your singletons, give each singleton class a shutdown method that destroys the instance.
class Singleton
{
// ...
static Singleton * GetInstance()
{
if (instance == NULL)
instance = new Singleton;
return instance;
}
static void Shutdown()
{
delete instance;
instance = NULL;
}
static Singleton * instance;
};
Singleton * Singleton::instance = NULL;
Not really an answer, but maybe too long for a comment.
Dependency injection is a very good alternative to singletons: You create instances in the main function of your program and you pass them to "modules" (which are main classes), so they can use them locally. This means that for these classes you will have the "complicated" constructors that you don't want.
However, The complexity should only be limited to some classes and passing some dependent "modules" are in my point of view not that complex. As a bonus, you can find out dependencies between modules by just looking at the constructors or at the main function.
Dependency injection is used a lot because it does solve the issue that you are seeing (and more, like unit testing) with only a very limited amount of added complexity.
So I understand pretty much how it works, but I just can't grasp what makes it useful. You still have to define all the separate functions, you still have to create an instance of each object, so why not just call the function from that object vs creating the object, creating a pointer to the parent object and passing the derived objects reference, just to call a function? I don't understand the benefits of taking this extra step.
Why do this:
class Parent
{
virtual void function(){};
};
class Derived : public Parent
{
void function()
{
cout << "derived";
}
};
int main()
{
Derived foo;
Parent* bar = &foo;
bar->function();
return -3234324;
}
vs this:
class Parent
{
virtual void function(){};
};
class Derived : public Parent
{
void function()
{
cout << "derived";
}
};
int main()
{
Derived foo;
foo.function();
return -3234324;
}
They do exactly the same thing right? Only one uses more memory and more confusion as far as I can tell.
Both your examples do the same thing but in different ways.
The first example calls function() by using Static binding while the second calls it using Dynamic Binding.
In first case the compiler precisely knows which function to call at compilation time itself, while in second case the decision as to which function should be called is made at run-time depending on the type of object which is pointed by the Base class pointer.
What is the advantage?
The advantage is more generic and loosely coupled code.
Imagine a class hierarchy as follows:
The calling code which uses these classes, will be like:
Shape *basep[] = { &line_obj, &tri_obj,
&rect_obj, &cir_obj};
for (i = 0; i < NO_PICTURES; i++)
basep[i] -> Draw ();
Where, line_obj, tri_obj etc are objects of the concrete Shape classes Line, Triangle and so on, and they are stored in a array of pointers of the type of more generalized base class Shape.
This gives the additional flexibility and loose coupling that if you need to add another concrete shape class say Rhombus, the calling code does not have to change much, because it refers to all concrete shapes with a pointer to Base class Shape. You only have to make the Base class pointer point to the new concrete class.
At the sametime the calling code can call appropriate methods of those classes because the Draw() method would be virtual in these classes and the method to call will be decided at run-time depending on what object the base class pointer points to.
The above is an good example of applying Open Closed Principle of the famous SOLID design principles.
Say you want someone to show up for work. You don't know whether they need to take a car, take a bus, walk, or what. You just want them to show up for work. With polymorphism, you just tell them to show up for work and they do. Without polymorphism, you have to figure out how they need to get to work and direct them to that process.
Now say some people start taking a Segway to work. Without polymorphism, every piece of code that tells someone to come to work has to learn this new way to get to work and how to figure out who gets to work that way and how to tell them to do it. With polymorphism, you put that code in one place, in the implementation of the Segway-rider, and all the code that tells people to go to work tells Segway-riders to take their Segways, even though it has no idea that this is what it's doing.
There are many real-world programming analogies. Say you need to tell someone that there's a problem they need to investigate. Their preferred contact mechanism might be email, or it might be an instant message. Maybe it's an SMS message. With a polymorphic notification method, you can add a new notification mechanism without having to change every bit of code that might ever need to use it.
polymorphism is great if you have a list/array of object which share a common ancestor and you wich to do some common thing with them, or you have an overridden method. The example I learnt the concept from, use shapes as and overriding the draw method. They all do different things, but they're all a 'shape' and can all be drawn. Your example doesn't really do anything useful to warrant using polymorphism
A good example of useful polymorphism is the .NET Stream class. It has many implementations such as "FileStream", "MemoryStream", "GZipStream", etcetera. An algorithm that uses "Stream" instead of "FileStream" can be reused on any of the other stream types with little or no modification.
There are countless examples of nice uses of polymorphism. Consider as an example a class that represents GUI widgets. The most base classs would have something like:
class BaseWidget
{
...
virtual void draw() = 0;
...
};
That is a pure virtual function. It means that ALL the class that inherit the Base will need to implement it. And ofcourse all widgets in a GUI need to draw themselves, right? So that's why you would need a base class with all of the functions that are common for all GUI widgets to be defined as pure virtuals because then in any child you will do like that:
class ChildWidget
{
...
void draw()
{
//draw this widget using the knowledge provided by this child class
}
};
class ChildWidget2
{
...
void draw()
{
//draw this widget using the knowledge provided by this child class
}
};
Then in your code you need not care about checking what kind of widget it is that you are drawing. The responsibility of knowing how to draw itself lies with the widget (the object) and not with you. So you can do something like that in your main loop:
for(int i = 0; i < numberOfWidgets; i++)
{
widgetsArray[i].draw();
}
And the above would draw all the widgets no matter if they are of ChildWidget1, ChildWidget2, TextBox, Button type.
Hope that it helps to understand the benefits of polymorphism a bit.
Reuse, generalisation and extensibility.
I may have an abstract class hierarchy like this: Vehicle > Car. I can then simply derive from Car to implement concrete types SaloonCar, CoupeCar etc. I implement common code in the abstract base classes. I may have also built some other code that is coupled with Car. My SaloonCar and CoupeCar are both Cars so I can pass them to this client code without alteration.
Now consider that I may have an interface; IInternalCombustionEngine and a class coupled with with this, say Garage (contrived I know, stay with me). I can implement this interface on classes defined in separate class hierarchies. E.G.
public abstract class Vehicle {..}
public abstract class Bus : Vehicle, IPassengerVehicle, IHydrogenPowerSource, IElectricMotor {..}
public abstract class Car : Vehicle {..}
public class FordCortina : Car, IInternalCombustionEngine, IPassengerVehicle {..}
public class FormulaOneCar : Car, IInternalCombustionEngine {..}
public abstract class PowerTool {..}
public class ChainSaw : PowerTool, IInternalCombustionEngine {..}
public class DomesticDrill : PowerTool, IElectricMotor {..}
So, I can now state that an object instance of FordCortina is a Vehicle, it's a Car, it's an IInternalCombustionEngine (ok contrived again, but you get the point) and it's also a passenger vehicle. This is a powerful construct.
The poly in polymorphic means more than one. In other words, polymorphism is not relevant unless there is more than one derived function.
In this example, I have two derived functions. One of them is selected based on the mode variable. Notice that the agnostic_function() doesn't know which one was selected. Nevertheless, it calls the correct version of function().
So the point of polymorphism is that most of your code doesn't need to know which derived class is being used. The specific selection of which class to instantiate can be localized to a single point in the code. This makes the code much cleaner and easier to develop and maintain.
#include <iostream>
using namespace std;
class Parent
{
public:
virtual void function() const {};
};
class Derived1 : public Parent
{
void function() const { cout << "derived1"; }
};
class Derived2 : public Parent
{
void function() const { cout << "derived2"; }
};
void agnostic_function( Parent const & bar )
{
bar.function();
}
int main()
{
int mode = 1;
agnostic_function
(
(mode==1)
? static_cast<Parent const &>(Derived1())
: static_cast<Parent const &>(Derived2())
);
}
Polymorphism is One of the principles OOP. With polymorphism you can choose several behavior in runtime. In your sample, you have a implementation of Parent, if you have more implementation, you can choose one by parameters in runtime. polymorphism help for decoupling layers of application. in your sample of third part use this structers then it see Parent interface only and don't know implementation in runtime so third party independ of implementations of Parent interface. You can see Dependency Injection pattern also for better desing.
Just one more point to add. Polymorphism is required to implement run-time plug-ins. It is possible to add functionality to a program at run-time. In C++, the derived classes can be implemented as shared object libraries. The run time system can be programmed to look at a library directory, and if a new shared object appears, it links it in and can start to call it. This can also be done in Python.
Let's say that my School class has a educate() method. This method accepts only people who can learn. They have different styles of learning. Someone grasps, someone just mugs it up, etc.
Now lets say I have boys, girls, dogs, and cats around the School class. If School wants to educate them, I would have to write different methods for the different objects, under School.
Instead, the different people Objects (boys,girls , cats..) implement the Ilearnable interface. Then, the School class does not have to worry about what it has to educate.
School will just have to write a
public void Educate (ILearnable anyone)
method.
I have written cats and dogs because they might want to visit different type of school. As long as it is certain type of school (PetSchool : School) and they can Learn, they can be educated.
So it saves multiple methods that have the same implementation but different input types
The implementation matches the real life scenes and so it's easy for design purposes
We can concentrate on part of the class and ignore everything else.
Extension of the class (e.g. After years of education you come to know, hey, all those people around the School must go through GoGreen program where everyone must plant a tree in the same way. Here if you had a base class of all those people as abstract LivingBeings, we can add a method to call PlantTree and write code in PlantTree. Nobody needs to write code in their Class body as they inherit from the LivingBeings class, and just typecasting them to PlantTree will make sure they can plant trees).
I'm trying to make a button class (abstract) so I can set what function is that button going to trigger when clicked dynamically when my program load.
I want to construct all my buttons by reading XML files, this is to avoid code replication so having only 1 "generic" button class is really useful for me.
I was wondering if you could dynamically pass the necessary information about a method, like a pointer to the method's owner and method in question name, or even better the direct pointer to the method, for a button to call that function/method when clicked ?
Since pointer to function is a runtime artifact you cannot store that in the offline configuration. I see two solutions that might fit what you describe:
put your functions into a dynamic library and load them by name - that way your configuration would map a button to library path/function name pair,
build a "registry" of named function pointers at startup, probably some hash table, so the configuration would map a button to the hash key.
From experience though I would say that building such facilities are usually overkill, and the configuration quickly becomes heavier then the app itself.
Some additional pointers: Boost.Signals, QT Signals, Command and Chain of Responsibility design patterns.
You can create a SetFunctor method in your generic Button class, which accepts a function object as a parameter. Then you create a Call method that calls the function wrapped inside the function object. Something like this:
template<typename FUNC>
class Functor
{
typedef FUNC (*FC)();
FC func;
public:
Functor( FC f ) : func(f) {}
~Functor() {}
FUNC Call() { return func(); }
FUNC operator()() const { return Call(); }
};
class Button
{
std::auto_ptr<Functor<void> > pfunc;
public:
Button() {}
~Button() {}
void SetFunctor( void(*fc)() )
{
pfunc.reset( new Functor<void>( fc ) ); // now owns ptr;
}
void Call()
{
pfunc->Call();
}
};
...
void changeColor()
{
// do work
}
Button obj;
obj.SetFunctor( changeColor );
obj.Call();
Of course I could've used better smart pointers and or better techniques, but this should give you a gist of what I was hinting at. Also note, that this Functor object can only accept functions that have no parameters. You can change this to your liking. I hope it helps!
UPDATE: A few fixes added. Sorry about that!
You are looking for the signal/slot pattern.
In C++ two popular options are boost signals and sigc.
There are a couple of ways to link a button to a function in C++ - you can use function pointers (which are somewhat scary), or a signals and slots pattern which provides the functionality of function pointer with more type safety.
As far as wiring up the function pointers or signals and slots at run time based on a config file, to do this elegantly will require reflection, which C++ doesn't provide for you. I suspect this will be the ugly part.