14

Is it safe to do the following or is it undefined behaviour:

class Base
{
private:
    int a;
};

class Derived : public Base
{
private:
    int b;
};

Base x;
Derived y;
x = y;   // safe?

Do the extra bits in derived classes just get sliced off?

Magnus Hoff
  • 21,529
  • 9
  • 63
  • 82
links77
  • 779
  • 2
  • 7
  • 8
  • Nothing gets "sliced off" here: `y` remains a fully valid object of type `Derived`. But only those parts of `y` are assigned to `x`, that fit into `x`. That again is not a problem. It only becomes a problem, if you later assumes, that `x` is not of type `Base`, but of type `Derived`. – Kai Petzke Sep 22 '21 at 06:35

2 Answers2

12

Yes, slicing occurs. It is not undefined behaviour though.

You might find this entry in the C++-FAQ helpful:
http://www.parashift.com/c++-faq-lite/virtual-functions.html#faq-20.8

sbi
  • 219,715
  • 46
  • 258
  • 445
Gabriel Schreiber
  • 2,166
  • 1
  • 20
  • 33
9

You are right, the object is sliced. This is a common problem. You shouldn't do it!

Community
  • 1
  • 1
Nikola Smiljanić
  • 26,745
  • 6
  • 48
  • 60
  • This is not a "problem", it's a language feature and very useful one. For example, if you have data only struct where some values are specified and other values must be computed then you can put computed values in derived class. – Shital Shah Aug 15 '18 at 03:24
  • @ShitalShah Most people find out about this feature the hard way but I agree it can be useful. My question would be if you were to use it how would you make it obvious to the reader of your code that this is your intention? I for one would always assume it was a bug unless there was a comment saying "Deliberately slicing the object". – Nikola Smiljanić Aug 15 '18 at 07:00