1

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.

Artjom B.
  • 61,146
  • 24
  • 125
  • 222
user2672807
  • 1
  • 2
  • 7
  • 20

1 Answers1

3

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).

David G
  • 94,763
  • 41
  • 167
  • 253
David Rodríguez - dribeas
  • 204,818
  • 23
  • 294
  • 489
  • Can you please give an example of additional invariants that could be broken? I don't know exactly what you mean. If I swap the base data out of the derived class am I swapping its virtual functions as well? – user2672807 Aug 26 '13 at 18:05
  • 1
    Note, though, that if a class can be broken because you can freely access the base class, that's a bug in the class. – GManNickG Aug 26 '13 at 18:09
  • 2
    @user2672807: No, you are just changing data (virtual functions don't change). But the functions on the derived type may depend on a particular combination of values in the base and the added data members (invariants, like derived member `x` holds the sum of base members `a` and `b` at all times). The swap in the question can potentially break those invariants by modifying parts of the complete object without updating the rest. – David Rodríguez - dribeas Aug 26 '13 at 18:11
  • @GManNickG: Agreed, although I fear that most code bases fail here (considering how inheritance is abused in general) – David Rodríguez - dribeas Aug 26 '13 at 18:13
  • David and @GManNickG Ok I will take that into consideration, thanks guys. – user2672807 Aug 26 '13 at 18:26