function pointer is not a function or function pointer - c++

I have following problem:
void MyClass::LoopFunction(vector<Item>& items,void (MyClass::*funcy)(vector<Item>&,int))
{
for(SInt32 i = 0; i < 50; i++)
{
funcy(items,i);
}
}
It says:
Called object type 'void(MyClass::*)(vector<Item>&,int)' is not a function or function pointer
Can anyone help me to find a solution for this?

funcy is a pointer to a member function, so you need to call it on an instance of the class, like this:
(this->*funcy)(items,i);

The thing with non-static member functions is that they have an invisible first argument which the compiler will turn into this inside the member function. This means that you can't call (non-static) member functions without having an object instance to call the member function on.
In your case, if you want to call it using the this objectinside LoopFunction you need to do e.g.
(this->*funcy)(items, i);
If you want to call it on another object instance, you need to pass that object to the function, and use that instead.
Or you could use e.g. std::function and std::bind instead of the member function pointer. Or use a template parameter similar to the way the standard library handles callbacks, and which allows you to pass any callable object to the function (still have to use std::bind if you want to use a non-static member function though).

Related

How do you call a function in a function using std::?

std::vector<char>function(std::string word) {
}
namespace::json getList(){
function();
}
I was just wondering if im suppose to call the function on top by including std::function(argument)
No, you don't need nor should you use the std::function class to call function. The std::function class is more like a function pointer wrapper. It lets you work with functions as data more easily.
For example, std::function<T> func represents some parameterless function that returns an object of type T.
Refer to the documentation for std::function for more information.

C++: How to call a member function pointer that is a member of the same class?

I'm trying to implement more flexibility in my numerics by allowing me to choose different forms of a mathematical function and vary their parameters through instantiating them as objects of a certain class. That class includes certain mathematical functions I may choose plus parameters that I can vary. The constructor of the class sets a member function pointer in the class to a member function according to what mathematical function I want. I want to solely use the pointer to call whatever function it points to by directly using the pointer in my routine.
However, that proved daunting as I didn't know that member function pointers require a certain syntax and seem to work somewhat differently from regular function pointers according to what I could gather. I've experimented quite a bit and constructed myself a minimal example shared below.
#include<iostream>
#include<string.h>
#include<cstdlib>
#include<stdio.h>
class Someclass
{
public:
// constructor to set pointer
Someclass(std::string);
// member function pointer to hold functions
void (Someclass::*fptr)();
// auxiliary function to call testfunction via pointer
void call ();
// testfunction
void foo();
};
// testfunction
void Someclass::foo()
{
printf("foo says hi! \n");
}
// call via specific function
void Someclass::call()
{
(this->*fptr)();
}
// constructor
Someclass::Someclass(std::string name)
{
if(name=="foo")
{
this->fptr = &Someclass::foo;
}
}
int main()
{
Someclass someobject("foo");
someobject.foo(); // direct testfunction call: Works OK
someobject.call(); // call via auxiliary function: Works OK
//(someobject.*fptr)(); // direct pointer dereferencing: Gives Error
return(EXIT_SUCCESS);
}
It shows that I can access the pointer by use of another member function that just calls whatever the pointer points to via use of a this pointer. However, I still can't seem to get the function call to work if I try to use the pointer directly in my main function through the line,
(someobject.*fptr)()
This particular expression leads to my compiler complaining about the scope and if I include the class scope, the compiler mentions invalid use of non-static members. Still, I'm confused as to why my implementation here doesn't work and if it does, how the proper syntax in my problem would be and why that has to be so.
Any insights would be really appreciated.
fptr is a member of the object, not a variable local to main. In such respect member function pointers behave exactly the same as all other variable types. You were so close, and just need to qualify the function pointer name with the object name:
(someobject.*(someobject.fptr))();
The reasons for this is .* indicates a pointer to member function and does not directly reference the members of an object like the . and .-> operators. Since fptr is a member of Someclass and not a local variable you need to reference it directly like so
(someobject.*someobject.fptr)();

Why is the "this" prefix required when invoking a member function via a function pointer?

