I was wondering if someone could tell me how to delete a variable so if i say wanted to no longer use it, or after its deleted declare it as an int, or double ect; i could do it with the same variable.
/* the following code works in my full
program, however with the delete
command it does not, and i am
trying to delete "string x" */
void Player1()
{
Player Player1;
string x;
cout << "What is your name? ";
cin >> x;
Player1.SetPlayerName(x);
cout << "What is your age? ";
cin >> x;
Player1.SetPlayerAge(x);
cout << "What is your gender? ";
cin >> x;
Player1.SetPlayerGender(x);
delete x;
}
The delete keyword can only be used with dynamically allocated memory (that is, memory obtained by using the new keyword). You have several options in this case:
1. Dynamically allocate/de-allocate X (bad):
1 2 3
string* x = new string();
//...
delete x;
2. clear() the content of X to free memory (good):
1 2 3
string x;
//...
x.clear();
3. Put X in a lower scope so that it goes away when that scope ends (good):
1 2 3 4 5 6
//in main
{
string x;
//...
//copy X into player
} //x is destroyed here
Sorry, you'll just have to declare more than one variable. It helps prevent ambiguity anyway, there is no reason why you should ever want nor need to do what you just described.
e: If you really want to have a data type that can hold either an int or a string declare a union that can hold either an int or a string I guess. But seriously don't do this unless there's some logical reason why a variable could hold either an int or a string.
Name them differently. No reason the int has to be named x also.
Names such as string s; and int i; instead of x help remind you of the type of the variable. Note that at line 18, setPlayerGender probably is not expectig an int.