Large projects may be written by multiple people, or even companies being contracted. Medium projects may not want to have a single large file, and instead, break it into smaller chunks, or files, which makes managing the project easier and easier to edit the files as you look for items.
To do this, you need to separate out your classes into separate files. Each class will have two files, a header file and the class file.
The Header File
The header file is what we’re going to include in our main file, and it holds all of the information about method prototypes and properties.
As a header file it will have a .h extension, and the name of the class it represents.
class Circle {
public:
double radius;
Circle();
Circle(double newRaidus);
double getArea();
double getDiameter();
};
Notice that a lot of the information for the class is there.
The CPP Source File
We will move the implementation of those class methods into a .cpp file.
#include "circle.h"
Circle::Circle()
{
radius = 3.5; // this is the way
}
Circle::Circle(double newRaidus)
{
radius = newRaidus;
}
double Circle::getArea()
{
return radius * radius * 3.141592;
}
double Circle::getDiameter()
{
return radius * 2;
}
Notice at the top, we’re going to have to include the header file. Notice that instead of enclosing it in angle brackets, we enclose them in quotes, this is because it is local, relative to our file.
Likewise, we’re going to write each method outside of a class definition. So how does it know which class it belongs to?
We add the class reference to the front of the method names. In this case Circle
and then put two colons in front of each one, so total it is Circle::
.
Notice that the file has an extension of .cpp (for C Plus Plus).
Where the main is
Next we have the main file. Here we will include the header again, and we can run our application like we normally would. C++ will handle the compiling of the different files and linking them together as part of the compilation process.
#include <iostream>
#include "circle.h"
using namespace std;
int main()
{
Circle c;
cout << c.getArea();
return 0;
}
Separating Definition from Implementation was originally found on Access 2 Learn