Allow me to post my code first:
void Fun(short &s){}
void FunCon(const short &s){}
int main()
{
int iTest = 20;//note: iTest is int but parameter of Fun is "short &"
Fun(iTest);//error, I know there is a temp variable(typecast)
FunCon(iTest);//ok
return 0;
}
I know Fun(iTest);
will generate a new temp variable(typecast), but I wonder if the temp variable is a constant?
If No: Why can't I pass the temp variable to short &
If Yes: I have another code like this:
class MyObject{
public :
void F(){}
};
MyObject MOCreator(){
return MyObject();
}
int main()
{
MOCreator().F();//OK
return 0;
}
If temp variable that returned by MOCreator()
is constant, why the temp variable can call non-const member function?
My questions are:
1) What is the difference between temporary variable and constant in C++?
2) There is a sentence in Thinking in C++(page 507). Is the sentence right? and why?:
Temporary objects are automatically const
I was asked for a simple question by someone, and I encounter more questions on my way to solving the question. I do know they may be a very common questions,and I am searching for a long time on net. I also got many different answers. But I'm more confused about it now.
Thanks in advance.