-6

So, I ran into this problem while trying to create a text based game to play at work. :P

I wanted users to be able to make their new character, and the character object would be named, whatever they input. I know that I can just have a string variable that holds the name and use a counter, but even then, can I make the program change that? Here's an example.

(in this situation there is a menu that uses switch case, and another file with the class 'Character')

case: 1
    string tempName;
    cout << "Please enter the name of your new character." << endl;
    cin >> tempName;
    Character tempName();
    Character.setName(tempName);
    cout << "Congratulations! Your character " << Character.getName() << " has      been created." << endl;
πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
Bobin
  • 1

1 Answers1

0

No, this just doesn't work.

First of all, the compiler must know all the variable names when the code is compiled. After compilation the names are gone and the executable file contains the binary code to be executed. That in itself makes it impossible to change the names later.

You also have a few other problems in your example code, so I bet you get quite a few confusing messages from the compiler. I'm sure the compiler itself is pretty confused by your attempts. :-)

First of all Character tempName(); doesn't declare an object of type Character, but the () at the end makes it declare a function returning a Character.

The fact that tempName already is the name of a string doesn't make it any better.

The next line Character.setName(tempName); is probably an attempt to call a function for a type. Interesting attempt, but it just doesn't work that way. The closes you have is Character::setName(tempName); if setName is a static member of class Character. But that would affect all objects of that type, not only a single one.


Oh, and I guess case: 1 is just a typo for case 1:.

Bo Persson
  • 90,663
  • 31
  • 146
  • 203