Question

is it safe to do something like this:

class Base { public: int x; };
class Derived : public Base { public: int y; };
Base b;
Derived d;
b.x = 1;
d.x = 2;
d.y = 3;
std::swap(b,d);

At this point is it guaranteed that the derived info d.y is still valid? In other words I am only swapping the base object but the derived data is still valid, correct? Also, is this considered slicing?

EDIT: In comments it's been pointed out this won't compile. What's the best way to swap the base data in d with b? Keep in mind b is obviously a lot more complicated then I put in my example.

Was it helpful?

Solution

It all depends on what your definition of valid is and how precise the scope of the question. In the general case, swapping just the bases will not be valid, since the derived type might enforce additional invariants that could be broken.

In the particular case you have, with no invariants, all public data (after fixing the type definitions so that the code below compiles) the data will be swapped and most probably won't cause any issues (assumption: the change in the swap could be manually done by accessing the members directly, so the swap does not break anything that would not be otherwise broken).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top