Passing an object as a parameter in C++ - c++

I'm currently running into a few problems surrounding passing an objects return value through a function. My function is prototyped in .h and defined in .cpp. the function for example Class::function(int value); takes in an integer of value. When I'm calling the object objectName name; and passing it through as Class::function(name);.
// foo.h
class foo
{
void function(int value);
}
//foo.cpp
void foo::function(int value)
{
// CODE HERE
}
//main.cpp
int main()
{
objectName name;
foo::function(name);
}
The errors that I am receiving go along the lines of:
Main.cpp:43:23: error: no matching function for call to ‘class::function(objectName&)’
name.function(name); // passes value to the function

The call foo::function(name); is triple wrong.
It's a call to a static function, but function is not static, so you need a instance of foo to call the function:
foo myFoo;
myFoo.function(0);
function is private, so it can not be used, outside of foo. All class members are by default private, so you need to declare it as public:
class foo {
public:
void function(int);
}
function takes an int as parameter, but you pass some object of type objectName. That's more a design issue, what parameter should function take? int or objectName?
Maybe you want
//header
class foo {
public:
void function(objectName &);
}
// cpp
void foo::function(objectName &value) {
}

The declaration and definition of foo is correct. However, that is not how you create and use objects in C++.
int main() {
foo foo_obj; // Create an object of type 'foo' named 'foo_obj'
foo_obj.function(1); // call function named 'function' on the object 'foo_obj'
// and pass integer (=1) as an argument
return 0;
}
You should definitely pick up a good C++ book

I see an allocated variable named name, and it has a type objectName.
I see no allocation of any other objects, especially of type foo.
You can't call a class method, like foo::function() without an object of type foo. (except static declarations, which you are not using and do not need)
Mainly, that error you see is because you only have a class method that takes an int parameter, and no function that takes a parameter of type objectName.

Related

C++: Store pointer to a member function of an object in another object

