Passing member function to another object's member function C++ - c++

I am having issues trying to pass a function as an argument in another object's function. I am well aware there are many similar topics but I either can't get their solution to work or can't understand them.
class foo
{
public:
void func1(void (*Drawing)(void));
template<class T>
void func2(void (T::*Drawing)(void));
};
class bar
{
private:
foo myFoo;
void Drawing();
void func3() {
// Attempt 1
myFoo.func1(Drawing);
// Attempt 2
myFoo.func2<bar>(&bar::Drawing);
}
};
So in my first attempt, I get the error where you can't convert void (bar::*)(void) to void (*)(void) of which I then found out there are normal function pointers and member function pointers.
Attempt 2 was my feeble attempt to overcome this but I get unresolved externals now...
So how can I successfully pass my Drawing() member function into another function from another object?

The issue is that you cannot consider bar::Drawing as a void (*)(void) function since it's a non static method, which therefore required an object (the this context which will be used)
A solution, assuming c++11 is ok for you, would be to use std::bind and to sligtly modify your foo definition:
class foo
{
public:
void func1(std::function<void(void)> Drawing)
{
Drawing(); // or do whatever you want with it
}
};
Then you will be able to do
void bar::func3() {
myFoo.func1(std::bind(&bar::Drawing, this));
}
making valid a lot of potential uses
int main()
{
bar myBar;
myBar.func3();
foo myFoo;
myFoo.func1([](){ printf("test\n"); });
return 0;
}

I'm guessing you've left out important details as to what you're trying to accomplish. However, the following should give you some idea of what you need to do.
Code
#include <iostream>
class foo
{
public:
void func1(void (*Drawing)(void))
{
std::cout << "func1\n";
}
template<class T>
void func2(T* instance, void (T::*fn)(void))
{
std::cout << "func2: ";
(instance->*fn)();
}
};
class bar
{
public:
bar()
{
func3();
}
private:
foo myFoo;
void Drawing()
{
std::cout << "bar::Drawing()\n";
}
void func3()
{
// Attempt 1
//myFoo.func1(Drawing); // This won't work
// Attempt 2
myFoo.func2(this, &bar::Drawing); // Must pass an object instance if you plan to use the member function
}
};
int main(int argc, char *argv[])
{
bar b;
return 0;
}
Sample Output
func2: bar::Drawing()

Related

How to Pass a Function to Structure in C++?

My Struct Code :
struct MouseHandler
{
void OnHover();
void* OnLeftClick();
// void (*OnLeftClick)();
void OnRightClick();
void OnDrag();
void OnDrop();
};
Calling of Struct :
MouseHandler ms;
I am trying to pass SampleScrollDownClickHandler to ms.OnRightClick(), Is it is possible, How can I do that, I am tried this, but I failed :
ms.OnRightClick() = SampleScrollDownClickHandler();
I am not using std library!
So the commented out line is actually closer to the solution you want. In order to pass the function pointer you need to not call the function itself, which you did by invoking it with the trailing (). So the following code is closer to what you want (limiting it just to the most basic parts of your code):
struct MouseHandler {
void (*OnLeftClick)();
void OnRightClick();
void OnDrag();
void OnDrop();
};
void my_callback() {
}
int main() {
MouseHandler m;
m.OnLeftClick = my_callback;
}
The member variables of the struct are not defined correctly.
void OnHover(); declares a member function, not a member variable. You need to use void (*onHover)();, which can point to a non-member function.
struct MouseHandler
{
void (*OnHover)();
void (*OnLeftClick)();
void (*OnRightClick)();
void (*OnDrag)();
void (*OnDrop)();
};
With that change, you can use:
MouseHandler me;
me.OnRightClick = SampleScrollDownClickHandler;
as long as SampleScrollDownClickHandler is declared and is the right function type.

Write a function in C++ in which the client decides what function to run from the class?

