Separating class code into a header and cpp file
The class declaration goes into the header file. It is important that you add the #ifndef
include guards. Most compilers now also support #pragma once
. Also I have omitted the private, by default C++ class members are private.
// A2DD.h
#ifndef A2DD_H
#define A2DD_H
class A2DD
{
int gx;
int gy;
public:
A2DD(int x,int y);
int getSum();
};
#endif
and the implementation goes in the CPP file:
// A2DD.cpp
#include "A2DD.h"
A2DD::A2DD(int x,int y)
{
gx = x;
gy = y;
}
int A2DD::getSum()
{
return gx + gy;
}
In general your .h contains the class defition, which is all your data and all your method declarations. Like this in your case:
A2DD.h:
class A2DD
{
private:
int gx;
int gy;
public:
A2DD(int x,int y);
int getSum();
};
And then your .cpp contains the implementations of the methods like this:
A2DD.cpp:
A2DD::A2DD(int x,int y)
{
gx = x;
gy = y;
}
int A2DD::getSum()
{
return gx + gy;
}
Basically a modified syntax of function declaration/definitions:
a2dd.h
class A2DD
{
private:
int gx;
int gy;
public:
A2DD(int x,int y);
int getSum();
};
a2dd.cpp
A2DD::A2DD(int x,int y)
{
gx = x;
gy = y;
}
int A2DD::getSum()
{
return gx + gy;
}
It's important to point out to readers stumbling upon this question when researching the subject in a broader fashion that the accepted answer's procedure is not required in the case you just want to split your project into files. It's only needed when you need multiple implementations of single classes. If your implementation per class is one, just one header file for each is enough.
Hence, from the accepted answer's example only this part is needed:
#ifndef MYHEADER_H
#define MYHEADER_H
//Class goes here, full declaration AND implementation
#endif
The #ifndef etc. preprocessor definitions allow it to be used multiple times.
PS. The topic becomes clearer once you realize C/C++ is 'dumb' and #include is merely a way to say "dump this text at this spot".