Counting how many times a function is called - c++

I want to count how many times a function is called, so that if it is called more than once, some error is notified to the developers (via logging, or asserting, and so on). I would like this code to be well defined and isolated so that it is easily portable across many function and member functions as well. Something as easy as:
void function( )
{
if( is_called_more_than_once( ) )
{
// do something to handle the error
}
}
void AClass::method( )
{
if( is_called_more_than_once( ) )
{
// do something to handle the error
}
}
Is it possible in C++, since it does not have reflection, to achieve something like that somehow?

For standalone functions, or static class methods, you can use a static local variable:
void function()
{
static int num_called = 0;
if( ++num_called > 1 )
{
// do something to handle the error
}
...
}
For non-static class methods, use a class data member for each method, allowing individual instances of the class to do their own tracking:
class AClass
{
private:
int num_method1_called;
int num_method2_called;
public:
AClass();
void method1();
void method2();
...
};
AClass::AClass() :
num_method1_called(0),
num_method2_called(0)
{
}
void AClass::method1()
{
if( ++num_method1_called > 1 )
{
// do something to handle the error
}
...
}
void AClass::method2()
{
if( ++num_method2_called > 1 )
{
// do something to handle the error
}
...
}
If the error handling is always the same, consider extracting it to a reusable helper:
struct callTracker
{
int counter;
callTracker() : counter(0) {}
void called()
{
if( ++counter > 1 )
{
// do something to handle the error
}
}
};
void function( )
{
static callTracker tracker;
tracker.called();
...
}
class AClass
{
private:
callTracker method1_tracker;
callTracker method2_tracker;
public:
void method1();
void method2();
...
};
void AClass::method1()
{
method1_tracker.called();
...
}
void AClass::method2()
{
method2_tracker.called();
...
}
Alternatively:
struct singleCallTracker
{
int counter;
singleCallTracker() : counter(0) {}
void called()
{
if( ++counter > 1 )
{
// do something to handle the error
}
}
};
struct multiCallTracker
{
std::map<std::string, singleCallTracker> trackers;
void called(const std::string &name)
{
trackers[name].called();
}
};
void function()
{
static singleCallTracker tracker;
tracker.called();
...
}
class AClass
{
private:
multiCallTracker method_tracker;
public:
void method1();
void method2();
...
};
void AClass::method1()
{
method_tracker.called(__FUNC__);
...
}
void AClass::method2()
{
method_tracker.called(__FUNC__);
...
}

Reflection isn't necessary, because the caller is known as compile time. C++11 has a built-in __func__ which evaluates as a plain-C string that is the unadorned name of the function. There is also typeid(*this).name() to get the mangled name of the class behind *this.
So define a class that maintains a set of strings and has a single method, announce_call. Put an instance of that class in every class you define, possibly by inheriting from someone that has a protected instance.
Call announce_call providing the function name and class name. If the function name is already within the set, log an error with it and the class name. Otherwise add it to the set.
Provide a global instance if desired, for functions that do not belong to classes.
So net per-class syntax cost is: adding an extra base class, adding an extra line at the start of every counted function.
Inheritance provides the main caveat: since this always points to an instance of the thing the function belongs to, if B inherits from A and C owns an instance B but calls a method from A twice, the log will show a double call to A rather than to B.

I think this is as close as you can get with a single macro:
#define if_called_more_than_once() \
static int s_nTimesCalled = 0; if (++s_nTimesCalled > 1)
void function( )
{
if_called_more_than_once()
{
// do something to handle the error
}
}

Related

Provide PV function content when constructing object in C++

