(My knowledge is more C# and less C++, so C++ syntax I'm not as familiar with.)
I want to create a class, and I want to pass to the constructor a function, and this function has a class type as a parameter. It's also possible I might want to pass a completely different function, with completely different parameters.
Either way I want the function parameters defined when I create the class.
Perhaps an example would better demonstrate. I'll start with a class definition for a class named MyStateA
, this class will have a method named Execute
, so if I instantiate an instance of class MyStateA
, something like
a = new MyStateA
(syntax is totally wrong here. I'm not even sure if I use new
or I think there's a variation of new
that I should use instead.)
Now say I want to instantiate an instance of class MyStateA
, and I want a.Execute()
to run ChangeStateTo(MyStateB)
So when I instantiate my instance of class MyStateA
, I pass as a parameter ChangeStateTo(MyStateB)
. Something like:
a = new MyStateA( ChangeStateTo(MyStateB) )
The desired end result is when I call
it will run ChangeStateTo(MyStateB)
Then method ChangeStateTo
can instantiate an instance of MyStateB
I just need to get the C+++ syntax right for this.
Notice I'm not passing parameters to a.Execute(), I want a.Execute() to run ChangeStateTo(MyStateB). Or, alternately, I might want a.Execute() to run foobar( 12, "a string", DoStuff(5) )
If the resulting C++ code for this dynamic approach is too convoluted I could fall back to using static classes. The program will have a finite number of classes that can be created. I thought maybe I could save memory space if I dynamically created the classes as I needed them and destroyed them when I was done with them. However, I don't know if behind the scenes that might end up with a lot of memory fragmentation, so perhaps I should just statically create all my classes once and be done with it, especially if it makes the resulting code a lot simpler.
In which case, what would be the C++ syntax for doing the above assuming all the classes are static? That is, just one instance of each class. (I don't think I need to use the Singleton Design Pattern do I? Can't I just declare a class static and start using it?)
A full example would be nice since I'm not as familiar with C++ syntax. (This will be unmanaged C++, not .NET C++. I think the target compiler is a variation of the GNU C++ compiler.)