Solved

Saving a function in a variable

Posted on 2000-03-07
8
146 Views
Last Modified: 2010-04-02
Is it possible to save a function (not a value) in a variable, to evaluate it later???
0
Comment
Question by:Xertunus
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 7
8 Comments
 
LVL 22

Accepted Solution

by:
nietod earned 100 total points
ID: 2591294
it is possible to save a function pointer and then use the function pointer to call the function at a later time.  Also there is a more c++ way of doing this, using classes called functors.  

Continues
0
 
LVL 22

Expert Comment

by:nietod
ID: 2591303
If you have functions that have the same signature--same calling convention, same parameters and same return values like

int Add(int x,int y)
{
   return x+y;
};

and

int Sub(int x,int y)
{
   return x - y;
};

Then you can create a pointer that can point to any of these functions.  At typedef for this pointer makes things easier, in this case it would be

typedef int (*FunPrtTyp)(int x,int y);

continues
0
 
LVL 22

Expert Comment

by:nietod
ID: 2591323
You can declare then pointer a pointer of this type, iniitialze it to one of the functions and call the function with the pointer like

FunPtrTyp FunPtr;

if (OperationTyp == AddOperatio)
    FunPtr = &Add; // Set pointer to the add function.
   // FunPtr = Add; is also a legal syntax for this.
else
    FunPtr = ⋐ // Set pointer to the subtact function.

   *  *  *

 // Use the function pointer as follows.
   int Result = (*FunPtr)(5,3); // Does 5+3 or 5-3;
// also "FunPtr(5,3);" is a legal syntax.

continues
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 22

Expert Comment

by:nietod
ID: 2591346
Obviously the function pointer can be passed to or returned from functions aand "saved till later" just like any pointer.

Now this same thing can be accomplished in a more C++ manor using classes.  This technique is so common that the classes used in this way are given a name--"functor".  A functor could be considered any class that has virtual functions, but usually it is a class with no data members and only a single virtual function.  Often this virtual function will be operator (), but in the following example I use a function called "Operate" because I think it makes the code easier to read.  

First you need to define a base class, preferabley pure abstract, that defines the virtual function(s).  For example

class MathOperation
{
public:
    virtual int Operate(int x,int y) = 0;
};

Then from this base class derive concrete classes for the differen operations to be performed, like

class Add : pulbic MathOperation
{
public:
    virtual int Operate(int x,int y) { return x + y; };
};

class Sub: pulbic MathOperation
{
public:
    virtual int Operate(int x,int y) { return x -  y; };
};

continues
0
 
LVL 22

Expert Comment

by:nietod
ID: 2591354
Opps those functions shoudl all have been declared const.  That makes the class much more "flexible" and useful.  Like

class MathOperation
{
public:
    virtual int Operate(int x,int y) const = 0;
};

Then from this base class derive concrete classes for the differen operations to be performed, like

class Add : pulbic MathOperation
{
public:
    virtual int Operate(int x,int y) const { return x + y; };
};

class Sub: pulbic MathOperation
{
public:
    virtual int Operate(int x,int y) const { return x -  y; };
};
0
 
LVL 22

Expert Comment

by:nietod
ID: 2591373

Now to use the class you would declare some code that has a pointer or reference to the base class, but actually works with one of the derived class objects.  For example  you could declare a function that takes a reference to the base class, but is passed one of the derived classes,  This funciton would call the functor's virtual function to perform some sort of action, for example

int DoMath(const MathOperation &Fun)
{
   return Fun.Operate(5,3);
};

this function could be invoiked using an object of either of the derived types.  You could create the objects as locals or globals, but since the virtual function is constant and the DoMath() procedure takes a constant reference parameter, you can simply call DoMath() using an unamed tempoaray, like

int Result = DoMath(Add()); // 5+3

Obviously you can use pointers and references to these functor objects to pass them around and to save them just like function pointers.

Let me know if you have any questions.
0
 

Author Comment

by:Xertunus
ID: 2592472
Quite nice, but I want to do something like this:

RightButtonFunction = ShowPopupMenu();

OnRightButton()
{
        Run(RightButtonFunction);
}

(I hope you understand what I mean)
0
 
LVL 22

Expert Comment

by:nietod
ID: 2592641
Either approach I showed you will do that.
0

Featured Post

Enroll in June's Course of the Month

June’s Course of the Month is now available! Experts Exchange’s Premium Members, Team Accounts, and Qualified Experts have access to a complimentary course each month as part of their membership—an extra way to sharpen your skills and increase training.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Written by John Humphreys C++ Threading and the POSIX Library This article will cover the basic information that you need to know in order to make use of the POSIX threading library available for C and C++ on UNIX and most Linux systems.   [s…
This article will show you some of the more useful Standard Template Library (STL) algorithms through the use of working examples.  You will learn about how these algorithms fit into the STL architecture, how they work with STL containers, and why t…
The goal of the video will be to teach the user the difference and consequence of passing data by value vs passing data by reference in C++. An example of passing data by value as well as an example of passing data by reference will be be given. Bot…
The viewer will learn how to pass data into a function in C++. This is one step further in using functions. Instead of only printing text onto the console, the function will be able to perform calculations with argumentents given by the user.

726 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question