explicit Vs Implicit conversions?

I

iceColdFire

Hi,

I have a game programming module and I am trying to do something really
fishy...my question is what is difference between explicit and implicit
conversion. this question pops up in the case of derived class to base
class pointer conversion...

Thansk ,
a.a.cpp
 
V

Victor Bazarov

iceColdFire said:
I have a game programming module and I am trying to do something really
fishy...my question is what is difference between explicit and implicit
conversion. this question pops up in the case of derived class to base
class pointer conversion...

Implicit conversion is one that is provided by the language and by the
compiler when you use the "source" object where a "destination" object
is expected. For example, a pointer to derived is convertible to
a pointer to base implicitly if the base class is unique and accessible
like here:

class base {};
class derived : public base {};
void foo(base* b) {}
int main() {
derived d;
foo(&d); // you give a pointer to derived, it is converted
// to a pointer to base _implicitly_ (without your
// expressed instructions)
}

Explicit conversion is one where you need to specify to what and how
the "source" is converted. For example, many (if not all) inverse
conversions of implicit conversions need to be explicit and can be
performed with the help of 'static_cast'. Example (extending the
previous one):

class base {};
class derived : public base {};
base* foo(base* b) { return b; }
int main() {
derived d;
base* pb = foo(&d);
derived *pd = static_cast<derived*>(pb); // ***
assert(pd == &d);
}

*** Since you know that the pointer to base was obtained by the implicit
conversion from a pointer to derived, you may convert it back to a pointer
to derived using static_cast.

V
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top