So I'm making a class to define a character in D&D. The way I thought setting up the class was that public members are defined in the header and private in the .cpp so they're not revealed to the outside right? How do you do this? Currently it looks like this and I'm sure it's wrong.
character.h:
namespace d20 {
class character {
public:
character(void);
virtual ~character(void);
// get stats
int getStr();
int getDex();
int getCon();
int getIntl();
int getWis();
int getCha();
// get modifiers of the stats
int getStrMod();
int getDexMod();
int getConMod();
int getIntlMod();
int getWisMod();
int getChaMod();
};
};
character.cpp:
namespace d20 {
class character {
private:
int str; // strength
int dex; // dexterity
int con; // constitution
int intl; // intelligence
int wis; // wisdom
int cha; // charisma
int hp; // hit points
int ac; // armor class
};
character::character(void) {
}
character::~character(void) {
}
}
Yes I know a ton is missing, but that's besides the point. Visual Studio 2010 shows it as 2 classes named character in class view. How do I accomplish what I intended? It doesn't matter much for this since it's an assignment and all the code is visible anyway, but for the future it'd probably be smart to keep private members out of the .h file correct?
Just put private
members in the same header file. Class definition cannot be spread across different files by design.
Why do you want prevent those private
members from being seen by clients in the first place? Being private
, they cannot be accessed directly anyway.
Edit:
Those private members are implementation details of the class. They are necessary to be in the definition of the class because sometimes compiler needs to know the size of objects of the class:
int main()
{
character ch;
// pass by value
Func(ch);
..
}
In the above example, the compiler has no way to know the size of ch
unless it sees the definition of character
, AND it can figure out the size by looking at the class definition! That's one reason why you need put implementations in the class definition.