views:

75

answers:

2

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?

+3  A: 

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

Nikola Smiljanić
+5  A: 

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

Gabriel Schreiber
Thank you for the link.
links77