Click to See Complete Forum and Search --> : Organizing classes with .h & .cpp


zsimaiof
October 27th, 2004, 10:01 AM
Hi guys.I have a question which has to do with the classes...I've read quite a lot tutorials and the majority encourages the reader to declare its classes in a .h library file like this

[Class.h] -for exaple
#include "stdafx.h"
__gc class testclass
{
public:
void function1(int var1);
double function2(float var2);
bool var3;
protected :
double var4;
}

and to write the functions in a separate .cpp file such as:

[Class.cpp]
#include "stdafx.h"
#include "Class.h"

testclass::function1(int var1)
{
command1;
command2;
........
}

....and so goes on with the other functions...



MY question is : 1) OK..We do benefit by having our classes' declarations in a .h library but why do we need to have the body of our functions in a separate .cpp file ? As a result of this structure we are forced to write again again the functions we need in each .cpp file... (Or am I wrong?)Unless we have lots of .h libraries and a single .cpp containing our main()...
Pls answer and thnx in advance

Idmir
October 27th, 2004, 10:21 AM
if you are wrting your own classes that you don't plan to reuse then I guess you could put the stuff from the cpp files in the .h files. But when you plan to reuse the class its better to split it up. Would you want to include the whole windows.cpp file or just the windows.h file?

ahoodin
October 27th, 2004, 10:30 AM
Well the one good approach to this is to create a thing called an .hpp file. You can just #include these in the headers or .cpp files if you so choose. It is possible to put code inline in the class definition or to put it directly in the header file, but it is a sloppy dis-organized coding style. The headers are best used as a location for a class definitions or prototypes, while implementations are better left in a seperate file. This makes it easier to seperate functionality from definitions such as in the case of a .dll that has a header file for exports.

HTH,

ahoodin