Can classes defined in one file be referenced in another?

Started by
2 comments, last by Sirveaux 20 years, 9 months ago
I have a single cpp file that defines many of the classes that I want used throughout my program. In another file, whenever I try to create an object using those classes it gives me errors. It is obviously a problem of scope because if I copy the class code into the same file, it compiles fine. Is there a certain way I need to define the classes in order to make them accessable by the rest of the program?
Advertisement
You need to put the definitions of those classes in a header file. Then you put the implementation of said classes in a .cpp file. Whenever you need to reference a class defined in a header file, you must #include the header file containing the class definition.

Something like this:
// Foo.hclass Foo{public:   void DoStuff();};// Foo.cpp:#include "Foo.h"void Foo::DoStuff(){   // ... }// Bar.h:class Bar{public:  int DoOtherStuff();};// Bar.cpp:#include "Bar.h"int Bar::DoOtherStuff(){   return 42;}// main.cpp#include "Foo.h"#include "Bar.h"int main(){   Foo foo;   foo.DoStuff();   Bar bar;   bar.DoOtherStuff();}



AnkhSVN - A Visual Studio .NET Addin for the Subversion version control system.
--AnkhSVN - A Visual Studio .NET Addin for the Subversion version control system.[Project site] [IRC channel] [Blog]
I tried that also, but it said that it couldn''t find the .h file even though it was included in the project. I noticed that you used quotes instead of <> for the #include, though. Is that what you''re supposed to do for a header file that''s already in your project?

Let''s see...

Yep. That did it. After all that it was just because I was using #include <classes.h> rather than #include "classes.h". Thanks a lot. That was driving me insane!
If you use brackets, it will look for the headers in the compiler''s standard include directories. If you use quotes, it will look in the same directory as the .cpp.


AnkhSVN - A Visual Studio .NET Addin for the Subversion version control system.
--AnkhSVN - A Visual Studio .NET Addin for the Subversion version control system.[Project site] [IRC channel] [Blog]

This topic is closed to new replies.

Advertisement