December 12th, 2012, 12:37 PM
Organization of classes and header files in c++
Im starting to move into c++ from c and have some difficulty understanding how to organize classes. When programming in java i remembered each class had its own file. However in c++ im seeing examples of classes in the same file with main. Is this correct? Or is that for example purposes only? Thank you for your responses.
December 12th, 2012, 12:54 PM
It's pretty free-form.
For small programs, examples, demos, etc, you can throw everything into the same file.
But if your aim is a reusable component, then it makes sense to assign each class to its own foo.h interface file and foo.cpp implementation file.
Also as programs get larger, you need to exercise a lot more discipline over how the code is organised. Arranging files on class boundaries makes for an easier life.
December 12th, 2012, 01:12 PM
The execution of Java programs is quite different than the execution of C++ programs, as are their executables.
Java compiles to bytecode, which is based on a non-existent virtual machine, which must be executed by a special interpreter. That interpreter is designed to expect each class to have its own .class file, so each class must have its own compiled .class file. The design of the interpreter dictates the overall structure of your program and hence dictates that you create a separate .java file for each class.
C++ compiles to native code (in general; some environment such as .NET have their own intermediate languages) and the end result of a C++ build is a native-code executable file no different from one created by C or Pascal or FORTRAN or assembly. All the classes that that C++ program will use are contained within that single executable file.
Therefore, the actual organization of the source code of a C++ program is entirely up to the programmer. Rather than having that overall structure be dictated to him by the programming language, the C++ programmer is free to organize his source code files in response to concerns and considerations of readability, reusability, etc.