1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2012
    Rep Power

    Organization of classes and header files in c++

    Hello everyone,

    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.
  2. #2
  3. Contributed User
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Jun 2005
    Rep Power
    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.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper
  4. #3
  5. Contributing User
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jan 2003
    Rep Power
    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.

IMN logo majestic logo threadwatch logo seochat tools logo