Originally Posted by
grumpy
The purpose in making a member private is to prevent any other code (including in derived classes) from directly modifying it.
If you really want direct access to the member, then make it public (if you are happy for ANY other code to modify int) or protected (if you only want derived classes to have access).
The better approach is use a public or protected member of the base class to do the work. In your case, you have setName(), so can do
Code:
class Player
{
public:
virtual void setName(const std::string &s)
{name = s;}
private:
std::string name;
};
class HumanPlayer : public Player
{
public:
void setName(const std::string &s)
{
Player::setName(std::string("h") + s); // this calls setName() as supplied by the base class
}
};
A couple of other points to note
1) I have made string into std::string. It is a really BAD IDEA to use "using namespace std;" in a header files. Some "using" directives are okay in a header file but better to avoid them completely (most using directives have unwanted effects in a header file).
2) Pass strings by const reference rather than by value. Copying large strings unnecessarily is not a good idea.
Thanks this explained alot!!
As a followup question:
An example of how I run my program is Where -p signifies the input of a user defined player name John (the John argument), who is a human player (the h argument)
In my code I take the from my main program and store it in a vector called cmdArgs like so:
Code:
vector<char*> cmdArgs;
for (int i = 1; i < argc; ++i)
{
cmdArgs.push_back(argv[i]);
}
Later on I call:
Code:
HumanPlayer hp;
hp.setName(cmdArgs.at(1));
which gives me an error:
Code:
Game.cc:116: error: no matching function for call to âHumanPlayer::setName(char*&)â
HumanPlayer.h:12: note: candidates are: virtual void HumanPlayer::setName(std::string&)
I'm guessing my cmdArgs vector is not storing the only ?
I also have other functions which work perfectly with cmdArgs. For example (Don't worry about what the code means, but the fact that it uses
Code:
cmdArgs.at(--some number here--)
just fine) :
Code:
if (static_cast<string>(cmdArgs.at(0)) == "-r")
{
int seed = atoi(cmdArgs.at(1));
mainDeck.setRandomSeed(seed);
cmdArgs.erase(cmdArgs.begin(), cmdArgs.begin()+2);
if (cmdArgs.size() == 0){ break; }
}
What's the best way to resolve this error?