how to call function to pointer of a class? - c++

class A;
class B;
class B
{
public:
void fn1(void (A::*fn)() )
{
//(*A::fn) ();how to call fn()?
}
};
class A
{
B *b;
public:
A():b(new B){}
void fn2()
{
cout<<"fn2"<<endl;
}
void fn3()
{
b->fn1(&A::fn2);
}
};
int main()
{
A a;
a.fn3();
}
I was asked this question in an interview: how to call fn2() from fn1(). That is what I am trying to solve. Can someone help me with that?
My main objective is to call fn2() from fn1(); if any other way is possible, please mention that

Pointers-to-member-functions need an object to call the function on.
The quickest change to your code is to simply pass in a pointer to the object you want to use. I assume that's the A that you called fn3 on.
So:
void fn1(void (A::*fn)(), A* ptr)
{
(ptr->*fn)(); // Yeah, the syntax is kind of weird
}
and:
void fn3()
{
b->fn1(&A::fn2, this);
}
(live demo)
In an interview I'd give this solution, then discuss how in modern C++ we'd prefer to have fn1 take a std::function (or a template callable), and bind the argument using std::bind or pass a lambda.

Related

Binding a class method to a method of another class

I have two classes where one is logic and one is the model. After initializing both, I would like to bind a b.funB()to a.funA() where A a; B b;.
class A{
public:
bool funA() { doStuff(); }
}
class B{
public:
bool funB();
Template<class T>
void bindBtoA((bool (B::*fun2)(), bool (T::*fun1)(), T *t){
funB=std::bind( ?);
// (fun1, t), (&T::fun1, &t), (T::fun1, t), ... ?
}
}
How do I bind these correctly and get rid of "can't convert" errors (I did use typedef in my actual code)
An answer using lambda is acceptable. But, funB needs to be a callable as another engine needs to grab this (hint: Q_INVOKABLE), so using std::function for A::funA might not work for my case.
You can achieve this via the magic of std::function, which would be hidden inside class B and type-erases the function to be called, thereby giving you the generality you seek.
Here's a fully-worked example:
#include <iostream>
#include <functional>
class A
{
public:
bool funA () { std::cout << "funA\n"; return true; }
};
class B
{
public:
bool funB ()
{
return f ();
}
template <class T>
void bindBtoA (bool (T::*fun1) (), T *t)
{
f = [t, fun1] { return (t->*fun1) (); };
}
private:
std::function <bool ()> f;
};
int main()
{
A a;
B b;
b.bindBtoA <A> (&A::funA, &a);
std::cout << b.funB ();
}
Live demo
I would think this would work with Q_INVOKABLE, but I don't actually know anything about it so you'd have to try it. But if it does work, it's a good way to do it.
Note: With the code as posted, you are responsible for keeping a alive for as long as b is alive. If you can't guarantee that, a better bet would be to use a std::shared_ptr instead. Or copy a inside bindBtoA if that is a practical solution for you (which I'm guessing it isn't).

C++ invalid function type casting

I've read several topics about that kind of problem - but can't find a simple and good solution. Here is the code:
void SomeFunction() { }
class A {
public:
typedef std::function<void(void)> AFunction;
static void AMethod(AFunction f) { f(); }
};
class B {
public:
void B1Method() { }
void BCorrectCall() { A::AMethod(SomeFunction); }
void BIncorrectCall() { A::AMethod(B1Method); }
};
Problem is here void BIncorrectCall() { A::AMethod(B1Method); }, where I receive error about invalid casting. What is the simplest way to achieve that kind of behaviour? Thanks a lot for any advice!
Use a lambda:
A::AMethod([this]{B1Method();});
It doesn't matter in this case, but if you wanted to store AFunction f and use it after the call to AMethod, you'd have to ensure that the B instance (the address of which is saved in the lambda) says alive as long as you use the function.
C++17 allows you to capture *this instead, which will copy the entire B instance into lambda, but normally it's not what you want.
You could do something similar with std::bind (see the other answer), but lambdas are more flexible.
B1Method is not void(*)(void), it's void(B1::*)(void).
You may do
void BIncorrectCall() { A::AMethod(std::bind(&B1::B1Method, this)); }
};
The issue is that B::B1Method() is a non-static member function in B and, therefore, it needs to be called on an instance of B.
If the implementation of B1Method() doesn't use any non-static data member of B and it doesn't call any other non-static member function of B, then simply declaring it as static will work with your current implementation of BIncorrectCall() as you will no longer need to call B1Method() on an instance of B:
class B {
public:
static void B1Method() { } // static now
void BCorrectCall() { A::AMethod(SomeFunction); }
void BIncorrectCall() { A::AMethod(B1Method); } // no change
};
Otherwise, you have to keep an object of type B whenever you want to call B1::B1Method().
The easiest way is to make it static and so there is no this object, but if you need it (the this object), you can use lambdas:
class B {
public:
void B1Method() { }
void BCorrectCall() { A::AMethod(SomeFunction); }
void BIncorrectCall() {
std::function<void(void)> el = [&](){this->B1Method();};
A::AMethod(el);
}
};
The problem is that 'B1Method' is not a simple function - it's a class method. That means that when you call myB.B1Method(), you're actually calling 'B1Method(&myB)', effectively passing the this pointer as a hidden argument - so you can't convert M1Method to a std::function without specifying which object it should act on.
One approach that should work is using std::bind to construct a callable object from a combination of an object (class instance) and the method. Something like:
void BNowCorrectCall() { A::AMethod(std::bind(&B::B1Method, this)); }

