1

I need to use casting in my program. I have in my code heading, in my base class

scSupervisor* msSupervisor;    ///< My Supervisor

and I want to create an accessor function in the same header, in the derived class

Supervisor* Supervisor_Get(void){ return (Supervisor*)msSupervisor;}
                                       //dynamic_cast<Supervisor*>(msSupervisor);}

As shown, the static casting compiles and runs fine. However, if I change to the dynamic cast version (shown commented) I am presented with the error message:

cannot dynamic_cast '((Core*)this)->Core::<anonymous>.scCore::msSupervisor' (of type 'class scSupervisor*') to type 'class Supervisor*' (target is not pointer or reference to complete type)
                  dynamic_cast<Supervisor*>(msSupervisor);}
                                                        ^

In my eyes, it is a pointer. Do I do something illegal?

NathanOliver
  • 171,901
  • 28
  • 288
  • 402
katang
  • 2,474
  • 5
  • 24
  • 48
  • 8
    Does the code see the full declaration of `Supervisor` at this point? See my emphasis on the error message: _"target is not pointer or reference to **complete type**"_. – user0042 Aug 25 '17 at 12:17
  • See this answer https://stackoverflow.com/questions/332030/when-should-static-cast-dynamic-cast-const-cast-and-reinterpret-cast-be-used – Clonk Aug 25 '17 at 12:26

1 Answers1

2

Although dynamic_cast<T> has multiple limitations, the one that is relevant to your situation is described in section 5.2.7.1 of the C++ standard:

The result of the expression dynamic_cast<T>(v) is the result of converting the expression v to type T. T shall be a pointer or reference to a complete class type, or “pointer to cv void.”

Note the requirement for the class type to be complete in the description above.

In your case, T is Supervisor*, which, according to the error message, is not a pointer to a complete class (i.e. a pointer to a class that has been forward-declared, but not fully specified).

Including a header file for Supervisor will fix this problem.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • I did have a #include "scSupervisor.h" in my head. Later, however, I also had "class scSupervisor; class Supervisor;" maybe this confused the compiler? Anyhow, I moved the function body to the .cpp file, and everything works fine. – katang Aug 25 '17 at 12:32
  • @katang When this error happens for code in the header, the most likely cause is that a header guard made the definition invisible. Moving the code to cpp file often fixes this problem, because definitions from both headers are available. – Sergey Kalinichenko Aug 25 '17 at 12:37