How to use a variable in separate class when forward declaration fails?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Ed Fung
    New Member
    • Dec 2010
    • 2

    #1

    How to use a variable in separate class when forward declaration fails?

    Hey, allow me to make a sketch of the situation:

    in foo.cc
    Code:
    #include "bar.h"
    Actor actor;
    in bar.h
    Code:
    class Bar {
    public:
      void doSomething();
    };
    in bar.cc
    Code:
    #include "bar.h"
    
    Bar::doSomething() {
      actor.action();
    }
    When I compile the code, it will fail because it can't find "actor" in bar. I can't seem to forward declare it, and I can't use a static actor either (I need 'Actor actor' to come after '#include "bar.h"'). Help?

    Thanks
    Ed
  • Savage
    Recognized Expert Top Contributor
    • Feb 2007
    • 1759

    #2
    Take a look at this.

    Regards :)

    Comment

    • Banfa
      Recognized Expert Expert
      • Feb 2006
      • 9067

      #3
      A forward declaration like Actor actor; just names the type. This allows the compiler to use the type to create pointers and references but does not allow you to access any members of the type (since the compiler does not know about them).

      To access the class members you need to have the definition of the class Actor which is presumably in actor.h. You should include this into bar.cc.

      Forward declarations are normally used where 2 classes are self referential (that is each class references the other). The forward declaration is normally enough to allow the header of the other class to compile without errors since it normally only contains references and pointers to the first class and the header file for the first class can be included into code files for full access to the class.

      Comment

      • Ed Fung
        New Member
        • Dec 2010
        • 2

        #4
        extern is exactly what I needed. Thank you both :)

        Comment

        Working...