views:

219

answers:

3
+1  Q: 

Type Casting C++

see the following code:

void simple_dynamic_casts( )
{
  AB  ab;

  B*  bp  = (B*)&ab;  // cast needed to break protection
  A*  ap  = &ab;      // public derivation, no cast needed

  AB& abr = dynamic_cast<AB&>(*bp);  // succeeds

  ap = dynamic_cast<A*>(bp);         assert( ap != NULL );
  bp = dynamic_cast<B*>(ap);         assert( bp == NULL );
  ap = dynamic_cast<A*>(&abr);       assert( ap != NULL );
  bp = dynamic_cast<B*>(&abr);       assert( bp == NULL );
}

code taken from here

will this work

ap = &abr;

why does the code use a dynamic cast here. i have not tried to compile this code.

+1  A: 

Yes. A pointer to a class can always be implicitly converted to a pointer to a public base class; in this case, you're converting from AB* to A*. A dynamic_cast is allowed, but not required.

It's no different to the second conversion (A* ap = &ab;).

The code uses a dynamic_cast to illustrate how that works.

Mike Seymour
A: 

why does the code use a dynamic cast here.

The dynamic_cast operator allows you to check if a cast is valid at runtime. If it is not, it will return null (hence the assert() calls).

will this work

Try it and see... :)

jheddings
+4  A: 

They use dynamic_cast to show what it does. So, that's the answer to your "why" question.

Otherwise, the explanations given at that web page are incorrect. The resource you are trying to use is either heavily outdated or tied to some specific, poor-quality compiler. The words "The emerging C++ standard..." at the top of the page are a dead giveaway. C++ standard became reality 11 years ago. (Meaning that site is not a good resource for C++ in general and on dynamic_cast in particular, if that's what you are looking for.)

Here are their class definitions

class A          { public: virtual void f( ); };
class B          { public: virtual void g( ); };
class AB :       public virtual A, private B { };

The cast

AB& abr = dynamic_cast<AB&>(*bp); // they say: succeeds

will not succeed. It will throw a bad_cast exception, since B is not a public base class of AB. dynamic_cast cannot be used to break protection in downcasts.

The cast

bp = dynamic_cast<B*>(&abr);

will not even compile, since illegal upcasts (breaking protection) are rejected at compile time even by dynamic_cast (i.e. the code is ill-formed). Note, that dynamic_cast does nothing special in this case. With upcasts, dynamic_cast is equivalent to static_cast or to no-cast-at-all. The above cast will not compile because B is a private base. The authors seem to incorrectly assume that dynamic_cast should return null-pointer in this case.

As for ap = &abr - yes it will work. There's nothing wrong with it, as long a A is a public base of AB.

AndreyT
well bp = dynamic_cast<B*>(ap) does compile. however assert fails.
iamrohitbanga
Oops... That cast should not have been included. It is a cross-cast, not an upcast. I fixed it. Thank you.
AndreyT