Reputation: 979
In my code I have two almost identical structs, which I have here simplified:
struct foo {
struct bar {
int b;
} a;
};
struct foo2 {
struct qux {
int b;
int c;
} a;
};
(The only difference here is that qux has a member c
while bar does not.)
My question is, Is there a way to let qux inherit from bar, without having to create two foo? This can easily be done with classes, but I want to know if it can be achieved with structs. In my imagination it would look something like this:
struct bar {
int b;
};
struct qux : bar {
int c;
};
struct foo {
bar_or_qux a;
};
Upvotes: 0
Views: 76
Reputation: 5331
Here's the snippet posted in a comment to Ricardo's answer.
struct bar {
int b;
};
struct qux : bar {
int c;
};
struct foo {
bar a;
};
int main() {
qux q;
foo f;
f.a = q;
f.a.b = 7;
// f.a.c = 3;
}
This sort of thing might work in Python or JavaScript but this is C++. Assigning a qux
to a bar
doesn't magically turn the bar
into a qux
. This f.a = q
is called slicing. I'm not sure exactly what you want but I'm gonna make a few guesses and maybe I'll stumble upon it.
You could use templates. This would mean that you can have a "foo with a qux" type and a "foo with a bar" type.
struct bar {
int b;
};
struct qux : bar {
int c;
};
template <typename T>
struct foo {
T a;
};
int main() {
qux q;
foo<qux> f;
f.a = q;
f.a.b = 7;
f.a.c = 3;
}
You could use polymorphism. This would mean that you can have a single foo
type that can store a subclass of bar
(e.g. qux
).
#include <memory>
struct bar {
int b;
virtual void setC(int) = 0;
};
struct qux : bar {
int c;
void setC(const int value) override {
c = value;
}
};
struct foo {
std::unique_ptr<bar> a;
};
int main() {
qux q;
foo f;
f.a = std::make_unique<qux>(q);
f.a->b = 7;
f.a->setC(3);
}
I hope this helps!
Upvotes: 1
Reputation: 9
You can use inheritance with structs in the same way as classes.
Structs in C++ have all the same capabilities as classes, with the only differential being that their members (declarations) and bases (inheritance) are public by default, while for classes, they're private by default.
Upvotes: 0