After Griff's and nv3's answers there's not a lot left to say... But I'll say it anyway!
In C++ functions aren't objects the way in some other programming languages. You can't ask a function anything apart from what the result of executing it is with a particular set of parameters.
nv3 mentioned that you could make
val
a member of
Test1
and keep the value there and have it accessible there. If that's not going to work for you you can build objects that work like functions. These are called functors in the literature - do a quick search and you'll find out all sorts of interesting stuff about them.
In a nutshell a functor is an object with an overloaded function call operator. This lets you have a function that:
- has state between calls
- can be
copied (this doesn't sound that cool, but it is, trust me)
You can get what you seem to want using three classes instead of one:
struct f1
{
double val;
f1::f1() : val( 0 ){}
void operator()()
{
val = 20.88;
}
};
struct f2
{
f1 *function1;
f2( f1 * function1_ ) : function1( function1_ ){}
void operator()() const
{
std::cout << function1->val << std::endl;
}
};
class Test1
{
public:
Test1() : function2( &function1 ){}
f1 function1;
f2 function2;
};
Here I've made
f1
and
f2
functors that do the sort of thing you wanted the member functions of
Test1
to do.
function1
can now maintain some state independently of
Test1
.
You can see it work with something like:
int main()
{
Test1 t1;
t1.function2();
t1.function1();
t1.function2();
}
function2()
outputs a zero first time around, 20.88 the second time.
Cool, so it works. But it's a lot more complicated than nv3's example. When would you use this more complicated styke lump of code? The answer is not often but it does have one use that nv3's code can't manage - you can use the components of Test1 without needing a Test1 around, composing them into arbitrary classes. They can also act as "Tear offs" enabling you to instantiate large chunks of code and data only when they're used. You can also use this sort of thing instead of implementation inheritance when you need a common piece of code as a member function. They also make good template parameters, exposing a particular piece of functionality and just that piece.
However if you need them that often (i.e. at all) then you're probably missing something - go back and review your design!