0

For e.g.

int x = 3;
float * ptr = (float*)&x;  // here compiler does not implicitly do conversion, but we have to manually convert to float*   

so my question is, why here we don't need to manually convert it.

Base_Class * ptr = Derived_Class pointer;

is here implicit conversion occuring ?

sparsh goyal
  • 89
  • 1
  • 7
  • 1
    Yes, derived pointer -> base pointer conversion can happen implicitly. Unlike `int *` -> `float *`, because those are unrelated types. – HolyBlackCat May 13 '21 at 06:57

1 Answers1

3

here compiler does not implicitly do conversion

Because int and float are unrelated types. Accessing one as if it's the other (type punning) is Undefined Behavior.

Why is here implicit conversion occurring

Because accessing a derived object via a pointer of type base is a fundamental mechanism by which runtime polymorphism works.

bolov
  • 72,283
  • 15
  • 145
  • 224