I've been wondering if it's possible for the client / user to decide what function to run from the class.
For example, Say I have the following function:
std::vector<double> greeks_mesh_pricer(const Greeks& Greek, (function to Run), int mesh_size) {
std::vector<double> result;
for(int i = 0; i < mesh_size; i += mesh_size) {
result.push_back(Greek.(function to run));
}
}
Function to run, is a member function of the Greek class. Greeks here is an interface containing pure virtual functions, so the user is actually passing
in a Derived class of Greeks. So if the client specifies the function Delta(), it returns a vector of Delta() results, etc.
You can do it with pointers to member functions:
#include <iostream>
struct Base {
virtual ~Base() {}
virtual void foo() const = 0;
virtual void bar() const = 0;
};
struct Derived1 : Base {
void foo() const { std::cout << "Derived1::foo\n"; }
void bar() const { std::cout << "Derived1::bar\n"; }
};
struct Derived2 : Base {
void foo() const { std::cout << "Derived2::foo\n"; }
void bar() const { std::cout << "Derived2::bar\n"; }
};
void invoke(const Base &b, void (Base::*func)() const) {
(b.*func)();
}
int main() {
Derived1 d1;
Derived2 d2;
invoke(d1, &Base::foo);
invoke(d2, &Base::foo);
invoke(d1, &Base::bar);
invoke(d2, &Base::bar);
}
Output
Derived1::foo
Derived2::foo
Derived1::bar
Derived2::bar
Windows has implemented that sort of automation with IDispatch, you can implement a similar one if not using Windows. The idea is to specify a function by ID (or translated from a name) and to pass the arguments as VARIANTs.
You might be asking about function pointers in C++. Just like a pointer can be use to reference a variable or object, similarly pointers can be used to reference a function as well and you can also pass a function to a function using these pointers or create an array of pointers where each pointer is actually a function pointer (reference to a function).
Read here : https://www.cprogramming.com/tutorial/function-pointers.html
You can use std::function to represent and store a function. You can also use std::bind and std::placeholder to facilitate the whole thing. Example:
struct A {
int f(int);
int g(int);
};
A instance;
std::function<int(int)> client_fn;
using namespace std::placeholders;
if (...) {
client_fn = std::bind(&A::f, &instance, _1);
} else {
client_fn = std::bind(&A::g, &instance, _1);
}

Can i pass a function from a class to a constructor of another class and store it there to call later? C++

So basically I'm making buttons in a game, and the buttons are a called Button.
The class i want the function from to store is called SoccerLevelsClass. I've tried looking into function pointers, but I'm not sure what's going on though i think it's the correct thing to do.
I want to save the function of SoccerLevelsClass as a member of Button.
Would i do something like this?
//MenuButton.h
#ifndef MenuButton
#define MenuButton
....
class Button
{
public:
Button(void(*SoccerLevelsClass::func)());
void (*SoccerLevelsClass::function)();
....
}
#endif
//MenuButton.cpp
#include <MenuButton.h>
Button::Button(void(*SoccerLevelsClass::func)())
{
function=func; //something like this
}
I know the code is probably way off, but I'd like to know if anybody has any suggestions.
All i really want to know is if it's possible.
Yes, this can be done - either with function pointers like in your example, or with lambdas if you can use C++11.
However, since you want to call a bound function of another class, you would need to pass/store pointer to an instance of that class as well to do that, unless the function is static.
In C++11, this is trivial:
std::function<void(void)> _f;
void apply() {
_f();
}
Bar(void (Foo::* f)()) {
_f = std::bind(f, Foo());
}
In C++03, this is a little tricky. Note in both versions I construct a temporary to call the member function, but I'm not sure whether it is necessary to store an instance of the class.
#include <iostream>
#include <functional>
struct Foo
{
Foo() { }
void stuff() {
std::cout << "hi\n";
}
};
struct Bar
{
void (Foo::* _f)();
void apply() {
(Foo().*_f)();
}
Bar(void (Foo::* f)()) {
_f = f;
}
};
int main()
{
Bar bar(&Foo::stuff);
bar.apply();
}
For what you are trying to do I would use the observer pattern:
class IFootballObserver
{
public:
virtual void OnBallKicked() = 0;
virtual ~IFootballObserver() {}
};
class Fooball
{
public:
Fooball(IFootballObserver& obs)
: mObs(obs)
{
// Call the observer interface at any time like so:
mObs.OnBallKicked();
}
private:
IFootballObserver& mObs;
};
class Button : public IFootballObserver
{
public:
// Football could be passed in/owned by something else
Button() : mFootball(*this) { }
void DoSomething()
{
// Called when foot ball is kicked
}
private:
virtual void OnBallKicked()
{
DoSomething();
}
Fooball mFootball;
};
I find this easier than using function pointers/std::function. Plus you could have a vector of observers and notify many objects of events.

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.

The use case of 'this' pointer in C++

