sharptooth
sharptooth

Reputation: 170499

Which kind of cast is from Type* to void*?

In C++ for any data type I can do the following:

Type* typedPointer = obtain();
void* voidPointer = typedPointer;

which cast is performed when I assign Type* to void*? Is this the same as

Type* typedPointer = obtain();
void* voidPointer = reinterpret_cast<void*>( typedPointer );

or is it some other cast?

Upvotes: 5

Views: 381

Answers (4)

AnT stands with Russia
AnT stands with Russia

Reputation: 320471

It is a standard pointer conversion. Since it is a standard conversion, it doesn't require any explicit cast.

If you want to reproduce the behavior of that conversion with an explicit cast, it would be static_cast, not reinterpret_cast.

Be definition of static_cast given in 5.2.9/2, static_cast can perform all conversions that can be performed implicitly.

Upvotes: 4

Naveen
Naveen

Reputation: 73443

From Type* to void* implicit conversion is available. You can use static_cast to clarify the intention of the code. For the reverse you require reinterpret_cast

EDIT: As per comment for the reverse also static_cast can be used. Tried a sample piece of code and it indeed compiles. Didn't knew that and always used reinterpret_cast to cast from a void*.

Upvotes: 4

Alok Singhal
Alok Singhal

Reputation: 96131

It is not a cast, it is implicit conversion. Casts are explicit by definition. It is no more a cast than:

char c = 'a';
int i = c;

is.

Upvotes: 4

Arve
Arve

Reputation: 7506

It is the same cast. Any pointer can be cast to a void-pointer.

Upvotes: 2

Related Questions