Function Pointer - Compile time error - c++

I am new to function pointers and I would like your help.
I am having a method:
int test3(int i)
{
return i;
}
Then in another method(not main) I do:
int (*pTest3)(int) = test3;
From the examples that I have read this seems ok.
However, I get a compile time error:
testFile.cpp:277:25: error: argument of type ‘int
({anonymous}::CheckingConsumer::)(int)’ does not match ‘int (*)(int)’
I do not understand what is wrong. Any help would be appreciated.
Thanks a lot.

Your test3 is a member function of a struct or a class. Class member functions have a hidden this parameter passed into them and so cannot be used with plain function pointers. You need to either declare the function as static or move it outside the struct/class, so that it no longer has a hidden this parameter, or use a class method pointer instead of a function pointer:
// static class method:
class X
{
static int test3(int i)
{
...
}
};
// Non-class method, at global scope
int test3(int i)
{
...
}
// Class method pointer
class X
{
int test3(int i)
{
...
}
};
// Create the method pointer
int (X::*pTest3) = &X::test3;
X *obj;
// Call the method pointer on an object
(obj ->* pTest3)(42);

Your method test3 seems to be an instance method. Later on you define pTest3 as function pointer, not as member function pointer.
Main difference between simple pointers and member pointers is that using the member pointer requires an instance of the object. An instance of the object tells what object should be processed and the value of the pointer tells what data field of the object should be used or what member function should be called. Value of the member pointer is conceptually equivalent to the offset from the beginning of the object to its member.
Declaring the member pointer using typedef:
typedef int (SomeClass::*MyMethodPtr)(int i);
MyMethodPtr ptr3 = SomeClass::test3;
Now using this pointer:
class SomeClass *pab = &ab;
int ret_value = (pab->*ptr3)(4);
Note that the instance of the class is used. There is other important point about the member pointers. They are implemented as structs that contain inside from 2 to 5 simple pointers and offsets depending on the compiler and other aspects like multiple inheritance, presence of vitrual base classes, etc.

Related

pass a function pointer between classes

I have two claces.
here is the first one
class one{
one(){ }
public:
void change(double a){
//print a
}
void run(){
two tw;
tw->functionpointer=&change;
}
};
and here is the two class
public two{
two();
static void progresschange(double v){
functionpointer(v);
}
public:
void (*functionpointer)(double);
};
as you see in example I have a function in class one, I want to call it from an static function in class two As progresschange is static I can only call change function in class one uisng function pointers. but It does not work and compiles says
error: cannot convert ‘void (one::*)(double)’ to ‘void (*)(double)’ in assignment
it happens in this line
tw->functionpointer=&change;
how can I make it work. it is even possible to pass a function using its function pointer to another class using this method?
thanks
The error message is quite straightforward:
error: cannot convert void (one::*)(double) to void (*)(double) in assignment
void one::change(double) is a member function of the class one, not just a function. Therefore, you can't assign a pointer to this member function (i.e.: void (one::*)(double)) to a pointer to a function with the same signature (i.e.: to a void (*)(double)).
Besides, a non-static member function (like one::change() above) has to be called on an object, so you also need to provide an one object to call that pointed-to non-static member function.
Basically, you can achieve what you want by adding the following data members in two:
void (one::*mem_func_ptr)(double);
one *obj_ptr;
That is, a pointer to the member function (mem_func_ptr) and a pointer to the object to call this member function on (obj_ptr).
To assign to the member function pointer:
mem_func_ptr = &one::change;
Then, to call the member function pointed by mem_func_ptr on the object pointed by obj_ptr with 0.0 as argument:
(obj_ptr->*mem_func_ptr)(0.0);
It can be done analogously by keeping a copy of an object one as data member instead of a ponter. In that case you should use the operator .* instead of ->*.
The problem is that one::change() is a class member so you need to pass a pointer to a class instance as well.
The modern way to do it is to use std::function, std::bind and std::mem_fn:
class two {
....
std::function<void(double)> functionpointer;
}
tw->functionpointer = std::bind(std::mem_fn(&one::change), _1, one_instance);
Alternatively you can use a lambda function:
tw->functionpointer = [&one_instance](double x) { one_instance->change(x); }

C++ pointer to a function

