Allow user to name a class object - c++

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;

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:.

Related

request for member which is of pointer type (maybe you meant to use '->' ?) [duplicate]

Why are the parenthesis surrounding the pointer in this code snippet necessary?
cout << (*pStr).size() << endl;
After looking back in my book I finally found a small mention of it in a footnote that I had looked over.
It says, "--this ensures that the dot operator will be applied to the object to which the pointer points."
Why does this not work?
cout << *pName.size() << endl;
I'm only asking because my book doesn't give a very good explanation and because I just wasted a lot of time trying to figure out why this line of code was giving an error for me. (I forgot the parenthesis, of course)
. has higher precedence than *. So *foo.bar means *(foo.bar).
So this code is invalid because the . operator can not be applied to a pointer
(I used an example without the function call operator () because that also has higher precedence than * so it was getting complicated).
Remember that you can and should write pName->size(). The -> was presumably created to avoid all these parentheses.

What exactly are cout/cin?

I know Java and now want to learn C++. I can't understand what are cout (character output stream) and cin (character input). Are these global variables? Then why
"My message">>cout;
doesn't work? But
cout<<"My message";
works.
cout is an instance of the class std::ostream, and yes, it's a global variable. But operator>>(char *, ostream& os); hasn't been declared by the relevant header, so "My message">>cout; will give an error of something like "can't find an operator >> which takes arguments const char * and std::ostream" (and possibly a lot more errors because sometimes compilers get very confused by these sort of things).
cin is the same thing, except std::istream
If you really want to mess with peoples heads, you could do:
template<typename T>
std::ostream& operator>>(T x, std::ostream& os)
{
os << x;
return os;
}
Of course, it won't work for "My Message " >> "Some other string" >> cout;, which is probably one of the reasons it's not done that way.
Note that this is simply slight abuse of the operator overloading, where we have a custom type as the left-hand side, and standard or non-standard type on the right hand side. cout is no different from some other variable of a custom type.
std::cout and std::cin are indeed global variables. Your code doesn't compile because that's not the way the language works. You have to put the stream on the left, and then the operator and then the variables you are streaming into/out of. (For output, you can use literals and expressions as well as variables.)
consider the arrows as streams. << stands for output stream , while >> stands for input stream.
so cout << "hello" means output to screen
when cin >> a means asks from a user input for variable a
cout can also use "+" like for example you can add more strings to one stream like this
cout << "Hello" << "world" << "I am john";
cin in the same way can ask for input from multiple variables
cin >> a >> b ; will ask from user to input two times one for each variable
iostream is a header file which contain classes handling input and output operations for a console. Its like you create a object when you say "cin" for the input class handling input operation for a console in the header file. Same can be said about "cout" where a object is being created from a class handling output operation to a console in the header file.
When you consider "cin", imagine creating a pipe connected to the console and your program and an object "cin" taking your inputs from the console which you provide through your keyboard and dumping them on to the program. That's the reason you can see having a ">>" operator for cin and you can find the analogy to the pipe where the operator is taking the job of specifying the direction for the object "cin".
Whereas for "cout", imagine creating a pipe connected to the console and your program and an object "cout" taking its input from the program and dumping them on to the console. That's the reason you can see having a "<<" operator for cout and you find the analogy to the pipe where the operator is taking the job of specifying the direction for the object "cout".
So basically you need to first specify what object you would be creating for your operations and then assigning an operator to accomplish your task. If you include the header file, then its like you could use those objects anywhere throughout your program.
So, "My message">>cout; doesn't function the way you expect it to be because there is no object and an operator to accomplish your task whereas cout<<"My message"; does.
The technical aspects have been described by Mats Petersson. This is just to give you a general picture of what's actually happening pictorially. Hope this helps you.

Is it possible to check existance of variables?

