The read method you have defined in your mutant_info class is not a constructor. Also, your use of the read and set methods combined together is incorrect.
As your code is written, You prompt for the alien name, then call read() which receives input for all three members in the class (not just the name), then the setName method which passes in the value of the local string name, but that local string is never assigned a value. This process is then repeated for power and level, which cause a lot of redundant and out of sequence input.
Gumbercules code removes the read() calls, inputs the values into the local variables, then passes those variables into the appropriate set method. Prompt for name, set name. Prompt for power, set power. Prompt for level, set level.
As for your 3 constructors: Constructors are defined using the same name as the class itself. Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
class myClass{
std::string str1;
int myVal;
public:
myClass() : str1("abc"), myVal(25){} //Default constructor
myClass(std::string a, int c): str1(a), int(c){} //Constructor with string and int as input parameters
myClass(std::istream&); //Constructor with input stream param.
};
//Caution should always be taken when using streams to construct objects
//There are more potential pitfalls with this kind of constructor than other constructors
//This simple example is perfect example of how NOT to use them, but that's beyond the scope of this thread
myClass(std::istream& in){
in >> str1 >> myVal;
}
|
The constructor only gets called when an instance of the class is created, it's not a class method you explicitly call yourself. Which constructor gets called depends on how the object is instantiated (ie, the constructor that gets called is the one that matches the input parameters provided at the time of construction).
mutant_info mutant;
calls the default constructor, since no input parameters are provided. This method requires you use your set methods to set the class members to the appropriate values prior to inserting them into your vector. (unless you want to insert an object set to the default values as defined in the constructor)
Alternatively, you could push the object into your vector this way
store.push_back(mutant_info(name, power, level));
. This method uses the constructor that takes two strings and an int as input parameters. You would prompt the user for the three values, than execute this call, passing those values in.
And to use your third constructor,
store.push_back(mutant_info(cin));
. This constructor prompts for the input values within the constructor itself, and so your external variables are not used.
There's actually a forth constructor getting used in your code as well. When you call
store.push_back(mutant);
, push_back is making a copy of mutant and inserting that copy into the vector. This is done using the copy constructor, which the compiler will define for you if you don't explicitly define it yourself.