Search code examples
c++oopfstreamreinterpret-cast

With or without reinterpret_cast


int main()
{
    class_name object;
    object.method();
    fstream file("writeobject.dat" , ios::out|ios::app);
    file.write(reinterpret_cast<char*>(&object), sizeof(object));
    return 0;
}

//////////////////////////////////////////////////////////////////////////////////////////

int main()
{
    class_name object;
    object.method();
    fstream file("writeobject.dat" , ios::out|ios::app);
    file.write((char*)&bk,sizeof(book));
    return 0;
}

What is the difference between above both functions. What is reinterpret_cast is doing here? I don't see any of the difference between output of both main() functions.


Solution

  • A C style cast is nothing but the C++ cast that succeeds from the predefined order of:

    • const_cast
    • static_cast
    • static_cast, then const_cast
    • reinterpret_cast
    • reinterpret_cast, then const_cast

    In this case they are doing the same thing. However, if you are using C++ it is better to use C++ style of explicit casting because they are more indicative of the intent and also it's always better to be explicit about what casting you need than be at the mercy of the compiler to chose one for you.