AFAIK, in C++, invoking another member function within a member of function of the same class should not require the "this" prefix as it is implicit. However, in the specific case of using function pointers, the compiler requires it. The following code compiles correctly only if I include the "this" prefix for the call via func pointer -
When function pointers are used can the compiler deduce when it points a member func of the same class?
class FooBar
{
private:
int foo;
public:
FooBar()
{
foo = 100;
}
int GetDiff(int bar)
{
return abs(foo - bar);
}
typedef int(FooBar::*MyFuncPtr)(int);
void FooBar::Bar()
{
MyFuncPtr f = &FooBar::GetDiff;
(this->*f)(10);
GetDiff(10);
}
};
It's required, because member function pointers (which are not the same thing as function pointers) are not bound, and you can use them with different objects.
(this->*f)(10);
(foo.*f)(10);
// etc.
When you invoke an instances member function the this pointer is implicitely put to the function parameters. Thus you need to specify this also when invoking that function via a function pointer.
f isn't a member of the class, but a local variable, you could also specify another instance pointer instead of this, so the compiler can't deduce that. Same for member function pointers as class member variables.
The simple question is that it is a matter of language design and the language was designed this way.
Inside a member function, and to ease the common syntax when the compiler encounters an identifier it performs lookup starting from this class (plus ADL on the arguments), and if the lookup finds an unambiguous non-static member of this type (or of a base type) then the compiler will inject this-> for you (that is, applies operator-> to the this pointer).
In the case of a pointer to member the process is quite different. The pointer (which is not really a pointer, but for the sake of argument) is found by lookup, but it is your responsibility to provide the object on which it will be called and use the appropriate operator (either .* for calling a pointer to member on a reference, or ->* for calling the member on a pointer).
Note that the operators that are called are different, and that the process is different altogether (in one case lookup finds a member, in the other it finds a variable that happens to be pointer-to-member), but the most important part is that calling pointers to members is infrequent enough, and calling them on this is even less frequent that it does not not to warrant an exemption on the syntax for a small use case.
f isn't a member of FooBar. So if you want to call f on an instance of FooBar, you have to tell it which instance.
In your example, f does contain a member of FooBar, but the compiler doesn't know that.
This happens because of the way the C++ runtime handles classes while you are not looking.
Basically it would be inefficient to store the function pointers in the instance, so the compiler builds a class specific table with function pointers that have the same arity as the member functions you defined and that get the this pointer passed at runtime (AFAIK visualc passes the pointer via ecx, I'm not entirely sure what happens on GCC)
So basically when you do
instance->foo(10);
You are telling the runtime to call function foo with the parameter 10 and pass (instance) as the this pointer, wich is why you have to specifically say which object it has to be called on.

Help needed in Use of Function pointer in C++

i have made a sample example, in this i'm trying to pass a function as argument i am getting error, could you please help me
typedef void (*callbackptr)(int,int);
class Myfirst
{
public:
Myfirst();
~Myfirst();
void add(int i,callbackptr ptr)
{
ptr(i,3);
}
};
class Mysec
{
public:
Myfirst first_ptr;
Mysec();
~Mysec();
void TestCallback()
{
callbackptr pass_ptr = NULL;
pass_ptr = &Mysec::Testing;
first_ptr.add(2,&Mysec::Testing);
}
void Testing(int a,int b)
{
int c = a+b;
}
};
The type of the callback function you're passing as parameter is not defined as part of a class. You probably should define Testing as static.
You are geting an error because you are pointing to a member function. Pointers to member functions are different. See here:
http://www.parashift.com/c++-faq-lite/pointers-to-members.html#faq-33.1
A member function needs to know what instance it is working with (the this pointer) so it can't be called like any other function. If you moved the callback function out of the class (or made it static, which is similar to moving it out of the class) you could call it like any other function.
A more modern way of doing this is to use functors, e.g. boost::function and something like boost::bind :
C++ Functors - and their uses
how boost::function and boost::bind work
Those can hide the difference between member and global functions.
You are trying to access a member function pointer here, using a simple function pointer typedef, which will not work. Let me explain.
When you write a normal, non-member function (similar to C), the function's code actually exists in a location indicated by the name of the function - which you would pass to a function pointer parameter.
However, in the case of a member function, all you have is the class definition; you don't have the actual instance of the class allocated in memory yet. In such a function, since the this pointer is not yet defined, any reference to member variables wouldn't make sense, since the compiler doesn't have enough information to resolve their memory locations. In fact, member function pointers are not exact addresses; they encode more information than that (which may not be visible to you). For more, read Pointers to Member Functions.

Why callback functions needs to be static when declared in class

I was trying to declare a callback function in class and then somewhere i read the function needs to be static but It didn't explain why?
#include <iostream>
using std::cout;
using std::endl;
class Test
{
public:
Test() {}
void my_func(void (*f)())
{
cout << "In My Function" << endl;
f(); //Invoke callback function
}
static void callback_func()
{cout << "In Callback function" << endl;}
};
int main()
{
Test Obj;
Obj.my_func(Obj.callback_func);
}
A member function is a function that need a class instance to be called on.
Members function cannot be called without providing the instance to call on to. That makes it harder to use sometimes.
A static function is almost like a global function : it don't need a class instance to be called on. So you only need to get the pointer to the function to be able to call it.
Take a look to std::function (or std::tr1::function or boost::function if your compiler doesn't provide it yet), it's useful in your case as it allow you to use anything that is callable (providing () syntax or operator ) as callback, including callable objects and member functions (see std::bind or boost::bind for this case).
Callbacks need to be static so that they don't have an implicit this parameter as the first argument in their function signature.
Non-static methods require a 'this' instance, and can only be called upon an object instance.
However, it is possible to use non-static callbacks, but they are syntactically much harder to write. See http://www.newty.de/fpt/callback.html#member for an explanation.
Marshal Cline gives you the complete answer here
. The whole section contains everything you need to know.
To summarize it can explain that you need a static member because the this pointer isn't needed (unlike normal member methods). But it also covers that using a static may not be enough for all compilers since C++ calling convention might be different between C and C++.
So the recommendation is to use an extern "C" non-member function.
It needs to be static so that the function signature matches. When a member function is called, a hidden parameter is included in the call (i.e. the "this" pointer). In static member functions the this pointer is not passed as a parameter.
If you use function pointers, the runtime environment can't pass a reference to an instance when calling the function. But you may use std::mem_fun<>, in to use functors and member methods.