I have a class which shall invoke a function specified by the user on certain occasions. Therefore the class has a method void setExternalPostPaintFunction(void(*function)(QPainter&)); that can be used to "register" a function. This function then will be called on that occasion:
class A {
public:
void setExternalPostPaintFunction(void(*function)(QPainter&));
private:
void (*_externalPostPaint)(QPainter&);
bool _externalPostPaintFunctionAssigned;
};
The function pointer is saved in the member variable _externalPostPaint. The implementation of setExternalPostPaintFunction looks like this:
void A::setExternalPostPaintFunction(void(*function)(QPainter&)) {
_externalPostPaint = function;
_externalPostPaintFunctionAssigned = true;
}
Now, this works with normal functions. However, I want to be able to also pass pointers to member functions of objects. From what I know I also have to pass and store the pointer to the object in this case. However, I don't know which type the other object will have. So I guess I'm forced to use templates. I already thought of something like this:
class A {
public:
template <typename T>
void setExternalPostPaintFunction(void(T::*function)(QPainter&), T* object);
private:
void (T::*_externalPostPaint)(QPainter&); //<- This can't work!
bool _externalPostPaintFunctionAssigned;
};
This way I can pass a function pointer and an object pointer to setExternalPostPaintFunction and would probably be able to call the function on the object inside that function. But I'm not able to store it in the variable _externalPostPaint because the type T is only deduced when the function setExternalPostPaintFunction is called, thus I can't have a member variable that depends on this type, since the type of my member variable has to be known when the object is created and apart from that it cannot change, but it would have to in the case when a new function is assigned which possibly could be a member function of an object of different type.
So what is the proper way to do this, or is there any? I'm not super fit with templates and function pointers, so I might have overlooked something.
Anoter option would certainly be to create a functor class with a virtual member function which can be overwritten in a derived class and then pass + store an object pointer of that type instead of the function pointer. But I somehow would prefer my approach if it is somehow possible.
EDIT: SOLUTION
TartanLlama brought me on the right track by suggesting the use of std::function. Here is how I solved it:
class A {
public:
template <typename T>
void setExternalPostPaintFunction(T* object, void(T::*function)(QPainter&)) {
_externalPostPaint = std::bind(function, object, std::placeholders::_1);
_externalPostPaintFunctionAssigned = true;
}
void setExternalPostPaintFunction(std::function<void(QPainter&)> const& function);
private:
std::function<void(QPainter&)> _externalPostPaint;
bool _externalPostPaintFunctionAssigned;
};
As you see, the pointer to the function/member function is stored in an std::function<void(QPainter&)> object now. The advantage is, that an std::function can basically store any callable target. Then there are two overloads: one that can be used for any std::function object that also accepts e.g. a normal function pointer (because the std::function that is expected then is implicitly constructed from that) and one for member functions that have to be called on an object (more for convenience). The latter is implemented as a template. This uses std::bind to create a std::function object of the call of that member function (the user passed) on the object (the user passed).
The overload that takes an std::function is implemented in the source file like this:
void ImageView::setExternalPostPaintFunction(std::function<void(QPainter&)> const& function) {
_externalPostPaint = function;
_externalPostPaintFunctionAssigned = true;
}
Invoking that stored function in the code of class A is now as simple as that:
//canvas is a QPainter instance
if (_externalPostPaintFunctionAssigned) _externalPostPaint(canvas);
The user who wants to register a member function as callback function just has to do the following:
//_imageView is an instance of "A"
//"MainInterface" is the type of "this"
_imageView->setExternalPostPaintFunction(this, &MainInterface::infoPaintFunction);
Or if it's not a member function but just a normal function:
void someFunction(QPainter& painter) {
//do stuff
}
_imageView->setExternalPostPaintFunction(&someFunction);
Or he can explicitly create a std::function object and pass it:
std::function<void(QPainter&)> function = [&](QPainter& painter){ this->infoPaintFunction(painter); };
_imageView->setExternalPostPaintFunction(function);
Works like a charm.
You could use std::function:
class A {
public:
//PostPaintFun can be anything which acts as a function taking a QPainter&
//Could be a lambda, function pointer, functor, etc.
using PostPaintFun = std::function<void(QPainter&)>;
void setExternalPostPaintFunction(PostPaintFun fun);
private:
//Names beginning with an underscore are reserved, don't use them
//Ending with an underscore is fine
PostPaintFun fun_;
bool externalPostPaintFunctionAssigned_;
};
Now you can use member functions like so:
struct B
{
void exec(QPainter&) const;
};
void foo() {
B b;
a.setExternalPostPaintFunction(
[b] (QPainter& p) {b.exec(p);}
);
}
//or inside B
void B::foo() {
a.setExternalPostPaintFunction(
[this] (QPainter&p) {this->exec(p);}
);
}
I have to say I prefer TartanLlama's answer, but here you have something it could work for you.
This might to need some work, but I'm sure you'll get the idea.
struct IFunctionHolder {}; // Used for pointing to any FunctionHolder
typedef IFunctionHolder* functionHolder_ptr; // Alias for IFunctionHolder* .
template<typename Function> // The template for the actual function holders.
struct FunctionHolder: public IFunctionHolder
{
Function function;
};
class A {
public:
template <typename T>
void setExternalPostPaintFunction(void(T::*function)(QPainter&), T* object);
private:
functionHolder_ptr *function_holder; // This memeber can hold eny instantiation of template<> FunctionHolder.
// Instantiate this member wen calling setExternalPostPaintFunction
bool _externalPostPaintFunctionAssigned;
};
You could have some code like this:
A some_a;
void some_a.setExternalPostPaintFunction(&SomeInstance::some_fnunction); // Here take place the instantiation of FunctionHolder.
some_a.function_holder.function(some_painter);

Setting up callback to C function pointer via non-static function in C++

