1

I'm trying to understand these lines of code:

#include <iostream>

using namespace std;


struct Foo {};
struct Bar {};



int main()
{
    Foo* f = new Foo;

    Bar* b1 = f; //error

    Bar* b2 = static_cast<Bar*>(f); //error

    Bar* b3 = dynamic_cast<Bar*>(f); //error

    Bar* b4 = reinterpret_cast<Bar*>(f);

    Bar* b5 = const_cast<Bar*>(f); //error


    return 0;
}

Please, could you explain to me why the marked lines don't compile?

In addition, if reinterpret_cast was designed to deal with pointers, why should you use static_cast with pointers? Shouldn't it be used to cast objects?

Grant Miller
  • 27,532
  • 16
  • 147
  • 165
Enzos
  • 361
  • 1
  • 10
  • Possible duplicate of [Regular cast vs. static\_cast vs. dynamic\_cast](https://stackoverflow.com/questions/28002/regular-cast-vs-static-cast-vs-dynamic-cast) – tkausl Jun 13 '17 at 16:12

1 Answers1

1

Please could you explain me why that marked lines don't compile?

The reason your code is not compiling is the fact that Foo and Bar are unrelated data types

From cplusplus.com

dynamic_cast can be used only with pointers and references to objects. Its purpose is to ensure that the result of the type conversion is a valid complete object of the requested class.

Therefore, dynamic_cast is always successful when we cast a class to one of its base classes

whereas

static_cast can perform conversions between pointers to related classes, not only from the derived class to its base, but also from a base class to its derived

and

const_cast manipulates the constness of an object, either to be set or to be removed

The reinterpret_cast, however, is the only choice you have for making things work:

reinterpret_cast converts any pointer type to any other pointer type, even of unrelated classes. The operation result is a simple binary copy of the value from one pointer to the other.

All pointer conversions are allowed: neither the content pointed nor the pointer type itself is checked.

There's no relationship between your two structs Foo and Bar, so the reinterpret_cast is the only choise available to you in this case.

If you take a look at the link I put above, you will see (in the reinterpret_cast section) the same identical example you provided.

gedamial
  • 1,498
  • 1
  • 15
  • 30