ask the collective
ask the collective

Reputation: 27

conversion for void* as a method argument

For a method with an argument of void* is C++ employing static/reinterpret_cast to make the conversion or is there a different mechanism in play here?

void foo(void* p)
{
    // ... use p by casting it back to Base first, using static/reinterpret cast
}
Base* base(new Derived);
foo(base);       // at this exact line, is there a static/reinterpret_cast going on under the covers?

I am asking because it seems that on one hand the standard says that for c-style cast, C++ will go and try a C++ cast (static, reinterpret, const) until something that works is found. However I can't find a reasonable explanation as to what goes on when a method with a void* argument is called. On the face of thing there is no cast, so what happens?

Upvotes: 0

Views: 333

Answers (1)

AnT stands with Russia
AnT stands with Russia

Reputation: 320531

The language specification does not express the behavior in terms of static_cast or reinterpret_cast in this case. It just says that the pointer base is implicitly converted to void * type. Conversions that can be performed implicitly are called standard conversions in C++. Conversion of any object pointer type to void * is one of the standard conversions from pointer conversions category.

It is true that this is the same conversion that can be preformed explicitly by static_cast, but static_cast is completely irrelevant in this case. Standard conversions in C++ work "by themselves" without involving any specific cast operators under the cover.

In fact, it is the behavior of static_cast that is defined in terms of standard conversions for such cases, not the other way around.

Upvotes: 4

Related Questions