A C header of interest (some_external_library.h) declares the following struct, containing a function pointer:
#ifdef __cplusplus
extern "C" {
#endif
typedef struct {
void (*function_ptr)(void);
} fp_test;
/* ... */
#ifdef __cplusplus
}
#endif
When some interesting event happens in some_external_library.c, this function pointer gets called.
I would like to set up a pointer to an instance of this struct in an instance of a C++ class called Foo, and then set the value of function_ptr to the address of a non-static function with the instance of Foo. In other words, I want my C++ code to define what this function pointer does.
For instance, here is a class declaration (foo.h):
class Foo {
public:
fp_test *fp_test_ptr;
void setup(void);
void breakdown(void);
void my_callback(void);
};
There are three functions: a setup function to initialize values, a breakdown function to release any pointers or objects, and a simple my_callback function, which takes and returns no arguments.
Here is the class definition (foo.cpp):
int main(int argc, char** argv) {
Foo some_foo;
some_foo.setup();
some_foo.breakdown();
return EXIT_SUCCESS;
}
void Foo::setup(void) {
fp_test_ptr = new fp_test;
fp_test_ptr->function_ptr = &Foo::my_callback;
}
void Foo::breakdown(void) {
delete fp_test_ptr;
}
void Foo::my_callback(void) {
std::fprintf(stderr, "Callback called...\n");
}
When I compile this, I get the following error:
foo.h:: error: assigning to 'void (*)()' from incompatible type 'void (Foo::*)()'
fp_test_ptr->function_ptr = &Foo::my_callback;
^------------------
I tried casting this call, but I get an error message indicating that I cannot cast from type void (Foo::*)() to void (*)().
How might I set up a non-static method in C++ to be a function pointer to a C library?
I was able to get a static version of Foo::my_callback() to compile, but I don't think I can use a static method for my needs, as I will not have access to the states of non-global members in the class instance some_foo, only the values of global members.
Is there a way to do this with a non-static function?
The normal way around this is to have two one functions: one static and one member function and to pass the object instance as a parameter
class Foo {
public:
fp_test *fp_test_ptr;
void setup();
void breakdown();
void my_callback();
static void _my_callback(void* self);
};
void Foo::_my_callback(void* self)
{
reinterpret_cast<Foo*>(self)->my_callback();
}
Change the C signature of the function pointer to
void (*function_ptr)(void*)
When you call it, pass the object instance as the parameter.
Edit:
To call from C, presumably you need to know which object it refers to so somehow, you need a method of passing the C++ instance to C.
Foo* fu1 = new Foo();
Foo* fu2 = new Foo();
/* fu1 and fu2 need to be passed to the C program */
...
/* Setting up */
fp_test pointerTest;
pointerTest.function_ptr = Foo::_my_callback;
...
/* Calling */
pointerTest.function_ptr(fu1);
pointerTest.function_ptr(fu2);
It is not possible. Every non-static c++ member function has a hidden "this *" parameter. So the function signature will always be different.

Function pointer as parameter in a class method declaration

I'm trying to make a class method that takes a function pointer (regular C function pointer, not a class method pointer) as a parameter. The only thing that comes up when I search is how to create/use a member function pointer, which I'm NOT trying to do. So here's a method that takes a function pointer that returns a bool and takes two ints as parameters:
class ExampleA
{
public:
void sort(WHAT_GOES_HERE); // Should it be the same as method definition below?
};
ExampleA::sort(bool (*customSort)(int, int)) // Hopefully this is correct
{
// Use function pointer
}
Is there a way to declare the parameter in the method declaration without naming it like a method with an int parameter?
class ExampleB
{
public:
void someFunction(int); // Not named here
};
ExampleB::someFunction(int varName)
{
// do whatever
}
Yep! Just leave out the name.
void sort(bool (*)(int, int));
bool (*)(int, int)
Basically, remove the name of the variable to get a declaration without a variable name.
However, you are often better off with a typedef:
typedef bool(*custom_sorter)(int, int);
class ExampleA {
public:
void sort(custom_sorter);
};
ExampleA::sort(custom_sorter customSort) {
// Use function pointer
}
which is equivalent.
As I personally hate the syntax to declare a function pointer, in C++11 I might do:
template<class T> using type=T;
...
void sort(type<bool(int,int)>*)
which puts the signature type together, then I put a * after it to make it a pointer.
But I'm strange.
The declaration should match the definition, so WHAT_GOES_HERE should be bool (*customSort)(int, int), and also the function definition should have the return type void specified.
You can optionally leave out the name customSort, it makes no difference.
This is somewhat inflexible; consider making it a function template that accepts a functor or a std::function instead of a function pointer; then your callers can call it with a wider range of functions.

function pointers between classes

