AlwaysLearning AlwaysLearning - 2 months ago 6
C++ Question

Assigning subobject

What is the proper way to assign a subobject? For example:

struct A {
int x = 2;
int y = 3;
};

struct B: A {
int z = 5;
};

int main() {
std::unique_ptr<B> bp{new B{}};
A a;
a.x = 12;
a.y = 13;
*(static_cast<A*>(bp.get())) = a; // happens to work, but is it the right way?
std::cout << bp->x << " " << bp->y << std::endl;
return 0;
}


This works (or happens to work?), but is awkward and relies on an assumption about the layout of
B
. So, what is the correct way?

Answer

This may be slightly more idiomatic:

bp->A::operator=(a);

This kind of thing is pretty rare though, so it is hard to say. In general, the more you can avoid casts the better, but having an explicit cast may be useful in this case to make it clear you are doing something unusual.

Comments