By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,948 Members | 663 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,948 IT Pros & Developers. It's quick & easy.

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

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

Expand|Select|Wrap|Line Numbers
  1. #include "bar.h"
  2. Actor actor;
in bar.h
Expand|Select|Wrap|Line Numbers
  1. class Bar {
  2. public:
  3.   void doSomething();
  4. };
Expand|Select|Wrap|Line Numbers
  1. #include "bar.h"
  3. Bar::doSomething() {
  4.   actor.action();
  5. }
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?

Dec 5 '10 #1

✓ answered by Savage

Take a look at this.

Regards :)

Share this Question
Share on Google+
3 Replies

Expert 100+
P: 1,764
Take a look at this.

Regards :)
Dec 5 '10 #2

Expert Mod 5K+
P: 8,916
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

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.
Dec 6 '10 #3

P: 2
extern is exactly what I needed. Thank you both :)
Dec 7 '10 #4

Post your reply

Sign in to post your reply or Sign up for a free account.