Visual Studio 2015 won't let me initialize a function pointer [duplicate] - c++

This question already has answers here:
Function pointer to member function
(8 answers)
Closed 4 years ago.
I'm trying to create a function pointer. My code:
Header file:
#pragma once
#include <stdio.h>
class my_class
{
private:
int function(int x);
int *(*foo)(int);
public:
my_class();
~my_class();
};
css file:
#include "my_class.h"
int my_class::function(int x) {
return 1;
}
my_class::my_class() {
foo = &function;
}
my_class::~my_class()
{
}
But the line inside my_class::my_class() gives this error:
error C2276: '&': illegal operation on bound member function expression
Putting the mouse cursor over the = in said line makes the following tooltip appear:
a value of type "int (my_class::*)(int x)" cannot be assigned to an entity of type "int *(*)int"
How can I get it to work?

What you think the compiler will do for you is an implicit type cast from a pointer to a member function to a pointer to a normal function. But this is not what happens.
A pointer to a member function is usually not used, because the instance of an object is what is assigned a certain amount of memory and thereby a pointer to a member function might not exactly point to the function and might lead to erroneous results.
You can fix it in two ways:
Define your member function as a static function. Static member functions are not attached to any particular object and can be used without the scope resolution operator.
Another probable fix you can use is to use the this pointer to create a pointer to a member function.

Related

Passing a member function to a base class constructor results in "invalid use of non-static function..." [duplicate]

This question already has answers here:
How can I pass a member function where a free function is expected?
(9 answers)
how to pass a non static-member function as a callback?
(8 answers)
Pass Member Function as Parameter to other Member Function (C++ 11 <function>) [duplicate]
(2 answers)
Closed 4 months ago.
I need to change the prototype of a function pointer of a class. So, I was hoping inheriting it and doing the following would work, but it doesn't ("invalid use of non-static member function 'void B::myIntCallback(unsigned int)"):
class A {
public:
typedef void (*intCallback_t)(unsigned int myInt);
A(intCallback_t intCallback) {}
};
class B : A {
public:
typedef void (*charCallback_t)(unsigned char myChar);
B(charCallback_t charCallback) : A(this->myIntCallback) {
charCallback_ = charCallback;
}
private:
charCallback_t charCallback_;
void myIntCallback(unsigned int myInt) {
charCallback_((unsigned char)myInt);
}
};
Does anybody know how I can solve this? I can't change class A.
You are trying to pass a member function (B::myIntCallback) to a function pointer argument. Since the member function needs an object to be called on, his would require some kind of capturing, e.g. a lambda capturing this or an std::bind expression. Unfortunately, neither is possible with a plain function pointer, see also Passing capturing lambda as function pointer.
If possible, you may want to consider changing the class A to accept either a std::function or a template argument as the type of the callback. See also Should I use std::function or a function pointer in C++?.

Problem using pointers to member functions in C++. Compiler says "Reference to non static member function must be called" [duplicate]

This question already has answers here:
C++ Call Pointer To Member Function
(4 answers)
Calling C++ member functions via a function pointer
(10 answers)
Closed 9 months ago.
Consider this class:
class Downloader {
private:
bool video_or_audio;
// other variables [...]
// [...]
void downloadVideo(std::string videoURL);
void downloadAudio(std::string audioURL);
public:
void download();
}
Now, download() is defined this way:
void Downloader::download(){
std::ifstream url_list;
void (*download_func)(std::string) = video_or_audio == 0 ? downloadVideo : downloadAudio; // Compiler says here: "Reference to non static member function must be called".
if(video_or_audio == 0){
url_list.open("video_list.txt");
}
else{
url_list.open("audio_list.txt");
}
std::string url;
while(std::getline(url_list, url)){
download_func(url); // Calling the function pointed by the pointer defined in line 2 of the function download().
}
}
My compiler (clang) says: "Reference to non static member function must be called" in the second line of function download() definition. Why is this happening and how can I solve this problem?
A solution appears to be defining downloadVideo() and downloadAudio() functions to be static in the class declaration. However, if I do so, I cannot access private variables members of class Downloader, that's not desirable, as I need these variables.
Thank you!
Once calling a member function by pointer, you need to provide two things:
Member function itself
Address of particular instance of given class at which the member function to be called (because the function can access class members thus you have to advise which of the instances is the right one)
void (Downloader::*download_func)(std::string) = video_or_audio == 0 ? &Downloader::downloadVideo : &Downloader::downloadAudio; // Correct the signatures.
...
while(std::getline(url_list, url)){
(this->*download_func)(url);
}
So, here we changed download_func from "just function pointer" to a member function pointer. Then, later in the loop body, we call this member function on this instance (however you can pass an instance as a param if necessary).