In Java you can create an object whilst at the same time providing (or overloading) abstract functions within the object, thus:
ActionListener al = new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Whatever in here
}
};
I really like that way of doing it, and was wondering if there was some similar construct in C++.
Basically I want a base class with a couple of PV functions declared in it (amongst other stuff), and the user to create an instance of that class whilst at the same time providing the body of the PV functions.
I know I could create child classes, but that seems a little clunky for what I need, where each child class would be unique and only be used to make one instance each.
I have thought about providing lamdas to the constructor and using those instead of actual member functions, but that really seems messy and hard for a novice user to get their head around - not to mention that it would be too rigid (I'd also like to be able to override some non-pure virtual functions optionally).
So is child classes the only way to go, or is there some lesser-known construct in some newer C++ standard that I don't know about that could do what I want?
To expand a little - the idea is to have a class like:
class Thread {
// other stuff
public:
virtual void setup() = 0;
virtual void loop() = 0;
// other functions, some virtual but not pure
};
Thread threadOne {
void setup() {
// Init code for this thread
}
void loop() {
// Run code for this thread
}
};
Thread threadTwo {
void setup() {
// Init code for this thread
}
void loop() {
// Run code for this thread
}
};
Obviously not that syntax, but it gives you an idea of how I'd like to use the class.
It's intended to be run on an embedded system with a slimmed-down C++ implementation (it's g++ but without the full STL). End users aren't the brightest bunch, so it has to be kept as simple to understand as possible.
Anonymous child classes are the closest to what I'd like (though still not perfect). I can use CPP macros to help abstract some of the class implementation syntactic sugar which would help.
Here's a compilable construct I have come up with. Is there anything "wrong" with this approach given the constraints above?
#define THREAD(NAME, CONTENT) class : public Thread {\
public:\
CONTENT\
} NAME;
class Thread {
private:
uint32_t stack[256]; // 1kB stack
volatile bool _running;
public:
virtual void setup() = 0;
virtual void loop() = 0;
void start();
void stop();
uint8_t state();
static void spawn(Thread *thr);
void threadRunner();
};
void Thread::spawn(Thread *thread) {
thread->threadRunner();
}
void Thread::start() {
Thread::spawn(this);
}
void Thread::threadRunner() {
_running = true;
setup();
while (_running) {
loop();
}
}
void Thread::stop() {
_running = false;
}
uint8_t Thread::state() {
return 0;
}
THREAD(myThread,
void setup() override {
}
void loop() override {
}
)
void setup() {
myThread.start();
}
void loop() {
}
Obviously it doesn't actually do anything yet - the whole of the threading back-end is a separate issue, and will be ported over from some existing code I wrote a few years back. I am mainly interested in simplifying the interface for the end user.
There is multiple possibilities, but I'd stick with something simple and versatile: callbacks and lambdas instead of virtual function and inheritance.
class ActionListener
{
std::function<void(int)> _action_performed;
public:
template<class CB>
ActionListener(CB cb) : _action_performed(cb) {}
void click() { _action_performed(0); }
};
int main()
{
ActionListener al([](int n) { std::cout << "Action Performed #" << n << "\n"; });
al.click(); // prints "Action Performed #0"
}
live demo
I'd also like to be able to override some non-pure virtual functions optionally
Which, semantically speaking, means providing a default behavior. This is possible:
ActionListener(CB cb) : _action_performed(cb) {} // construct an AL with the given callback
ActionListener() : _action_performed(default_action_performed) {} // construct an AL with a default callback
void default_action_performed(int n) { /*...*/ }
well, as you already mentioned, one way would be child classes.
another way would be providing some std::functions (or lambdas), either in the constructor or have some set functions.
store the function as a member and call this once your "virtual" member function is called: If you want it optional:
class MyBase
{
public:
MyBase();
void SetFunc(const std::function<int()>& myFun)
{
m_myFun = myFun;
}
int MyVirtFunc()
{
if(m_myFun)
{
return m_myFun();
}
else
{
return 42;
}
}
private:
std::function<int()> m_myFun;
}
if you want the functions given mandatory, put them in the constructor:
class MyBase
{
public:
MyBase(const std::function<int()>& myFun)
: m_myFun(myFun) {}
int MyVirtFun() { return m_myFun(); }
private:
const std::function<int()> m_myFun;
}

Can this be refactored for proper Dependency Injection?

