Classes across multiple files.

Could someone give me a short and simple examples of putting classes in mutiple files?

1
2
3
4
5
class ProgramFun
{

//Generic function i want in a different file, but still in the class
};
Usually a class definition is placed in a header file while its member functions' definitions are placed in a .cpp module if they were not defined in the class definition (that is they were only declared in the class definition).
Normally you put the class declaration (your code above) into a ProgramFun.h header file, then the definition of the class functions into a ProgramFun.cpp file. Then in a .cpp file that uses the class (whether it be the .cpp file that has main() in it, or some other file), you #include ProgramFun.h.

In the ProgramFun.cpp you need to use the scope resolution operator ::, like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
ProgramFun::ProgramFun() {  //default constructor
//your code here
}

ProgramFun::ProgramFun(int arg1, int arg2) {  //another constructor
//your code here
}

ProgramFun::~ProgramFun() {  //default destructor
//your code here
}

ProgramFun::MyFunction(int Arg1, double Arg2) {

//your code here
}



Don't be tempted to provide get / set functions for each private member variable, better to think about how things happen in the real world - provide functions that reflect that.

Hope all goes well.
Last edited on
I forgot to say that If you use an IDE, you should be able to use a class wizard, which will create the appropriate files, and stubs for the functions. IF you create a new function, you can get it to create a stub for it in the .cpp file. There are also handy things for when there is inheritance.

HTH
Aha! I got it, thanks for the help.
Topic archived. No new replies allowed.