Reputation: 424
This is a toy example of the issue. I have a large parent function, which, among other things, calls two child functions. In reality, this parent function is on a base class used for other things, so I don't want to rewrite the parent function or the wrapped functions to pass variables by reference, because they won't be needed for the other child classes inheriting the base. The parentFunc is also being called on multiple threads, so I can't just stick the needThisInSecondWrappedFunc variable as a class-level variable, as it would then be incorrectly shared between threads.
It seemed to me making a local variable on the parent function would be visible to the two child functions, which could then operate on the parentFunc's local variable, but it's not the case.
#include <iostream>
void parentFunc(float& data);
void wrappedFunc(float& ref);
void secondWrappedFunc(float& ref);
void parentFunc(float& data)
{
float needThisInSecondWrappedFunc[3];
wrappedFunc(data);
secondWrappedFunc(data);
}
void wrappedFunc(float& ref)
{
needThisInSecondWrappedFunc[0] = ref * 0.5f;
needThisInSecondWrappedFunc[1] = ref * 0.5f;
needThisInSecondWrappedFunc[2] = ref * 0.5f;
}
void secondWrappedFunc(float& ref)
{
ref = needThisInSecondWrappedFunc[0] +
needThisInSecondWrappedFunc[1] +
needThisInSecondWrappedFunc[3];
}
int main()
{
float g;
g = 1.0f;
parentFunc(g);
std::cout << g << '\n';
return 0;
}
I'm not sure why wrappedFunc and secondWrappedFunc can't see the local variables of the parentFunc - I thought the parentFunc locals would still be in scope at this point?
Upvotes: 1
Views: 1093
Reputation: 22023
There is no concept of parent function access in C++.
You can only access the global scope ("global" variables) and then local variables inside the current function. If you are in an object instance, you also have access to these.
There is no way to access variables declared in another function.
What you need to do is this:
void parentFunc(float& data);
void wrappedFunc(float& ref, float* needThisInSecondWrappedFunc);
void secondWrappedFunc(float& ref, const float* needThisInSecondWrappedFunc);
void parentFunc(float& data)
{
float needThisInSecondWrappedFunc[3];
wrappedFunc(data, needThisInSecondWrappedFunc);
secondWrappedFunc(data, needThisInSecondWrappedFunc);
}
void wrappedFunc(float& ref, float* needThisInSecondWrappedFunc)
{
needThisInSecondWrappedFunc[0] = ref * 0.5f;
needThisInSecondWrappedFunc[1] = ref * 0.5f;
needThisInSecondWrappedFunc[2] = ref * 0.5f;
}
void secondWrappedFunc(float& ref, const float* needThisInSecondWrappedFunc)
{
ref = needThisInSecondWrappedFunc[0] +
needThisInSecondWrappedFunc[1] +
needThisInSecondWrappedFunc[3];
}
Or even better, use std::array<float, 3>
.
Upvotes: 2