krawacik3
krawacik3

Reputation: 79

reinterpret_cast to the same type

Consider following program:

struct A{};

int main()
{
    A a;
    A b = a;
    A c = reinterpret_cast<A>(a);
}

The compiler(g++14) throws an error about invalid cast from type 'A' to type 'A'. Why is casting to the same type invalid?

Upvotes: 7

Views: 584

Answers (3)

Ramkumar lodhi
Ramkumar lodhi

Reputation: 131

reinterpret_cast should be used to pointers, references and integral types.

I don't know, Why someone do that.

But Still you want do.You can do like.

 A *d = reinterpret_cast<A*>(&a);

or

A c = reinterpret_cast<A&>(a);

Upvotes: 3

pptaszni
pptaszni

Reputation: 8218

Because reinterpret_cast cannot be used for classes and structures, it should be used to reinterpret pointers, references and integral types. It is very well explained in cpp reference

So, in your case one possible valid expression would be reinterpret_cast<A*>(&a)

Upvotes: 3

463035818_is_not_an_ai
463035818_is_not_an_ai

Reputation: 122133

It is not allowed, because the standard says so.

There is a rather limited set of allowed conversion that you can do with reinterpret_cast. See eg cppreference. For example the first point listed there is:

1) An expression of integral, enumeration, pointer, or pointer-to-member type can be converted to its own type. The resulting value is the same as the value of expression. (since C++11)

However, casting a custom type (no pointer!) to itself is not on the list. Why would you do that anyhow?

Upvotes: 5

Related Questions