How to call a class member function recursively from its own defintion in C++?

I'm new to C++ and I need a class member function to call itself from its own definition, like this -
class MyClass {
public: // or private: ?
// Some code here
// ...
void myfunction();
// ...
};
void MyClass::myfunction()
{
// Some code here
// ...
// Call MyClass::myfunction() here, but how?
// ...
}
but I don't know the proper syntax for it and how can it be called by itself without creating an object usually done like this - object_name.member_function(), if possible?
And, will there be any difference if myfunction() belongs to public: or private:?
Since the function isn't static, you already do have an instance to operate on
void MyClass::myfunction()
{
// Some code here
// ...
this->myfunction();
// ...
}
You could leave the this-> off, I was just being more clear about how the function is able to be called.
myfunction() is in the scope of the class, so you can "simply" call it:
class MyClass {
public:
// Some code here
// ...
void myfunction();
// ...
};
void MyClass::myfunction()
{
myfunction();
}
Note, however, that this will give a stack overflow. You need a means to stop the recursion.
Member functions are actually a form of syntactic sugar. They describe a function that somehow secretly takes a pointer to an object instance which, inside the function, is accessible as this.
struct Foo {
vod bar();
};
Foo foo;
foo.bar();
What you're really doing in the call here is calling a Foo::bar(&foo); and bar is really taking a pointer Foo* this. How that's done varies from implementation to implementation, some compilers/architectures will use a special register to track the current object.
An additional piece of syntactic sugar makes all member variables and functions visible to you within a member function as though they are locally scoped
struct Foo {
int i;
int add(int n) {
return i + n;
}
int addx2(int n) {
return add(n) * 2;
}
};
What's actually happening here is:
return this->i + n;
and
return this->add(n) * 2;
This means its very easy to run into situations where you have conflicts between local and member names.
struct Foo {
int i;
Foo(int i) {
i = i; // not what you expected
}
};
For this reason, many engineers make careful use of case or prefixes or suffixes to help them distinguish members, parameters and variables.
struct Foo { // Uppercase for types and functions
int m_i; // m_ for member
Foo(int i_, int j_) {
int i = sqrt(i));
m_i = i + j_;
}
int Add(int i) {
return i_ + i;
}
};
There are various different patterns people use - some people use _name to denote a member, some use name_ and fn_ to denote members.
struct Foo {
int i_;
int add_(int _i) {
return i_ + _i;
}
};
The main thing is to be consistent.
but I don't know the proper syntax for it and how can it be called by itself without creating an object usually done like this - object_name.member_function(), if possible?
Use:
void MyClass::myfunction()
{
// Some code here
// ...
// Call MyClass::myfunction() here, but how?
// One way to call the function again.
this->myfunction();
// ...
}
this->mufunction() can be replaced by myfunction(). Use of this is a stylistic option that makes the code easier to read for some, like me.
And, will there be any difference if myfunction() belongs to public: or private:?
No, there won't be. You can call any member function of the class from another member function.

Passing any generic function as a C++ argument [duplicate]

