I had a homework assignment where I had to create an abstract class named Player (code below) and a dozen derived player position classes and store an instance of each in a single vector. The code is to get the player name, player id, and player position from the user to then instantiate an object from the appropriate class, like so:
Quarterback player(name, id)
I ran into an issue when I decided to create an instance of my object by directly assigning it to a pointer variable:
Player *player = &Quarterback("John Doe", 77);
The problem when I do this is that the name attribute is empty in the new object instance but the id attribute remains intact with what I assigned it. My theory is that string is considered out of scope when I create the object this way because the object is not referenced directly in the main program. If so, why does the rest of the object still exist as normal? What is going on behind the scenes of this declaration?
Header file:
// Player.h
class Player
{
public:
Player(std::string name, int id);
std::string getName() const;
int getPlayerID() const;
virtual std::string getPlayerPosition() const = 0;
virtual std::string play() const = 0;
virtual std::string toString() const = 0;
private:
std::string playerName;
unsigned int playerID;
};
class Quarterback : public Player
{
public:
Quarterback(std::string name, int id);
std::string getPlayerPosition() const override;
std::string play() const override;
std::string toString() const override;
};
// ...
Source file:
// Player.cpp
Player::Player(string name, int id)
{
if (name == "" || only_whitespace(name))
throw "Name cannot be empty.";
if (id < 1)
throw "ID number must be greater than 0.";
playerName = name;
playerID = id;
}
// ...
Quarterback::Quarterback(string name, int id)
:Player::Player(name, id)
{}
// ...
Thank you for your help!
EDIT: Here's a fuller version of my source code extracted from my homework assignment and put in a single file at this link. It doesn't compile on GCC (which is appropriate behavior according to the comments below), but it compiles with MSVC.