Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to Declare Structures, etc?

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?

like image 457
cam Avatar asked Apr 05 '10 12:04

cam


2 Answers

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.

like image 173
Billy ONeal Avatar answered Oct 17 '22 22:10

Billy ONeal


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.

like image 39
Zoli Avatar answered Oct 17 '22 21:10

Zoli