why does both giving same results?
Because the behaviour of the program is undefined.
How does casting works internally ?
This cast doesn't "work". The behaviour of the program is undefined.
Some extra explanation.
(B*) &a
This here is a C style cast. Don't use C style casts. It can mean different things in different contexts. In this case, it means a static cast from the base class pointer to a derived class pointer.
When you static cast to a derived type that isn't the dynamic type (or a base of the dynamic type) of the object, the behaviour of the program is undefined. Don't downcast to a type that isn't the dynamic type (or base) of the object.
If you don't know what the dynamic type is1, then dynamic_cast
is a safer option, since you can check for null in case your guess was wrong. That said, if you need to down cast without knowing the derived type, then your design is likely bad and you probably should have been writing a virtual function instead.
Another rule of thumb: If you don't know what you're doing, then adding casting will create problems for you. Study what casting means before using it at random.
1 This is a hypothetical discussion about where a downcast might be used. In this case you should know that the dynamic type isn't the one that you're casting to, so any cast to that type would be pointless.