Dynamic Cast

Hi All,

So If i have a class A
and i derive another class B from A.

now in a fn . i have input as A*
Now this code.

void fn (A* a)
{
if (A* aa = dynamic_cast<A*> (a))
cout << "good";
else
cout << "bad";
}

int main (void)
{
B* b = new B;
fn (b);
}

I would think it should print bad. but it does the opposite . why ???

short answer:

dynamic cast is for down casting. You're using it for up casting, which is pointless.

long answer:

dynamic cast simply checks to see if the cast is good. Casting a B* to an A* will always be good because B is derived from A (therefore a B is an A).

On the other hand, casting an A* to a B* might be good or it might be bad depending on the object. So dynamic cast will discriminate.

All poodles are dogs, but not all dogs are poodles. It's like you're asking the compiler "Is this poodle a dog?" Of course the compiler will always say yes, because poodles are always dogs. But the opposite might not be true.
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Io_obj
{ // base class for object I/O system
virtual Io_obj *clone() = 0 ;
};

class Io_date : public Date, public Io_obj
{
};

void (Io_obj *pio)
{
Date *pd = dynamic_cast<Date*> (pio);
/ / ...
}


would this dynamic cast work? and if yes, as what a crosscast ???
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Io_obj
{ // base class for object I/O system
virtual Io_obj *clone() = 0 ;
};

class Io_date : public Date, public Io_obj
{
};

void (Io_obj *pio)
{
Date *pd = dynamic_cast<Date*> (pio);
/ / ...
}


would this dynamic cast work? and if yes, as what a crosscast ???
Sorry for the slow reply.

would this dynamic cast work?


In that example, I don't think so. Date and Io_obj are not related, so you can't cast between them.

(I might be wrong on this, as I can't check right now -- but I'm reasonably sure it won't work)

What you could do is dynamic cast to Io_date, then upcast to Date:

1
2
3
4
5
6
7
8
9
10
11
12
void (Io_obj *pio)
{
  Io_date *pd = dynamic_cast<Io_date*> (pio);
  if(pd)
  {
    // a valid Io_date, so we can upcast to a Date:
    Date* date = pd;

    // or really, we don't even need to upcast to 'date', but instead we can just
    //   use 'pd' directly since it is also a Date
  }
}
So what does a cross cast mean ?
I picked this example from Stroustrup and there it says it will work !
Then I must be wrong, sorry. I didn't actually test it =x
If D1 and D2 are both derived directly from B, then a crosscast is a cast of a D1 to a D2. In this simplistic case, the cast will fail since a D1 is not a D2. However, if there existed a class E which multiply inherited D1 and D2, then I could downcast the E to D1, and then successfully perform a crosscast of the D1 to D2.
Topic archived. No new replies allowed.