I am trying to feed a string variable into the Class Constructor the data will be coming from cin. How might I do this. This is the function I am trying to us it in. and the Class is called Player, constructor is Player::Player of course. The Constructor works great I am just trying to figure out how to get input from user to name the class instance.
void makeCharacter()
{
system("cls");
string name;
cout << "What is your characters name?" << endl;
getline(cin, name);
Player name;
}
In the line Player name; you are declaring a variable called 'name' of type 'Player' but 'name' was already declared as string.
To create an object of class 'Player' passing 'name' to the constructor you should do something like these:
1 2
Player a_player ( name ); // explicit call of the constructor
Player another_player = name; // implicit call of the constructor
Notice that the scope would of the Player object you create in the function would be over when the function ends so you may return a copy of it:
1 2 3 4 5
Player /*Notice: not void*/ makeCharacter()
{
// etc.
return Player ( name ) ; // just call the constructor and return the object it created
}
Ok so would this work. I am just doing this for fun and to learn but I am trying to set it up so I can run multi "Player" class objects with differnet names. which gets there names form the command imput. also are you saying that if I want the Object to remain it needs to be called directly fomr the main() Function?
LOL yeah I did not even think about the fact that the constructor has access tot he private part of class. that does make my coding like double what it needs to be. thankx
struct BadClass
{
string name;
BadClass()
{
cout << "Give my name plz ";
getline ( cin, name );
}
};
struct goodClass
{
string name;
goodClass ( string Name ) : name ( Name ) // equivalent to name = Name but this would call name's constructor, not = operator
{
}
};
int main()
{
BadClass foo;
string bar_name;
cout << "Give my name plz ";
getline ( cin, bar_name );
goodClass bar ( bar_name );
}
You should give each object the scope you need. If you need it to be visible in main, declare it in main
So I should use Paramiters for my Contructor then somthing like Player::Player(string m_pname, string m_name, string m_class, int m_age) Allthough I guess I dont need to Declare these since they are in the class private
I find no reason to name things differently, except as a hint to myself that certain members are private. I expect the names I use in my class's declaration to be documentary, not obfuscatory.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
class Foo
{
public:
string name;
unsigned age;
bool has_job;
Foo( const string& name, unsigned age, bool has_job ):
name( name ),
age( age ),
f_can_vote( age >= 18 )
{
this->has_job = has_job;
}
private:
bool f_can_vote;
};