Can we understand if there is a variable mentioned/created/exists ?
I mean something like that:
//..Some codes
int main(){
int var1;
float var2;
char var3;
cout << isExist("var1") << endl;//Or isExist(/*Something related with var1*/)
cout << isExist("var2") << endl;
cout << isExist("var3") << endl;
cout << isExist("var456") << endl;//There is no variable named with var456
return 0;
}
Output:
true
true
true
false
No. C and C++ do not support reflection.
Not in C/C++. But you could have a look at boost reflect library. http://bytemaster.bitshares.org/boost_reflect/
In C/C++, accessing a variable not defined will generate a compiler error. So, in a sense, that is inherent to how it works. You cannot do that at runtime, at least not as you are trying to do, and should not have need to - because you can't name new variables at runtime in the first place, so you should already know the variables there.
The only way to do this would be indirectly with macros. Macros can't check if a variable itself is defined, but a define could be paired with a variable definition and you could check for the define token.
#define A_VARIABLE 1
int a_variable = 60;
And later:
#ifdef A_VARIABLE
...
#endif
Like most macros, it is probably best to avoid this sort of behavior - however, I have seen it used to deal with platform-dependence of certain variables.
Dynamic memory is a different matter. Since you did not mention it, I will not go into it, but suffice to say it is a more complicated problem which proves the bane of many programmers and the source of many runtime errors.
The 'programming language C' is a human readable form of providing instructions to a computer. All names in the program have only meaning within the program text.
Upon compilation, the names are replaced with a symbolic reference to a storage location or function (execution starting point). Any symbol not found in the current complilation unit (object module) is marked for future resolution.
The object modules are combined (linked) into an executable, where all references to symbols not in an object module are resolved with locations in other object modules; otherwise the creation of the executable fails.
Since now any names have been replaced with references to storage locations and execution starting points, the executable doesn't know anymore about the names used in the program text to refer to its storage locations and functions.
Any ability to do so (the 'reflection' as user #Bill-Lynch calls it) would be 'bolted on' to the language/environment as a separate layer, for example provided by the debugging/development envionment.

Eclipse Luna C++ endl

I just started learning C++ and I noticed that when I do cout << "Some text" << endl; endl is not bold. I want to make sure that this is not a problem and it won't cause any future problems.
Do not (<---- this intentionally bold!) use std::endl! Ever. It has no place in C++. It was a good idea but it is being abused. If you want a newline, use '\n'. If you want a flush, use a std::flush. Here is a more thorough explanation.
I don't know about Eclipse but I'd assume that it highlight keywords in bold: std::endl isn't a keyword. It is just a function (well, actually it is a function template but the details really don't matter) with a specific signature (std::ostream&(std::ostream&)) pointers to which are treated special when using it with an output operator on a std::ostream: the operator will just call the function with the stream as argument. These functions are called manipulators.

Convert string to variable name or variable type

Is it possible to convert strings into variables(and vise versa) by doing something like:
makeVariable("int", "count");
or
string fruit;
cin >> fruit; // user inputs "apple"
makeVariable(fruit, "a green round object");
and then be able to just access it by doing something like:
cout << apple; //a green round object
Thanks in advance!
No, this is not possible. This sort of functionality is common in scripting languages like Ruby and Python, but C++ works very differently from those. In C++ we try to do as much of the program's work as we can at compile time. Sometimes we can do things at runtime, and even then good C++ programmers will find a way to do the work as early as compile time.
If you know you're going to create a variable then create it right away:
int count;
What you might not know ahead of time is the variable's value, so you can defer that for runtime:
std::cin >> count;
If you know you're going to need a collection of variables but not precisely how many of them then create a map or a vector:
std::vector<int> counts;
Remember that the name of a variable is nothing but a name — a way for you to refer to the variable later. In C++ it is not possible nor useful to postpone assigning the name of the variable at runtime. All that would do is make your code more complicated and your program slower.
You can use a map.
map<string, int> numbers;
numbers["count"] = 6;
cout << numbers["count"];
Beginning programmers ask this question regarding every language. There are a group of computer languages for which the answer to this question is "yes". These are dynamic, interactive languages, like BASIC, Lisp, Ruby, Python. But think about it: Variable names only exist in code, for the convenience of the programmer. It only makes sense to define a new variable while the program runs if there's a person to then subsequently type the name of the variable in new code. This is true for interactive language environment, and not true for compiled languages like C++ or Java. In C++, by the time the program runs, and the imaginary new variable would be created, there's no one around to type code that would use that new variable.
What you really want instead is the ability to associate a name with an object at runtime, so that code -- not people -- can use that name to find the object. As other people have already pointed out, the map feature of C++'s standard library gives you that ability.
You might want to look at C++ map.
No. C++ is statically typed, and this goes against that whole paradigm.
I have seen this type of functionality implemented before by storing variables in an stl map.
At least for the (vice versa) there is a possibility with the preprocessor statement stringify #. See this answer on how to convert a C++ variable name into an string.
well i guess u cannot make dynamics variables but u can use some function to write a new variable and its value in any external text file and access its value from that file where ever it is needed (u can also remove the dynamic variable by removing it from the text file.)
theory: variables are places in memory where we store data, identified by a name, we can store data in a text file if processor doesnot allow us to store it in registers, and we can access its value by searching its identity (name of variable) int the text file, our data will be next to it.
its just an idea, it should work but i guess it will be not very simple and ur program will have to pay in terms of speed.