0

Currently I have created a class called A that creates an array of pointers to functions as well as declared the function's prototypes, please view the A.h below.

#ifndef A_H
#define A_H

class A
{
    public:

        //Function Definitions that will be called from the seq function below.

        A::A()
        //prototype functions that will be pointed to from array 
        void f1(int);
        void f2(int);
        void f3(int);

        void (*funcs[3])(int);
        //Destructor method
        virtual ~A();    
};

Then I have A.cpp defined below with the function definitions of f1, f2, f3.

A::A()
{

}

void A::f1(int a){ cout << "This is f1: " << endl; }
void A::f2(int b){ cout << "This is f2: " << endl; }
void A::f3(int c){ cout << "This is f3: " << endl; }

//Would this be valid?
funcs[0] = f1;
funcs[1] = f2;
funcs[2] = f3;

A::~A()
{
    //dtor
}

How would I access the array from main.cpp

include "A.h"
.
.
.


int main()
{
    //This doesn't work, what is the proper way to access the pointers to functions?
    A a;
    a.funcs[0](1);

}

Should print out "This is f1: ". This has really been bugging me, i've been reading different threads and even used typedefs but to no avail. Any help would truly be appreciated. If you need anymore details please let know.

10
  • //Would this be valid? No. You can't use non static class member functions there. I'd recommend you use std::function and a lambda expression to capture a. Commented Feb 4, 2018 at 15:53
  • Your functions are not functions. They are class methods, which are not functions. That's why your compiler is refusing to compile this. Declare your class methods as static if you want them to be real functions, instead of class methods. Commented Feb 4, 2018 at 15:54
  • 1
    Possible duplicate of C++: Array of member function pointers to different functions Commented Feb 4, 2018 at 15:54
  • @Sam "They are class methods, which are not functions." This terminology is new to me. I always thought class member function is the correct term, no? And why these aren't functions? Commented Feb 4, 2018 at 15:55
  • 1
    @Kevag6 "I guess before I ask a question a should dig deeper into my research." Yes, it is expected of you, to do research, before asking. And I don't know about digging deeper, since it was the second link, in the search engine, that I am using.. Commented Feb 4, 2018 at 16:26

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.