I am having troubles refactoring the following code to use proper Dependency injection.
That is because I don't have access on the State Class constructors
My main limitation now is that the inject implementation mapping is done with strings and in case of a typo there will be a nice fat exception.
How can I:
have compile time checks that the implementation indeed exists?
having dynamic map and get rid of the strings
Central point of configuration
here is some sample code to demonstrate the issue
struct IState
{
virtual void Entry() = 0;
virtual void Update() = 0;
};
struct ABase :IState
{
void Entry() override { /* Default implementation..*/ }
void Update() override { /* Default implementation..*/}
};
struct A1 : ABase
{
void Entry() override { /*...*/ }
void Update() override { /*...*/ }
};
struct A2 :ABase
{
void Entry() override { /*...*/ }
};
struct BBase :IState
{
void Entry() override { /* Default implementation..*/ }
void Update() override { /* Default implementation..*/ }
};
struct B1 :BBase
{
void Entry() override { /*...*/ }
};
// This is to return the desired implementation based on a key string
struct SFactory
{
SFactory()
{
// This is the binding of the implementations and the States.
// I don't really like it,
// but I could live with it IF it was the only place
// that the keys "A" "B" were mentioned.
mImplementedStates.insert(std::make_pair("A", std::shared_ptr<IState>(new A2())));
mImplementedStates.insert(std::make_pair("B", std::shared_ptr<IState>(new B1())));
}
static SFactory& GetInstance()
{
static SFactory msInstance;
return msInstance;
}
std::shared_ptr<IState> GetState(std::string implementation) {
auto it = mImplementedStates.find(implementation);
if (it == mImplementedStates.end())
{
throw std::invalid_argument("Unregistered Implementation: " + implementation);
}
return it->second;
}
private:
std::map<std::string, std::shared_ptr<IState>> mImplementedStates;
};
// this is the class that I want to inject functionality. This is a wrapper of the actual implementation.
struct AStateConcrete : ThirdPartyLink
{
// Cannot have my onw constructor because of the library
// The library instantiate me.
private: std::shared_ptr<IState> mState;
public:
// This is how I pick the once by the 3rd party library
void Entry()
{
// this is the ugly part. This "A" wont change however someone
// that wants to create a new implementation has to visit this code
// to know which "id" he should use in the factory. IF he makes a typo
// this will an throw an exception
mState = SFactory::GetInstance().GetState("A");
mState->Entry();
}
void Update()
{
mState->Update();
}
void GoB()
{
//...
}
};
// this is another class that I want to inject functionality. This is a wrapper of the actual implementation.
struct BStateConcrete : ThirdPartyLink
{
// Cannot have my onw constructor because of the library
// The library instantiate me.
private: std::shared_ptr<IState> mState;
public:
// This is how I pick the functionalityCalled once by the 3rd party library
void Entry()
{
mState = SFactory::GetInstance().GetState("B");
mState->Entry();
}
void Update()
{
mState->Update();
}
void GoA()
{
//...
}
};
int main()
{
SFactory::GetInstance();
ThirdPartyStateMachine<ThirdPartyLink, AStateConcrete /*As initial State*/> sm; // D
// A::Entry() is called;
sm->Update(); // A::Update() is called (thus A2::Update();)
sm->GoB();
// B::Entry() is called (Thus B1::Entry();)
sm->Update(); // B::Update() is called (thus B1::Update();)
}
having dynamic map and get rid of the strings
Central point of configuration
Currently you have this mapping/relation:
---> --->
AStateConcrete "A" A2
BStateConcrete "B" B1
You could leave out that intermediate step and directly map:
--->
AStateConcrete A2
BStateConcrete B1
For this, you could replace your map in the factory with
std::map<std::type_info, std::shared_ptr<IState>> mImplementedViews;
and use the typeid operator (which returns the needed std::type_info) to populate it.
Though this won't help you for your first point:
have compile time checks that the implementation indeed exists?
For that you need to encode the information about the available implementations in some type (otherwise the compiler cannot check it). This is some metaprogramming that's a lot of fun, or you use for example boost MPL set.

Specific "getter setter" dedicated object

