Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign derived class to base class

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?

like image 827
links77 Avatar asked Sep 18 '10 19:09

links77


People also ask

What is an example of a base class with derived classes?

Let’s consider the example of a base class X: With two derived classes A and B: class A : public X { // ... }; class B : public X { // ... }; If we have two concrete objects that we manipulate through their base class as references to X, how can we implement an assignment operator to assign one into the other?

Is it possible to assign a derived class to a variable?

But you can assign an instance of a derived class to a variable of base class type. You can cast a variable that is typed as the base-class to the type of a derived class; however, by necessity this will do a runtime check, to see if the actual object involved is of the correct type.

Can a pointer of a base class point to a derived class?

The pointer of Base Class pointing different object of derived class: A derived class is a class which takes some properties from its base class. It is true that a pointer of one class can point to other class, but classes must be a base and derived class, then it is possible.

Can two objects of the same derived class be assigned together?

One case comes up often: handling the behaviour of two objects of the same derived class. One case in this special case comes up often: assigning an object to another one. Let’s consider the example of a base class X: With two derived classes A and B: class A : public X { // ... }; class B : public X { // ... };


2 Answers

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

like image 101
Gabriel Schreiber Avatar answered Oct 24 '22 07:10

Gabriel Schreiber


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

like image 23
Nikola Smiljanić Avatar answered Oct 24 '22 09:10

Nikola Smiljanić