Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast object from derived to base and than back

Tags:

c++

oop

casting

If i cast an object to the base type and store it in a std::map, and then get it back and recast it to the derived type, do i still have the correct data in the derived class members ?

Do i need to make a specific kind of cast ?

like image 861
Cumatru Avatar asked Feb 13 '12 13:02

Cumatru


People also ask

Why downcasting is not allowed?

Downcasting is not allowed without an explicit type cast. The reason for this restriction is that the is-a relationship is not, in most of the cases, symmetric. A derived class could add new data members, and the class member functions that used these data members wouldn't apply to the base class.

What is the use of upcasting and downcasting in C++?

It means the upcasting used to convert the reference or pointer of the derived class to a base class. Upcasting is safe casting as compare to downcasting. It allows the public inheritance that implicitly cast the reference from one class to another without an explicit typecast.

Can you cast a base class to a derived class in C++?

C++ Explicit type conversions Base to derived conversion Likewise, a reference to base class can be converted to a reference to derived class using static_cast . If the source type is polymorphic, dynamic_cast can be used to perform a base to derived conversion.

What is dynamic cast in C++?

In C++, dynamic casting is, primarily, used to safely downcast; i.e., cast a base class pointer (or reference) to a derived class pointer (or reference). It can also be used for upcasting; i.e., casting a derived class pointer (or reference) to a base class pointer (or reference).


1 Answers

If you're casting pointers to the object, it's no problem because the pointers will still point to the same object.

If you're casting the actual object, all information from the subclass will be lost when its converted to the superclass, so casting it back won't restore that information.

like image 138
sepp2k Avatar answered Sep 28 '22 19:09

sepp2k