I'd like to create an object used to store data, restricting read/write access.
For example :
OBJ obj1;
OBJ obj2;
// DataOBJ has 2 methods : read() and write()
DataOBJ dataOBJ1 (obj1);
With the code above, I want obj1 to access write() method, while other OBJ objects (obj2 in this case) should only access the read() method.
Is it possible to create a DataOBJ class restricting rights like that ?
The classical "getter setter" does not suit my needs.
Thanks.
You can control access to write/read by template global reference obj1/obj2 like in this example:
class OBJ {
};
OBJ obj1;
OBJ obj2;
// RESTRICTED ACCESS
class DataOBJBase {
protected:
void write() {}
void read() {}
};
template <OBJ&>
class DataOBJ;
// ALLOW WRITE IF FOR obj1
template <>
class DataOBJ<obj1> : public DataOBJBase {
public:
using DataOBJBase::write;
};
// ALLOW READ IF FOR obj2
template <>
class DataOBJ<obj2> : public DataOBJBase {
public:
using DataOBJBase::read;
};
int main() {
DataOBJ<obj1> dobj1;
dobj1.write(); // cannot read
DataOBJ<obj2> dobj2;
dobj2.read(); // cannot write
}
I think your best bet is defining an interface for the read and write methods, and pass a read-only wrapper object (which implements write by throwing an exception) rather than the real object to anyone who should not get write permission.
Mind you, this does not stop malicious code from dissecting your wrapper object -- if you want to do that, the DataOBJ should live in a different process than the read-only clients, and the RPC mechanism at the process boundary needs to enforce the access permission.
You could do it with a set of different classes, with the "disabled" method throwing an exception.
Something like:
struct DataInterface
{
virtual void read(...) = 0;
virtual void write(...) = 0;
};
struct DataReadOnly : public DataInterface
{
void read(...) { ... }
void write(...) { throw write_not_allowed(); }
};
struct DataReadWrite : public DataInterface
{
void read(...) { ... }
void write(...) { ... }
};
A thought I have and is probably bad practice. Nevertheless, I'll answer the question as asked with something that came to mind:
Static variables.
class Foo
{
private:
int y;
public:
Foo();
~Foo();
void set(int);
int get(void);
};
Foo::Foo()
{
static int c = 0;
++c;
y = c;
}
Foo::~Foo()
{
--y;
}
int Foo::get(void )
{
if(y == 1)
return y;
else
//do return an error code or something
}
void Foo::set(int r)
{
if(y== 2)
y = r;
else
//Do nothing
}
int main()
{
Foo *x1 = new Foo(); //Gets assigned 1
Foo *x2 = new Foo(); //Gets assigned 2
return 0;
}
Edit: For clarification -- I left out the delete's, and what not as well as the logic for properly decrementing on the destruction as my answer is hashing an idea out there, versus coding for the OP.

Passing a function pointer to a function

What should I do if I want to pass a non-static member function of any class as a click function of the button ? Is it possible ? If so what do I need to do ? For example in which ever class (EntityToolGUI over here) the button is initiatlized, I want to set its click action to a non-static member function (a non-static member function of class EntityToolGUI ) of that class.
GUIButton.h
typedef void (*ptr2clickFunc)(void);
class GUIButton : public GUIObject {
private : void (*clickFunc)(void);
public : void setClickFunction(ptr2clickFunc clickFunc);
};
GUIButton.cpp
void GUIButton::setClickFunction(ptr2clickFunc clickFunc)
{
this->clickFunc = clickFunc;
}
EntityToolGUI.h
class EntityToolGUI {
public : EntityToolGUI();
protected : void addAnimation();
}
EntityToolGUI.cpp
void EntityToolGUI::addAnimation()
{
cout<<"add animation"<<endl;
}
EntityToolGUI::EntityToolGUI()
{
....
btnAddAnimation->setClickFunction(&EntityToolGUI::addAnimation);
}
I am getting an error no matching function call to GUIButton::setClickFunction(void (EntityToolGUI::*)())
candidate is void GUIButton::setClickFunction(void (*)())
How do I solve this ?
Most (decent) C code that passes function pointers around use an extra void* argument for passing user context to the function. This is not so common in C++ (as better techniques than function pointers exist), but if you're stuck using function pointers for some reason then it may be appropriate.
typedef void (*ptr2clickFunc)(void*);
class GUIButton : public GUIObject {
private : ptr2clickFunc clickFunc;
private : void * userdata;
public : void setClickFunction(ptr2clickFunc clickFunc, void* userdata);
};
class Foo
{
static void do_foo( void * userdata )
{
Foo* thisptr = static_cast<Foo*>(userdata);
thisptr->foo();
}
void foo() { ... }
};
int main()
{
Foo foo;
GUIButton button;
button.setClickFunction( &Foo::do_foo, &foo );
button.click();
}
EDIT As noted by Bartek, if you're doing this a lot you can extract the static function into a template - it looks a bit like this (untested and probably with minor errrors).
// GUIButton is as before
// Note no static function here
class Foo { void foo(); }
template<typename T, void(T::*FN)() >
void Call( void * data)
{
static_cast<T*>(data)->*FN();
}
int main()
{
Foo f;
GUIButton button;
button.setClickFunction( &Call<Foo,&Foo::foo>, &f );
button.click();
}
If you want to pass obj fun ptr you can use boost::bind and boost::function
http://www.boost.org/doc/libs/1_50_0/libs/bind/bind.html
You cannot pass a pointer to non-static member function as a pointer to a "regular" non-member function. You should either make addAnimation static, or make ptr2clickFunc typedef a pointer to member function.
Note that invoking a pointer to member function is different from invoking a function pointer, because you must supply an instance on which the member pointer is to be invoked.
addAnimation needs to be static function. When the call back function is set the way you are doing it now, the object of class EntityTollGUI is not registered along with the function.
Try this one (C++11):
#include <stdio.h>
#include <stdlib.h>
#include <functional>
class Raiser
{
public:
std::function<void(int)> ev1, ev2;
void RaiseEv1()
{
if (!ev1._Empty())
ev1(44);
}
void RaiseEv2()
{
if (!ev2._Empty())
ev2(66);
}
};
class Handler
{
private:
int id;
std::function<void(int)> h;
public:
Handler(int newId)
{
id = newId;
h = [this](int i)
{
printf("Handler with id = %d captured event!\n", this->GetId());
};
}
void Hook1(Raiser & raiser)
{
raiser.ev1 = h;
}
void Hook2(Raiser & raiser)
{
raiser.ev2 = h;
}
int GetId()
{
return id;
}
};
int main(int argc, char * argv[])
{
Raiser raiser;
Handler handler1(1), handler2(2);
handler1.Hook1(raiser);
handler2.Hook2(raiser);
raiser.RaiseEv1();
raiser.RaiseEv2();
getchar();
}
AFAIK, this is the most you can get with events in C++ without using language extensions.