This question already has answers here:
Function pointer to member function
(8 answers)
Closed 8 years ago.
I'm trying to pass any generic function as an argument in a C++ function. As an extra layer of fun, the function is going to reside in its own separate class. In this particular case, they will all take no arguments and return void. This includes members of any generic class.
My current code reads like:
class functionsFedHere {
public:
void (*callback)();
functionsFedHere(void(*)());
}
functionsFedHere::functionsFedHere (void(*callbackFunction)()) {
callback = callbackFunction;
}
void fn1() { cout<<"Fn1"<<endl; }
class myClass {
public:
int i;
void fn2() { cout<<i<<endl; }
}
class myOtherClass {
public:
string j;
void fn3() { cout<<j<<endl; }
}
int main() {
// Initialise some objects
myClass b;
b.i = 2;
myOtherClass c;
c.j = "some text";
// Works fine with non-member functions
functionsFedHere objectA(fn1);
objectA.callback();
// Doesn't work with member functions
functionsFedHere objectB(b.fn2);
functionsFedHere objectC(c.fn3);
}
I've seen solutions like a forwarding function, or boost::bind, but as far as I can tell, I don't think these solutions will fit?
It's also worth noting that eventually I'd like to pass member functions by way of an array of pointers. For example, if myPointer[] is an array of pointers to objects of class myClass, then it would be nice to be able to write something like:
functionsFedHere objectD(myPointer[0]->fn2);
EDIT: Apparently I wasn't clear enough. This answer is not an appropriate answer, because I'm looking to pass both member and non-member functions as arguments (whereas the suggested answer is setting up a member pointer to a function that is a member of the same class).
I don't think that the forward function example will work, because the forwarding function assumes a single class type, where I'd like to pass an object of generic class.
boost::bind could well be the answer; I'm just unfamiliar with it. Can anyone point me towards some newbie-friendly reading material?
EDIT 2: Sorry, forgot to mention I'm programming on a device that is pre-C++11.
Use std::function:
class functionsFedHere {
public:
typedef std::function<void()> Func;
Func callback;
functionsFedHere(Func callback_) : callback(callback_) {}
};
void fn1() { cout<<"Fn1"<<endl; }
class myClass {
public:
int i;
void fn2() { cout<<i<<endl; }
};
class myOtherClass {
public:
string j;
void fn3() { cout<<j<<endl; }
};
class callableClass {
public:
void operator()() { std::cout << "in callableClass" << std::endl; }
};
int main() {
// Initialise some objects
myClass b;
b.i = 2;
myOtherClass c;
c.j = "some text";
// Works fine with non-member functions
functionsFedHere objectA(fn1);
objectA.callback();
// Works with member functions now
functionsFedHere objectB(std::bind(&myClass::fn2, b));
objectB.callback();
functionsFedHere objectC(std::bind(&myOtherClass::fn3, c));
objectC.callback();
// Works with lambdas as well
functionsFedHere objectLambda([]() { std::cout << "in lambda" << std::endl; });
objectLambda.callback();
// Works also with classes with overloaded operator()
functionsFedHere(callableClass()).callback();
return 0;
}

Object-Oriented Callbacks for C++?

