Re: Implicit cast from derived to base == static_cast
On 20 f?v, 20:10, abhay.bu...@gmail.com wrote:
Hello,
Question-1:
Recently i was asked a question on the following lines...
1. class A {};
2. class B : public A {};
3. A *anA = 0;
4. B *aB = new B;
5. anA = aB;
6. anA = dynamic_cast<A*>(aB);
What is the difference between lines 5 and 6? Are they both same
semantically?
They're the same, yes.
6 should be less efficient, but a good compiler should realize that
the dynamic cast is actually not needed.
AFAIK, implicit cast in C++ has semantics of a static_cast.
And that is completely false, thankfully.
Implicit conversions, explicit conversions and static_cast are all
different things. However, if you can convert implicitly, you can
convert explicitly, and if you can convert explicitly, you can cast
statically.
The same in the other direction is not true, however.
Here, you're doing an implicit conversion.
Indeed, all pointers to a class type T are implicitly convertible to
pointers to U if U is a base of T, since this is is a perfectly safe
operation.
Question-2:
Can i vindicate my understanding of Question-1 above with the
following code as proof!
<snip>
1. class A{
2. };
3. class B {
4. public:
5. virtual ~B() {} // just to make this class polymorphic
6. };
7. int main(){
8. A *anA = 0;
9. B *aB = new B;
12. anA = dynamic_cast<A*>(aB);
If this compiles, your compiler has a bug.
Question-4:
In the context of the above question, is it possible to have a class
hierarchy, wherein a static_cast would succeed and a dynamic_cast
would fail for the same cast?
static_cast always succeeds, but will raise undefined behaviour if you
don't cast to the right type.
dynamic_cast may fail or not, actually telling you whether you tried
to cast to the right type or not.
You're supposed to use it for downcasting or cross-casting, of course.
It has no point otherwise.
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]