what happens when we write statemnets like where B is a class from which D1 is derived in c++ does actual new objects are created or just simple typecasting like primitive types is done
D1 d1;
(B)d1;
what happens when we write statemnets like where B is a class from which D1 is derived in c++ does actual new objects are created or just simple typecasting like primitive types is done
D1 d1;
(B)d1;
Type cast doesn't create new objects, but compiler which knows both types can apply required offsets to interpret the object as the type casted one. Of course compiler or runtime will make sure the casting is legal.
In your specific case if you are casting a derived object to base class, it is called "slicing", the derived parts are cut off from the base object. To intuitively understand this, lets say d1 had a memory region to hold all this members , since it derives from B it will have a sub-region to hold its version of the base class. When you cast d1 to base class, you have to make sure the variable only refers to sub region and ignores the rest of it, in other words the objects boundary stops at the base class part.
Casting types never creates new instances of them, but give 'a view' of the casted instance as if it were of the type you're casting it to.
static_cast
will check if the type is castable at compile time.
dynamic_cast
will check type is castable at runtime.
reinterpret_cast
just does the cast without any check at compile or runtime.