Problem with forward declaration



  • Hi all,
    I've got a problem with a forward declaration. My source tree structure is as follows:

    @

    • src
      role.h
      role.cpp
      • daemon
        daemon.h
        daemon.cpp
        @

    where daemon.h uses Role via forward declaration:

    @
    // daemon.h

    // forward declaration of the Role implementation
    class Role;

    class Daemon : public QObject{
    ...

    QList<Role> roles();
    }
    @

    and when I compile the project I got the following error for the Daemon::roles() method:

    @error: ‘Role’ was not declared in this scope@

    Am I missing something?



  • Must be a pointer, like this:
    @
    QList<Role *> roles();
    @

    In daemon.cpp
    @
    #include "role.h"
    @


  • Moderators

    Your QList is of Role objects, not of Role pointers. A forward declaration would be sufficient for pointers, but since you are using the entire object, you'll need to #include "role.h" in your daemon.h file.



  • Thanks, I was not aware forward declaration worked only for pointers, but it makes sense!



  • It works for pointers and references (which technically are more or less pointers) and, in both cases, only as long as you need the pointer or reference, but not any of the methods or members of the class.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.