We're a community of 1076K IT Pros here for help, advice, solutions, professional growth and fun. Join us!
1,075,983 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Start New Discussion Reply to this Discussion

Error with function pointer in C++

Hi,
I am getting the following error while compiling

error: argument of type 'void(FClass::)()' does not match 'void(*)()'

on the line

fPointer=instance.PrintIt; // Give the pointer the function address

This is my code

/**
 * @file FPointer.c
 * This is the main FPointer program start point.
 */

/**
 * Main program function.
 */

#include <stdio.h>
#include <propeller.h>
#include "FClass.c"

int main(void)
{
    FClass instance; // Create an instance of the class
    void (*fPointer)(); // This will point to a function in FClass

    waitcnt(CLKFREQ*3+CNT); // Give the microcontroller 3 secs to boot

    fPointer=instance.PrintIt; // Give the pointer the function address

    return 0;
}

and

/**
 * @file FClass.c
 */

#include <stdio.h>

class FClass
{
    int number; // We will print this number
    public:
        FClass()
        {
            number=8; // Initialize the number
        }
        void PrintIt()
        {
            printf("%d",number); // Print the number
        }
};

Thanks,
Enrique

3
Contributors
3
Replies
15 Hours
Discussion Span
9 Months Ago
Last Updated
4
Views
Enrique Nivasch
Newbie Poster
12 posts since Aug 2008
Reputation Points: 10
Solved Threads: 0
Skill Endorsements: 0

function pointers can only point to static class methods or global c-style functions. You will have to make PrintIt() a static method if you want to do that.

Ancient Dragon
Achieved Level 70
Team Colleague
32,124 posts since Aug 2005
Reputation Points: 5,836
Solved Threads: 2,575
Skill Endorsements: 69

Thanks

Enrique Nivasch
Newbie Poster
12 posts since Aug 2008
Reputation Points: 10
Solved Threads: 0
Skill Endorsements: 0

AD's already got this one covered, but I wanted to throw something in as well.
If you want a static function to use instance specific data, you have to pass a pointer to the instance as a parameter:

You modify your FClass::PrintIt like so:

static void PrintIt(FClass *instance)
{
    printf("%d",instance->number); // Print the number
}

And your fPointer definition to be:

void (*fPointer)(FClass *); // This will point to a function in FClass

And your assignment becomes:

fPointer=FClass::PrintIt; // Give the pointer the function address

To be used like this:

fPointer(&instance);

I learned this when I was combining classes with threading for the first time. (I'm still quite the noob at parallel programming).

DeanMSands3
Posting Whiz
310 posts since Jan 2012
Reputation Points: 80
Solved Threads: 42
Skill Endorsements: 1

This article has been dead for over three months: Start a new discussion instead

Post: Markdown Syntax: Formatting Help
 
You
 
© 2013 DaniWeb® LLC
Page rendered in 0.0637 seconds using 2.66MB