I understand the meaning of 'this', but I can't see the use case of it.
For the following example, I should teach the compiler if the parameter is the same as member variable, and I need this pointer.
#include <iostream>
using namespace std;
class AAA {
int x;
public:
int hello(int x) { this->x = x;}
int hello2(int y) {x = y;} // same as this->x = y
int getx() {return x;}
};
int main()
{
AAA a;
a.hello(10); // x <- 10
cout << a.getx();
a.hello2(20); // x <- 20
cout << a.getx();
}
What would be the use case for 'this' pointer other than this (contrived) example?
Added
Thanks for all the answers. Even though I make orangeoctopus' answer as accepted one, it's just because he got the most vote. I must say that all the answers are pretty useful, and give me better understanding.
Sometimes you want to return yourself from an operator, such as operator=
MyClass& operator=(const MyClass &rhs) {
// assign rhs into myself
return *this;
}
The 'this' pointer is useful if a method of the class needs to pass the instance (this) to another function.
It's useful if you need to pass a pointer to the current object to another function, or return it. The latter is used to allow stringing functions together:
Obj* Obj::addProperty(std::string str) {
// do stuff
return this;
}
obj->addProperty("foo")->addProperty("bar")->addProperty("baz");
In C++ it is not used very often. However, a very common use is for example in Qt, where you create a widget which has the current object as parent. For example, a window creates a button as its child:
QButton *button = new QButton(this);
When passing a reference to an object within one of its methods. For instance:
struct Event
{
EventProducer* source;
};
class SomeContrivedClass : public EventProducer
{
public:
void CreateEvent()
{
Event event;
event.source = this;
EventManager.ProcessEvent(event);
}
};
Besides obtaining a pointer to your own object to pass (or return) to other functions, and resolving that an identifier is a member even if it is hidden by a local variable, there is an really contrived usage to this in template programming. That use is converting a non-dependent name into a dependent name. Templates are verified in two passes, first before actual type substitution and then again after the type substitution.
If you declare a template class that derives from one of its type parameters you need to qualify access to the base class members so that the compiler bypasses the verification in the first pass and leaves the check for the second pass:
template <typename T>
struct test : T {
void f() {
// print(); // 1st pass Error, print is undefined
this->print(); // 1st pass Ok, print is dependent on T
}
};
struct printer {
void print() { std::cout << "print"; }
};
struct painter {
void paint() { std::cout << "paint"; }
};
int main() {
test<printer> t; // Instantiation, 2nd pass verifies that test<printer>::print is callable
t.f();
//test<painter> ouch; // 2nd pass error, test<painter>::print does not exist
}
The important bit is that since test inherits from T all references to this are dependent on the template argument T and as such the compiler assumes that it is correct and leaves the actual verification to the second stage. There are other solutions, like actually qualifying with the type that implements the method, as in:
template <typename T>
struct test2 : T {
void f() {
T::print(); // 1st pass Ok, print is dependent on T
}
};
But this can have the unwanted side effect that the compiler will statically dispatch the call to printer::print regardless of whether printer is a virtual method or not. So with printer::print being declared virtual, if a class derives from test<print> and implements print then that final overrider will be called, while if the same class derived from test2<print> the code would call printer::print.
// assumes printer::print is virtual
struct most_derived1 : test<printer> {
void print() { std::cout << "most derived"; }
};
struct most_derived2 : test2<printer> {
void print() { std::cout << "most derived"; }
};
int main() {
most_derived1 d1;
d1.f(); // "most derived"
most_derived2 d2;
d2.f(); // "print"
}
You can delete a dynamically created object by calling delete this from one of its member functions.
The this pointer is the pointer to the object itself. Consider for example the following method:
class AAA {
int x;
public:
int hello(int x) { some_method(this, x);}
};
void somefunc(AAA* a_p)
{
......
}
class AAA {
int x;
public:
int hello(int x) { this->x = x;}
int hello2(int y) {x = y;} // same as this.x = y
int getx() {return x;}
void DoSomething() { somefunc(this); }
};
this is implicit whenever you use a member function or variable without specifying it. Other than that, there are many, many situations in which you'll want to pass the current object to another function, or as a return value.
So, yeah, it's quite useful.
Sometimes you need to refer to "this" object itself, and sometimes you may need to disambiguate in cases where a local variable or a function parameter shadows a class member:
class Foo {
int i;
Foo* f() {
return this; // return the 'this' pointer
}
void g(){
j(this); // pass the 'this' pointer to some function j
}
void h(int i) {
this->i = i; // need to distinguish between class member 'i' and function parameter 'i'
}
};
The two first cases (f() and g() are the most meaningful cases. The third one could be avoided just by renaming the class member variable, but there's no way around using this in the first two cases.
Another possible use case of this:
#include <iostream>
using namespace std;
class A
{
public:
void foo()
{
cout << "foo() of A\n";
}
};
class B : A
{
public:
void foo()
{
((A *)this)->foo(); // Same as A::foo();
cout << "foo() of B\n";
}
};
int main()
{
B b;
b.foo();
return 0;
}
g++ this.cpp -o this
./this
foo() of A
foo() of B
One more use of this is to prevent crashes if a method is called on a method is called on a NULL pointer (similar to the NULL object pattern):
class Foo
{
public:
void Fn()
{
if (!this)
return;
...
}
};
...
void UseFoo(Foo* something)
{
something->Fn(); // will not crash if Foo == NULL
}
If this is useful or not depends on the context, but I've seen it occasionally and used it myself, too.
self-assignment protection