Search code examples
c++castingreinterpret-cast

Reinterpret cast to different type C++


While reading about Reinterpret cast, I was checking the following code.

class Type1 {
public:

    Type1() {
        a = "Class Type 1";
    }
    void get1()
    {
        std::cout << a;
    }
private:
    std::string a;
};

class Type2 {
public:
    
    Type2() {
        b = "class Type 2";
    }

    void get2()
    {
        std::cout << b;
    }
private:
    std::string b;
};

int main()
{
    
    Type1* type1 = new Type1();

    //converting Pointer
    Type2* type2 = reinterpret_cast<Type2*>(type1);

    // accessing the function of class A 
    type2->get2(); 
}

After running the following code it prints in console "Class Type 1"

Now type1 is pointer of type Type1 and i cast it to Type2 and store in type2. Now when i call type2->get2(); Is it printing the data member a of instantiated Type1 or compiler is dynamically changing function ?

Similarly in Following Code.

#include <iostream> 
using namespace std; 
  
class A { 
public: 
    void fun_a() 
    { 
        cout << " In class A\n"; 
    } 
}; 
  
class B { 
public: 
    void fun_b() 
    { 
        cout << " In class B\n"; 
    } 
}; 
  
int main() 
{ 
    // creating object of class B 
    B* x = new B(); 
  
    // converting the pointer to object 
    // referenced of class B to class A 
    A* new_a = reinterpret_cast<A*>(x); 
  
    // accessing the function of class A 
    new_a->fun_a(); 
    return 0; 
}  

How "In class A" is getting printed? since I instantiated Class B ?


Solution

  • What you are doing is undefined behavior. There is no correct answer to this.

    It is illegal in C++ to use a pointer/reference resulting from a reinterpret_cast between two types of an unrelated hierarchy -- and so any code that generates from such cannot be reasoned about.

    With undefined behavior, the compiler is free to do what it wishes with the invalid code. What you are experiencing may change between different compilers, optimization levels, and target architecture/system.