Joe
Joe

Reputation: 33

inheritance in structs prototypes

Is it possible to represent this in C++:

struct foo {
    int x;
    int y;
    struct A derived;
};

struct A {
    int val;
};

struct B : A {
    int baz[10];
};

struct C : A {
    int baz[20];
};

Where derived can be any of the inherited structs of A (either B or C) but never A, without changing the prototype struct foo? For example is it be possible to do the to do the following?

void func(void)
{
    struct B b;
    struct foo foo;
    foo.derived = b;
}

Upvotes: 0

Views: 107

Answers (1)

Edward Strange
Edward Strange

Reputation: 40867

struct A {
    int val;
    virtual ~A() = 0; // so nobody can instantiate A alone.
};
inline
A::~A() = default; // the destructor HAS to be defined.

struct foo {
    int x;
    int y;
    std::unique_ptr<A> derived;
};

And then the rest being the same...and using:

foo foo_v;  foo_v.derived = std::make_unique<B>();

Note that I've eliminated the C language elements and made it pure C++. I'd also clean these up and make them more cohesive. Does it make sense that x and y are uninitialized in the above code? Probably not, so there should be a constructor that forces them to be provided, sets them to an initial value, or both.

Upvotes: 1

Related Questions