views:

79

answers:

2

Should all structs and classes be declared in the header file? If I declare a struct/class in a source file, what do I need to put in the header file so that it can be used in other files? Also, are there any resources that show some standard practices of C++ out there?

+3  A: 

Should all structs and classes be declared in the header file?
Yes. EDIT: But their implementations should be in cpp files. Sometimes users coming from C# or Java don't realize that the implementation in C++ can be completely separate from the class declaration.

If I declare a struct/class in a source file, what do I need to put in the header file so that it can be used in other files?
You can't. The compiler needs the full declaration of a class available in any translation unit that uses that class.

Also, are there any resources that show some standard practices of C++ out there?
You could just download source for any number of open source applications to see. Though the only completely consistent thing you're likely to see is use of header guards, and keeping all declarations in header files.

Billy ONeal
A struct need not be header files if there is no intention of using it in some other source file. A functor written for STL algorithm is one such example.
Naveen
I use a lot of structs that are implementation details - these are declared in the .cpp files
anon
-1 Naveen and Neil have both given reasons why not *ALL* structs should be declared in headers. Yes to the OP's questions gives a misleading answer, particularly for newbies.
Steve Fallows
For the record, the term for a structure declared and used only in a .cpp file is "opaque". External code may obtain and pass around pointers to opaque structures, but they shouldn't manipulate what the pointers point to.
Mike DeSimone
@Steve @Neil @Naveen: Okay, there are few true "Always" or "Never" rules in programming, and I assumed that what the OP meant was "In the vast majority of cases, say 99.9% of the time". I think the exception does not disprove the rule.
Billy ONeal
+2  A: 

The whole point of header files is to declare interfaces that are meant to be shared across other source files. Oftentimes, people declare abstract types in header files and implement them in source files as needed. This means, of course that the newly implemented type will only be available to that particular source file. If you need to use a type across multiple files (which is usually the case), then you'll need to use header files.

C++ faq is usually a great resource for best practices.

zdawg