I am having difficulty getting my head around how to pass a class member function to a subclass (not derived).
My top level class is like this:
class CTop
{
public:
CTop();
int func1(void);
private:
CFnList* _funcList;
};
CTop::CTop():
_funcList(0)
{
_funcList = new CFnList();
_funcList->addFnPtrToList(0, &CTop::func1);
}
int CTop::func1(void)
{
// Does some stuff...
}
My function list class is like this:
class CFnList
{
public:
// Public functions
CFnList();
void addFnPtrToList(int index, int (*fn)(void));
private:
// Fn pointer list
typedef struct
{
int index;
int (*fn) (void);
}fn_list_t;
// function pointer list
QVector<fn_list_t> _fn_list;
};
So basically here I have an instance of class CTop and one of its members is a pointer to a class CFnList. CFnList pointer is instantiated in the constructor of CTop. Then I want to pass in a pointer to one of CTop's member functions to CFnList by calling the following line:
"_funcList->addFnPtrToList(0, &CTop::func1);"
I get issue (quite rightly) that addFnPtrToList does not take the parameters (int, (CTop::*)()). So the compiler knows this function is a certain member function and not just a generic (maybe static) function.
Is there a way to pass the a pointer to the member function into the sub-class? In my case I want the sub-class to be able to call this function. I am thinking I probably have to make static member functions or something, but the syntax is eluding me on how to do this.
All help / advise appreciated.
Fodder
CTop::func1 is a member function. &CTop::func1 is NOT a function pointer, it is a pointer to member (function). Those can not be mixed either in storing or calling. it is not compatible with int (*fn)(void), as the latter takes no arguments and the former requires an object that is passed as the hidden this.
For these reasons you can't have a simple but uniform facility. You either can go with simple function pointers, or pairs of PTM+object pointer, or use wrappers -- handmade or stock like boost::function fueled by boost::bind. If you have C++11 or TR1 you can use the std:: equivalents of the latter.
A declaration in the form:
int (*fn)(void)
cannot point to a member function. It can only point to a free function. Philispophically, this is because the calling conventions for member functions are different then that for free functions. Consider for example the need for a this pointer in the context of a member function call.
The syntax for declaring a pointer-to-member-function is like this:
int (CTop::*fn)(void)
There is an entire section in the C++ FAQ dedicated to member function pointers. Check it out.
You are passing the member function as if it were a regular function. That fails to include the 'this' reference to the class. In order to pass member functions, you have to be able to re-reference it from the original 'this'. Take a look at the following, instead.
typedef void (CTop::*OBJFNC)(args);
_funcList = new CFnList();
_funcList->addFnPtrToList(0, this, &CTop::func1);
void addFnPtrToList(int index, CTop* pobj, OBJFNC pfnc)
{ ... Store both ...
}
Now elsewhere you can execute it with the following.
(pobj->*pfnc)(args);
Here is the final solution, it uses a mixture of passing the instance of the object CTop and usage of template class for CFnList:
My top level class is like this (more or less the same except for the declaration of _funcList to includes the class type and to pass in the "this" to the constructor:
class CTop
{
public:
CTop();
int func1(void);
private:
CFnList<CTop>* _funcList;
};
CTop::CTop():
_funcList(0)
{
_funcList = new CFnList(this);
_funcList->addFnPtrToList(0, &CTop::func1);
}
int CTop::func1(void)
{
// Does some stuff...
}
My function list class is like this:
template<class T>
class CFnList
{
public:
// Public functions
CFnList(T *parent);
void addFnPtrToList(int index, int (T::*fn)(void));
private:
// Pointer to the parent (or owner is perhaps more correct)
T* _parent;
// Fn pointer list
typedef struct
{
int index;
int (T::*fn) (void);
}fn_list_t;
// function pointer list
QVector<fn_list_t> _fn_list;
};
// Constructor
template <class T>
CFnList<T>::CFnList(T *parent) :
_parent(parent),
_fn_list(0)
{
}
// addFnPtrToList:
template <class T>
void CFnList<T>::addFnPtrToList(int index, int (T::*fn)(void))
{
_fn_list.append((fn_list_t){index, fn});
}
So the major changes are:
1. Pass the CTop type in by using changing CFnList into a template.
2. Pass in the instance of the object CTop (so that the pointer to the function can be called) by passing "this" into the constructor and then template class stores it as a pointer to the given template type.... vio-la!...easy :o
Thanks to all who contributed :))

Get pointer to member function from within member function in C++

Currently in the program I am attempting to write I need to be able to get a pointer to a member function within a member function of the same class. The pointer needs to be passed to a function as a void (*)(). Example:
//CallFunc takes a void (*)() argument
class testClass {
public:
void aFunc2;
void aFunc1;
}
void testClass:aFunc2(){
callFunc(this.*aFunc1); // How should this be done?
}
void testClass:aFunc1(){
int someVariable = 1;
}
I'm trying to do this in GCC 4.0.1. Also, the member function being called can't be static because it references non-static variables in the class that it is part of. (In case you are wondering, the specific instance in which I need this is where I need to be able to pass a member function of a class to the GLUT function glutDisplayFunc() )
To take pointer to member function you need following syntax:
callFunc(&testClass::aFunc1);
But note, that to invoke member function you need have class instance. So callFunc needs 2 parameters (I'm using template but you can change it to testClass):
template <class T>
void callFunc(T*inst, void (T::*member)())
{
(inst->*member)();
}
So correct call of callFunc looks like:
void testClass::aFunc2()
{
callFunc(this, &testClass::aFunc1);
}