c++pointer-conversion

does implicit pointer conversion occur during assignment?


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 ?


Solution

  • 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.