Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

error: cannot dynamic_cast ... (target is not pointer or reference)

I'm learning exception handling in C++ and run into a problem. Here's the code:

#include<iostream>
#include<exception>

using namespace std;

class A
{
public:
    virtual void f(void){}
};

class AA:public A
{
public:
    void aa(void){};

};

int main(void)
{

    A a;
    try
    {
        dynamic_cast<AA>(a).aa();
    }
    catch(exception ex)
    {
        cout<<"["<<ex.what()<<"]"<<endl;
    }
    return 0;
}

So I thought the try catch will allow the function to execute and show me the content of the exception, but my compiler does not compile it. I'm using codeblock with GNU GCC. Please help me and show me what I need to do to get the code run as I intended. thanks a lot.

like image 270
focusHard Avatar asked Jun 16 '13 02:06

focusHard


1 Answers

I just dealt with the same error, but in my case I was going from a pointer to a pointer, so the other answers here did not apply. My error message was slightly different, however: error: cannot dynamic_cast 'f()' (of type 'class B*') to type 'class A*' (target is not pointer or reference to complete type).

The root cause in my case was much more simple and mundane.

Notice the addition of to complete type at the end. This caused me to remember that I did not include the header file for my class which I was using. It was not an unknown symbol because A* was forward declared with class A; in the header file, causing it to exist but not be complete, hence the error.

The solution in my case was to include the header file for the class I was casting to.

This is not the question asker's problem above, but as can be seen by my case can generate the same type of error.

like image 152
Loduwijk Avatar answered Oct 17 '22 14:10

Loduwijk