Possible Duplicate:
C++ – What should go into an .h file?
I know this is general, but I find it really annoying coding things twice, and would find it a lot easier if I didn’t have to browse between two files (my .h and .cc) rather than just keep it all in one.
So, what is the point in having a header file if most of what is there must be rewritten and the rest can just be placed in the .cc.
Instead of:
class VoterData {
// raw data
Voter::States state;
bool vote;
unsigned int numBlocked;
// flags
bool _hasState, _hasVote, _hasNumBlocked;
public:
VoterData();
void reset();
// getters
Voter::States getState();
bool getVote();
unsigned int getNumBlocked();
bool hasState();
bool hasVote();
bool hasNumBlocked();
// setters
void setState(Voter::States state);
void setVote(bool vote);
void setNumBlocked(unsigned int numBlocked);
};
AND:
/* VoterData */
VoterData::VoterData() {
reset();
}
void VoterData::reset() {
_hasState = _hasVote = _hasNumBlocked = false;
}
// getters
Voter::States VoterData::getState() { return state; }
bool VoterData::getVote() { return vote; }
unsigned int VoterData::getNumBlocked() { return numBlocked; }
bool VoterData::hasState() { return _hasState; }
bool VoterData::hasVote() { return _hasVote; }
bool VoterData::hasNumBlocked() { return _hasNumBlocked; }
// setters
void VoterData::setState(Voter::States state) {
this->state = state;
_hasState = true;
}
void VoterData::setVote(bool vote) {
this->vote = vote;
_hasVote = true;
}
void VoterData::setNumBlocked(unsigned int numBlocked) {
this->numBlocked = numBlocked;
_hasNumBlocked = true;
}
Why shouldn’t I just put it all in the .cc file and declare the class there?
C++ doesn’t tell you where to put your code. Actually, in your case it might be better to use one file:
If your class is more complicated than my or your example, you will notice that having a header file gives an advantage in understanding your program.
In that case, the header file (x.h) will be small (e.g. 20 lines of code) and the implementation file (x.cc) will be large (e.g. 200 lines of code – much more than in your example class). Anyone (who wants to understand what the class does, or how to use it) has to look at the 20 lines in the header file and doesn’t have to look at the 200 other lines of code – that’s great (speaking from experience)!
So, your example doesn’t require separation into header and implementation files.