For a class hierarchy like:
struct base { int i = 1; };
struct derived final : public base
{
int j = 2;
void f() { i = 2; }
};
// more derivations from base
I'd like a way to create an instance of derived
but using an existing base
instance. For example:
base b; // b.i == 1
{
derived d;
d.f(); // d.i == 2
}
Is there a way to set things up so that after calling d.f()
the value of b.i
is 2? As I've tried to indicate, the lifetime of derived
is fairly short.
Conceptually, I want to make base
look like derived
for a little while, with "look like" meaning access to d.j
. When I'm done, I want the changes made to d.i
to "stick to" b.i
. The obvious solution of base& b
member variable doesn't work because accessing i
requires different syntax: b.i
instead of i
.
Copying the derived
instance back to base
when I'm done would work; but that seems rather smelly.
{
derived d;
d.f(); // d.i == 2
b = d; // copy, YUCK!
}
But I really only want and need one instance of base
.
What's actually going on is that I'm trying to simulate nested functions; but I don't want to change the syntax to access either i
or j
.
In pseudo-code, I want to do something like:
struct s final
{
int i = 1;
void f()
{
int j = 2;
auto g = [&]();
}
// ... other code ...
void f::g() { i = 10; j = 20; }
};
In other words, the actual code for the "local function" is away from where it's declared.