Several C++ classes need to use the same static method with a different implementation

I need several C++ classes to have a static method "register", however the implementation of register varies between those classes.
It should be static because my idea is to "register" all those classes with Lua (only once of course).
Obviously I can't declare an interface with a static pure virtual function. What do you guys suggest me to do ? Simplicity is welcome, but I think some kind of template could work.
Example of what I would like to achieve
class registerInterface
{
public:
static virtual void register() = 0; //obviously illegal
};
class someClass: public registerInterface
{
static virtual void register()
{
//I register myself with Lua
}
}
class someOtherClass: public registerInterface
{
static virtual void register()
{
//I register myself with Lua in a different way
}
}
int main()
{
someClass::register();
someOtherClass::register();
return 0;
}
Based on how you've described the problem, it's unclear to me why you even need the 'virtual static method' on the classes. This should be perfectly legal.
class SomeClass {
static void register(void) {
...
}
}
class SomeOtherClass {
static void register(void) {
...
}
}
int main(int argc, char* argv[]) {
SomeClass::register();
SomeOtherClass::register();
return 0;
}
Drop the RegisterInterface, I don't think you need it.
If it helps, you could take Hitesh's answer, and add:
struct luaRegisterManager {
template <typename T>
void registrate() {
T::registrate();
// do something else to record the fact that we've registered -
// perhaps "registrate" should be returning some object to help with that
}
};
Then:
int main() {
luaRegisterManager lrm;
lrm.registrate<someClass>();
lrm.registrate<someOtherClass>();
}
More generally, if you want to introduce any dynamic polymorphism in C++, then you need an object, not just a class. So again, perhaps the various register functions should be returning objects, with some common interface base class registeredClass, or classRegistrationInfo, or something along those lines.
Could provide an example of what you feel it is that you need dynamic polymorphism for? Hitesh's code precisely matches your one example, as far as I can see, so that example must not cover all of your anticipated use cases. If you write the code that would be using it, perhaps it will become clear to you how to implement it, or perhaps someone can advise.
Something else that might help:
#include <iostream>
#include <string>
#include <vector>
struct Registered {
virtual std::string name() = 0;
virtual ~Registered() {}
Registered() {
all.push_back(this);
}
static std::vector<Registered*> all;
};
std::vector<Registered*> Registered::all;
typedef std::vector<Registered*>::iterator Iter;
template <typename T>
struct RegisteredT : Registered {
std::string n;
RegisteredT(const std::string &name) : n(name) { T::registrate(); }
std::string name() { return n; }
// other functions here could be implemented in terms of calls to static
// functions of T.
};
struct someClass {
static Registered *r;
static void registrate() { std::cout << "registering someClass\n"; }
};
Registered *someClass::r = new RegisteredT<someClass>("someClass");
struct someOtherClass {
static Registered *r;
static void registrate() { std::cout << "registering someOtherClass\n"; }
};
Registered *someOtherClass::r = new RegisteredT<someOtherClass>("someOtherClass");
int main() {
for (Iter it = Registered::all.begin(); it < Registered::all.end(); ++it) {
std::cout << (*it)->name() << "\n";
}
}
There are all sorts of problems with this code if you try to split it across multiple compilation units. Furthermore, this kind of thing leads to spurious reports from memory leak detectors unless you also write some code to tear everything down at the end, or use a vector of shared_ptr, Boost pointer vector, etc. But you see the general idea that a class can "register itself", and that you need an object to make virtual calls.
In C++ you usually try to avoid static initialisation, though, in favour of some sort of setup / dependency injection at the start of your program. So normally you would just list all the classes you care about (calling a function on each one) rather than try to do this automatically.
Your intentions are noble, but your solution is inkling towards "overengineering" (unless I am missing an obvious solution).
Here is one possibility: You can use the Virtual Friend function idiom For example,
class RegisterInterface{
friend void register(RegisterInterface* x){x->do_real_register();}
protected:
virtual void do_real_register();
}
class Foo : public RegisterInterface{
protected:
virtual void do_real_register(){}
};
class Bar : public RegisterInterface{
protected:
virtual void do_real_register(){}
};
int main(int argc, char* argv[]) {
BOOST_FOREACH(RegisterInterface* ri, registered_interfaces)
{
register(ri);
}
return 0;
}
I know you've already accepted an answer, but I figured I would write this up anyway. You can have self-registering classes if you use some static initialization and the CRTP:
#include <vector>
#include <iostream>
using namespace std;
class RegisterableRoot // Holds the list of functions to call, doesn't actually need
// need to be a class, could just be a collection of globals
{
public:
typedef void (*registration_func)();
protected:
static std::vector<registration_func> s_registery;
public:
static void do_registration()
{
for(int i = 0; i < s_registery.size(); ++i)
s_registery[i]();
}
static bool add_func(registration_func func) // returns something so we can use it in
// in an initializer
{
s_registery.push_back(func);
return true;
}
};
template<typename RegisterableType> // Doesn't really need to inherit from
class Registerable : public RegisterableRoot // RegisterableRoot
{
protected:
static const bool s_effect;
};
class A : public Registerable<A> // Honestly, neither does A need to inherit from
// Registerable<T>
{
public:
static void Register()
{
cout << "A" << endl;
}
};
class B : public Registerable<B>
{
public:
static void Register()
{
cout << "B" << endl;
}
};
int main()
{
RegisterableRoot::do_registration();
return 0;
}
std::vector<RegisterableRoot::registration_func> RegisterableRoot::s_registery;
template <typename RegisterableType> // This is the "cute" part, we initialize the
// static s_effect so we build the list "magically"
const bool Registerable<RegisterableType>::s_effect = add_func(&RegisterableType::Register);
template class Registerable<A>; // Explicitly instantiate the template
// causes the equivalent of
// s_registery.push_back(&A::Register) to
// be executed
template class Registerable<B>;
This outputs
A
B
although I wouldn't rely on this order if I were you. Note that the template class Registerable<X> need not be in the same translation unit as the call to do_registration, you can put it with the rest of your definition of Foo. If you inherit from Registerable<> and you don't write a static void Register() function for your class you'll get a (admittedly probably cryptic) compiler error much like you might expect if there really was such a thing as "static virtuals". The "magic" merely adds the class specific function to the list to be called, this avoids several of the pitfalls of doing the actual registration in a static initializer. You still have to call do_registration for anything to happen.
How about this way? Define an interface class:
// IFoobar.h
class IFoobar{
public:
virtual void Register(void) = 0;
}
Then define the class that handles the register..
// RegisterFoobar.h
class RegisterFoobar{
public:
// Constructors etc...
IFoobar* fooBar;
static void RegisterFoobar(IFoobar& fubar){
foobar = &fubar;
}
private:
void Raise(void){ foobar->Register(); }
}
Now, then define another class like this
// MyFuBar.h
class MyFuBar : IFoobar{
public:
// Constructors etc...
void Register(void);
private:
RegisterFoobar* _regFoobar;
}
Call the code like this:
//MyFuBar.cpp
MyFuBar::MyFuBar(){
_regFoobar = new Foobar();
_regFoobar->RegisterFoobar(this);
}
void MyFuBar::Register(void){
// Raised here...
}
Maybe I have misunderstood your requirements...