In my code I would like to call different functions by the same name. So I used pointers, and I did work with static functions, now I would like to do the same with non-static functions and it doesn't work at all.
class Amrorder
: {
public:
....
void (*fkt)(real&, const real);
void fktAcPulse(real &rhoRef, const real y);
void fktAcPulseSol(real &rhoRef, const real y);
...
}
void Amrorder::initData(a)
{
...
switch(method){
case 2://
Amrorder::fkt=&Amrorder::fktAcPulse;
break;
case 222://
Amrorder::fkt=&Amrorder::fktAcPulse1d;
break;
}
...
for(int i=0; i<ng; ++i){
Amrorder::fkt(rhoRef, yRef);
...
}
...
}
The code is quiet big so I hope the part above is enough to understand what I want to do.
Thanks for your time!
It doesn't work because your fkt has type:
void (*)(real&, const real);
and you're trying to assign it to, e.g., &Amrorder::fktAcPulse, which has type:
void (Amrorder::*)(real&, const real);
Notice the difference. The latter is a pointer-to-member function, not just a pointer to function. These have different semantics. A pointer to function can just be called (e.g. fkt(a, b)), but a pointer to member function needs to be called on an object (e.g. (obj.*pm)(a, b)).
For simplicity, since you probably just want "something that I can call with a real& and a const real", you may want to consider the type-erased function object: std::function:
std::function<void(real&, const real)> fkt;
This can be initialized with any callable that matches the arguments, so you can assign it to a free function:
void foo(real&, const real) { ... }
fkt = foo;
A static member function:
struct S { static void bar(real&, const real) { ... } };
fkt = &S::bar;
Or a member function, as long as its bound:
fkt = std::bind(&Amrorder::fktAcPulse, this);
fkt = [this](real& a, const real b){ return this->fktAcPulse(a, b); };
The key is that you need an instance of Amrorder to call fktAcPulse, and using std::function lets you use either std::bind or a lambda to store that instance in with the functor itself.
The type of fkt declares a function pointer to a free-standing function or a static member function. But you want to assign a non-static member function pointer to it. So fkt needs to be of the type of a non-static member function pointer of class Amrorder. That type is spelled
void (Amrorder::*fkt)(real&, const real);
// ^^^^^^^^^^
When invoking a function pointer to a non-static member function, you need to specify on which object you want the member to be called (which normally defaults to this when calling a member function directly with its name).
The syntax for this is quite strange. It requires another pair of parentheses and depends on wether you call it on a pointer or an object itself:
(object.*functionPointer)(arguments);
(pointer->*functionPointer)(arguments);
So if you just want to call the function on the this pointer, you need to write
(this->*fkt)(rhoRef, yRef);
(Note that you don't need to specify the class in your code everywhere. Amrorder:: can be removed in front of every function name inside the definition of a member function of the same class.)
When you call a non-static method of a class, the compiler needs to know which instance of the class you want to execute against. So there is a hidden parameter in the call, which is a pointer to the instance.
So you need to write something like this:
Amrorder::fkt=bind( &Amrorder::fktAcPulse, this );

Scope resolution instead of . operator for template class argument

below given code compiles successfuly:
template <typename T, T nontype_param>
class C;
class X {
public:
int n;
};
int main()
{
C<int X::*, &X::n>* c; //Here
return 1;
}
How the Scope resolution operator works here rather than the . operator? Are we allowed to access a non static member like this?
reference: C++ Templates The Complete Guide , Section 8.3.3 Nontype Arguments
Yes, this code is valid, and the source of your confusion isn't actually related to templates.
int X::* is a pointer-to-member (specifically a pointer to int data member on type X). The pointer itself does not convey an instance of the object, so you can indeed take a pointer to a non-static member. (In fact, a pointer to a static member would just be a regular pointer, not a pointer-to-member!)
You supply the object instance at the time you use the pointer, not at the time you take the pointer.
// Declare a pointer to a data member of type int on object of type X, and
// initialize it to point to the X::n member.
int X::*ptr = &X::n;
// *ptr is not valid on member pointers. Rather, we need to supply an instance:
X instance;
// Then use the member pointer dereference operator .*
(instance.*ptr) = 5; // Same as "instance.n = 5;" in this case.

c++ error: invalid use of member 'calls_object::OBJECT' in static member function

I got the following error from the code below.
error: invalid use of member 'calls_object::OBJECT' in static member function|
error: from this location
from the line OBJECT->call(); line 29.
Basically the function must be static because its really a simplified version of the code
which creates a windows thread. I just can't seem to use pointers within a static function but I can create the object within the static function no problem. Is there another way?
CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)windowsthread, (LPVOID)i, NULL, &m_id);
static DWORD_PTR WINAPI windowsthread()
{
OBJECT->call();
}
l
class object
{
private:
public:
object(){}
~object(){}
void call(){}
};
class calls_object
{
private:
object* OBJECT;
public:
calls_object()
{
OBJECT = new object();
}
~calls_object(){}
#ifdef _WIN32
static void windows_function()
{
OBJECT->call();
}
#endif
};
int main()
{
calls_object O;
}
This function:
static void windows_function()
{
OBJECT->call();
}
Is declared as static. It means it does not receive an implicit this pointers: in other words, it does not operate on an instance of calls_object. Therefore, it cannot see the OBJECT member variable.
Either declare the function as non-static, or declare OBJECT as a static member variable (whatever makes more sense in your application).
Basically the function must be static because its really a simplified version of the code which creates a windows thread
Since you are (unfortunately) dealing with a function (CreateThread) that accepts a function pointer, you cannot even use std::bind. However, CreateThread lets you provide a function which accepts a pointer (to void, see the prototype of ThreadProc).
Just pass a pointer to an object as the fourth argument to CreateThread, and let windowsFunction(void*) receive that pointer. Inside windowsFunction(), which would still be static or global (in fact, you do not need the calls_object class at all), you can cast that pointer to a pointer to object and invoke call() on it.
Also notice, that your class calls_object is leaking memory, since you are forgetting to delete the pointer you created in calls_object's constructor:
~calls_object()
{
delete object; // DON'T FORGET THIS!
}
windows_function is a static member function, so is not associated with any calls_object object. OBJECT is a non-static data member, so is associated with a calls_object object. You cannot access a non-static data member from a data member.
Simply make the function non-static and it will work.
Think of it this way. If you didn't even create an object of type calls_object and your main function was just:
int main()
{
calls_object::windows_function();
}
Where would you expect this function to get OBJECT from? Since OBJECT is a non-static member, it only exists as part of a calls_object object. A static member function cannot simply pull OBJECT from nowhere.

