Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't a Base class object be assigned to a Derived class object?

A derived class object can be assigned to a base class object in C++.

Derived d;
Base b = d; // It's Ok

But why can't a base class object be assigned to a derived class object?

Base b;
Derived d = b; //Not Ok. Compiler give an error

Edit:

Sorry, but this question was actually asked durring an interview.

like image 648
msc Avatar asked Aug 24 '17 09:08

msc


People also ask

Can we assign derived class object to base?

In C++, a derived class object can be assigned to a base class object, but the other way is not possible.

Why can't we assign a base class object to a derived class variable?

Expanding on @ybo's answer - it isn't possible because the instance you have of the base class isn't actually an instance of the derived class. It only knows about the members of the base class, and doesn't know anything about those of the derived class.

Can a base class use a derived class?

A derived class can have only one direct base class. However, inheritance is transitive. If ClassC is derived from ClassB , and ClassB is derived from ClassA , ClassC inherits the members declared in ClassB and ClassA .

Why can't a derived pointer reference a base object?

similarly a derived object is a base class object (as it's a sub class), so it can be pointed to by a base class pointer. However, a base class object is not a derived class object so it can't be assigned to a derived class pointer.


2 Answers

Inheritance is an "is-a" relationship, but it's one-way only.

If you have e.g.

struct Base { /* ... */ };
struct Derived : Base { /* ... */ };

Then Derived is a Base, but Base is not a Derived.

That's why you can assign or initialize a base-class instance with a derived object (but beware of object slicing), but not the other way around.

like image 169
Some programmer dude Avatar answered Oct 07 '22 00:10

Some programmer dude


A derived object is a base object, with additional information.

You can initialize a complete base object from the base part of a derived object, no problem.

But if you want to construct a derived object from just a base object, what should the additional information be initialized with?

If you want to provide defaults for that additional information, you can do so by declaring a Derived(Base const &) constructor. But since it does not work in the general case, it isn't done for you.

like image 22
Quentin Avatar answered Oct 06 '22 23:10

Quentin