I have been reading this answer which explained how slicing will modify only one part of an object. I'm wondering if the slicing behaviour explained in the treacherous case is guaranteed or undefined.
Given the following class structures (which I cannot modify):
class Combined : public Data, public Handler
{
// no operator=() defined
// implements abstract and/or virtual methods from Handler
// methods access members from Data
};
class Data
{
// no operator=() defined
// public members and public non-virtual methods only
};
class Handler
{
// no operator=() defined
// contains abstract as well as virtual methods
// protected/private members
};
can I reliably use object slicing to assign only the Data
portion of Combined
, as such:
// Declaration
Data returnSomeDataFromSomewhere();
// real work starts here
Combined usable_obj;
Data& sliced_data = usable_obj;
sliced_data = returnSomeDataFromSomewhere();
usable_obj.actOnData();
or even
Combined usable_obj;
usable_obj.initialise();
usable_obj = returnSomeDataFromSomewhere();
usable_obj.actOnData();
An answer from this question suggests that explicitly calling Combined.Data::operator=
(or is it Combined::Data::operator=
?) achieves the same effect. It looks the same as assigning to the Data&
object, but I'm confused by the caution about breaking the derived class' invariant.
If slicing happens to be undefined behaviour, I can always create a temporary Data
object and copy each member individually since they are public, but I would prefer to not have to do that if there are 200 members in Data
.
However, if the slicing behaviour is guaranteed, are there any pitfalls I should be aware of?
EDIT: Added restrictions on classes having no operator=
.