Is there a way to make a derived instance use an existing base instance

  allocation, c++, inheritance, local-functions

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.

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.

Source: Windows Questions C++

LEAVE A COMMENT