Visual Studio 'non-standard syntax; use '&' to create a pointer to member' [duplicate]

This question already has answers here:
How can I pass a member function where a free function is expected?
(9 answers)
Closed 6 years ago.
I was trying to call a function with a function pointer where the function pointer is a class member.
I simplifed the code to only showcase the problem but the foo() function in the oiginal code is already writen so I cannot change it.
(In my actual code, foo is from GLFW (glfwSetKeyCallback) and A is an input handler class.)
The code is:
#include <iostream>
// this four line can not be changed
typedef void(*fptr)(int);
void foo(fptr f) {
f(0);
}
void testOutA(int i) {
}
class A {
public:
void testInA(int i) {
}
};
int main()
{
foo(testOutA); // works fine as it should be
A * a = new A();
foo(a->testInA); // ERROR
return 0;
}
The compilation error message is:
ERROR: error C3867: 'A::testInA': non-standard syntax; use '&' to create a pointer to member
The type of the expression a->testInA is a pointer to a non-static member function.
It does not have the same type as fptr, so the compiler emits an error, albeit a cryptic one.
Compilation would pass if testInA were static.
See C++ function pointer (class member) to non-static member function for more details.

unexpected compilation error when passing by reference anonymous instance [duplicate]

This question already has answers here:
How come a non-const reference cannot bind to a temporary object?
(11 answers)
Closed 7 years ago.
Let's say I have a struct :
struct structazauras
{
string bla;
}
And some function (in my case this function is actually a constructor of some class but I don't think this is the issue):
void myfunc(structazauras& mystruct) { }
then some where i call myfunc :
..
myfunc(structazauras());
..
I get an error:
no matching function for call to myfunc(structazauras) candidates are myfunc(structazauras&)
If I change the code to :
structazauras tmp;
myfunc(tmp);
It will work fine.
I feel that he (the compiler) has a problem passing a reference to the anonymous instance if structazauras, but why ? the anonymous instance exist on the stack of the calling function.
That is because you cannot bind a temporary to a non-const reference. Mark your reference as const and it will work.
Also, you are using a standard C++ keyword (struct) in the definition
void myfunc(structazauras& struct) { }
Change the name to something else. Or maybe you meant
void myfunc(struct structazauras&) { }
but the additional struct is superfluous in C++.

C++ Struct internal declaration confusion? [duplicate]

This question already has an answer here:
Factory Pattern: typedef Class *(createClassFunction)(void)
(1 answer)
Closed 8 years ago.
I've come across a declaration inside a C++ Struct{..} that I've never seen before.
Can anyone tell me what it means;
struct DerivedMesh {
char cd_flag;
void (*calcNormals)(DerivedMesh *dm); // <-- What is this?
It kind of looks like it's dereferencing a pointer called calcNormals, but that's all I can make out.
This is a C syntax for declaring function pointers.
In this particular example, DerivedMesh will have a member calcNormals that is a pointer to a function accepting single argument of type DerivedMesh*. It can be called like an ordinary function:
void foo(DerivedMesh* dm) { ... }
DerivedMesh dm;;
// Init members and set calcNormals to actual function
dm.cf_flag = whatever;
dm.calcNormals = foo;
dm.calcNormals(&dm); // calls foo
This
void (*calcNormals)(DerivedMesh *dm);
is class data member definition with name calcNormals that has type of pointer to function of type void( DerivedMesh * )