Is there some library that allows me to easily and conveniently create Object-Oriented callbacks in c++?
the language Eiffel for example has the concept of "agents" which more or less work like this:
class Foo{
public:
Bar* bar;
Foo(){
bar = new Bar();
bar->publisher.extend(agent say(?,"Hi from Foo!", ?));
bar->invokeCallback();
}
say(string strA, string strB, int number){
print(strA + " " + strB + " " + number.out);
}
}
class Bar{
public:
ActionSequence<string, int> publisher;
Bar(){}
invokeCallback(){
publisher.call("Hi from Bar!", 3);
}
}
output will be:
Hi from Bar! 3 Hi from Foo!
So - the agent allows to to capsule a memberfunction into an object, give it along some predefined calling parameters (Hi from Foo), specify the open parameters (?), and pass it to some other object which can then invoke it later.
Since c++ doesn't allow to create function pointers on non-static member functions, it seems not that trivial to implement something as easy to use in c++. i found some articles with google on object oriented callbacks in c++, however, actually i'm looking for some library or header files i simply can import which allow me to use some similarily elegant syntax.
Anyone has some tips for me?
Thanks!
The most OO way to use Callbacks in C++ is to call a function of an interface and then pass an implementation of that interface.
#include <iostream>
class Interface
{
public:
virtual void callback() = 0;
};
class Impl : public Interface
{
public:
virtual void callback() { std::cout << "Hi from Impl\n"; }
};
class User
{
public:
User(Interface& newCallback) : myCallback(newCallback) { }
void DoSomething() { myCallback.callback(); }
private:
Interface& myCallback;
};
int main()
{
Impl cb;
User user(cb);
user.DoSomething();
}
People typically use one of several patterns:
Inheritance. That is, you define an abstract class which contains the callback. Then you take a pointer/reference to it. That means that anyone can inherit and provide this callback.
class Foo {
virtual void MyCallback(...) = 0;
virtual ~Foo();
};
class Base {
std::auto_ptr<Foo> ptr;
void something(...) {
ptr->MyCallback(...);
}
Base& SetCallback(Foo* newfoo) { ptr = newfoo; return *this; }
Foo* GetCallback() { return ptr; }
};
Inheritance again. That is, your root class is abstract, and the user inherits from it and defines the callbacks, rather than having a concrete class and dedicated callback objects.
class Foo {
virtual void MyCallback(...) = 0;
...
};
class RealFoo : Foo {
virtual void MyCallback(...) { ... }
};
Even more inheritance- static. This way, you can use templates to change the behaviour of an object. It's similar to the second option but works at compile time instead of at run time, which can yield various benefits and downsides, depending on the context.
template<typename T> class Foo {
void MyCallback(...) {
T::MyCallback(...);
}
};
class RealFoo : Foo<RealFoo> {
void MyCallback(...) {
...
}
};
You can take and use member function pointers or regular function pointers
class Foo {
void (*callback)(...);
void something(...) { callback(...); }
Foo& SetCallback( void(*newcallback)(...) ) { callback = newcallback; return *this; }
void (*)(...) GetCallback() { return callback; }
};
There are function objects- they overload operator(). You will want to use or write a functional wrapper- currently provided in std::/boost:: function, but I'll also demonstrate a simple one here. It's similar to the first concept, but hides the implementation and accepts a vast array of other solutions. I personally normally use this as my callback method of choice.
class Foo {
virtual ... Call(...) = 0;
virtual ~Foo();
};
class Base {
std::auto_ptr<Foo> callback;
template<typename T> Base& SetCallback(T t) {
struct NewFoo : Foo {
T t;
NewFoo(T newt) : t(newt) {}
... Call(...) { return t(...); }
};
callback = new NewFoo<T>(t);
return this;
}
Foo* GetCallback() { return callback; }
void dosomething() { callback->Call(...); }
};
The right solution mainly depends on the context. If you need to expose a C-style API then function pointers is the only way to go (remember void* for user arguments). If you need to vary at runtime (for example, exposing code in a precompiled library) then static inheritance can't be used here.
Just a quick note: I hand whipped up that code, so it won't be perfect (like access modifiers for functions, etc) and may have a couple of bugs in. It's an example.
C++ allows function pointers on member objects.
See here for more details.
You can also use boost.signals or boost.signals2 (depanding if your program is multithreaded or not).
There are various libraries that let you do that. Check out boost::function.
Or try your own simple implementation:
template <typename ClassType, typename Result>
class Functor
{
typedef typename Result (ClassType::*FunctionType)();
ClassType* obj;
FunctionType fn;
public:
Functor(ClassType& object, FunctionType method): obj(&object), fn(method) {}
Result Invoke()
{
return (*obj.*fn)();
}
Result operator()()
{
return Invoke();
}
};
Usage:
class A
{
int value;
public:
A(int v): value(v) {}
int getValue() { return value; }
};
int main()
{
A a(2);
Functor<A, int> fn(a, &A::getValue);
cout << fn();
}
Joining the idea of functors - use std::tr1::function and boost::bind to build the arguments into it before registering it.
There are many possibilities in C++, the issue generally being one of syntax.
You can use pointer to functions when you don't require state, but the syntax is really horrid. This can be combined with boost::bind for an even more... interesting... syntax (*)
I correct your false assumption, it is indeed feasible to have pointer to a member function, the syntax is just so awkward you'll run away (*)
You can use Functor objects, basically a Functor is an object which overloads the () operator, for example void Functor::operator()(int a) const;, because it's an object it has state and may derive from a common interface
You can simply create your own hierarchy, with a nicer name for the callback function if you don't want to go the operator overloading road
Finally, you can take advantage of C++0x facilities: std::function + the lambda functions are truly awesome when it comes to expressiveness.
I would appreciate a review on lambda syntax ;)
Foo foo;
std::function<void(std::string const&,int)> func =
[&foo](std::string const& s, int i) {
return foo.say(s,"Hi from Foo",i);
};
func("Hi from Bar", 2);
func("Hi from FooBar", 3);
Of course, func is only viable while foo is viable (scope issue), you could copy foo using [=foo] to indicate pass by value instead of pass by reference.
(*) Mandatory Tutorial on Function Pointers