-3

I want to downcast a object but it causes 'cannot dynamic_cast' error.. (source is not of class type)

what is the problem??

this is my code,

class A{...}

class B: public A{...}


A& x;
dynamic_cast<B&>(&x))!=0 //error here (source is not of class type)
juanchopanza
  • 223,364
  • 34
  • 402
  • 480
sol
  • 11
  • 2
  • 1
    Show us a [mcve] or [Short, Self Contained, Correct (Compilable), Example](http://www.sscce.org/). – Jesper Juhl Sep 16 '18 at 14:28
  • Btw; `x` is a *reference*. Not a class instance. – Jesper Juhl Sep 16 '18 at 14:36
  • 1
    In addition to the pointer/reference issue that has been pointed out elsewhere, the class definitions here are, obviously, not legal. This may hide other problems. In particular, if `A` has no virtual functions, the `dyanamic_cast` is not valid. And, of course, `x` has not been initialized, so, again, the code can't compile. In short: too much summarization. Post the smallest code you can come up with that compiles and **shows the problem**. – Pete Becker Sep 16 '18 at 14:56

2 Answers2

2

It is only possible to dynamic_cast a class type to a reference.

what is the problem??

As the error said, the result of &x expression is not a class type. It is a pointer type. You've attempted to dynamic_cast a pointer to a reference. That is not possible.

eerorika
  • 232,697
  • 12
  • 197
  • 326
1

You have a mismatch in types between reference and pointer, so the code shouldn't compile. Since you're checking for a null pointer, you apparently want to deal with pointers, so the code should be something on this general order:

class A{...}

class B: public A{...}


A& x;
if (dynamic_cast<B *>(&x))!=0)
    // cast was successful
else
    // cast wasn't successful

You could also use references throughout, but if you do then an unsuccessful cast is signaled by throwing a std::bad_cast exception:

void f(A &a) { 
    try {
        B &b = dynamic_cast<B &>(a);
        b.do_something_specific_to_b();
    }
    catch (std::bad_cast const &b) {
        // `a` wasn't of type `B`
    }
}

Note, however, that dynamic_cast is primarily useful in cases like this, where you're receiving the pointer/reference as a parameter, or for things like a collection of pointers, some of which may point to various different types:

std::vector<A *> objects;

for (auto const *a : objects) {
    B *b = dynamic_cast<B *>(a);
    if (b != nullptr)
        b->do_B_specific_stuff();
    else
        a->do_generic_A_stuff();
}

Finally, I'd note that if you find yourself using dynamic_cast very often, chances are pretty good that you're doing something wrong. I've used C++ since before dynamic_cast existed, and in the time it has existed, the number of times I've had to use it could probably be counted on the fingers of one hand (with a couple left over). There are times and places where it's useful (and a few where it's really important), but they really are fairly unusual.

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111