c++ member function pointer problem

I'm new to c++ . I want to know about object pointer and pointer to member function . I wrote a code which is following:
code :
#include <iostream>
using namespace std;
class golu
{
int i;
public:
void man()
{
cout<<"\ntry to learn \n";
}
};
int main()
{
golu m, *n;
void golu:: *t =&golu::man(); //making pointer to member function
n=&m;//confused is it object pointer
n->*t();
}
but when i compile it it shows me two error which is following:
pcc.cpp: In function ‘int main()’:
pcc.cpp:15: error: cannot declare pointer to ‘void’ member
pcc.cpp:15: error: cannot call member function ‘void golu::man()’ without object
pcc.cpp:18: error: ‘t’ cannot be used as a function.
my question are following :
What I'm doing wrong in this code ?
How to make object pointer ?
How to make pointer to member function of a class and how to use them ?
Please explain me these concept.
Two errors corrected here:
int main()
{
golu m, *n;
void (golu::*t)() =&golu::man;
n=&m;
(n->*t)();
}
you want a pointer to function
the priority of the operators is not the one you expected, I had to add parenthesis. n->*t(); is interpreted as (n->*(t())) while you want (n->*t)();
A member function pointer has the following form:
R (C::*Name)(Args...)
Where R is the return type, C is the class type and Args... are any possible parameters to the function (or none).
With that knowledge, your pointer should look like this:
void (golu::*t)() = &golu::man;
Note the missing () after the member function. That would try to call the member function pointer you just got and thats not possible without an object.
Now, that gets much more readable with a simple typedef:
typedef void (golu::*golu_memfun)();
golu_memfun t = &golu::man;
Finally, you don't need a pointer to an object to use member functions, but you need parenthesis:
golu m;
typedef void (golu::*golu_memfun)();
golu_memfun t = &golu::man;
(m.*t)();
The parenthesis are important because the () operator (function call) has a higher priority (also called precedence) than the .* (and ->*) operator.
'void golu:: *t =&golu::man();' should be changed to 'void (golu:: *t)() =&golu::man;' you are trying to use pointer to function not pointer to result of a static function!
(1) Function pointer is not declared properly.
(2) You should declare like this:
void (golu::*t) () = &golu::man;
(3) Member function pointer should be used with object of the class.