c++castingconstantspass-by-referencepass-by-const-reference

What is the difference between temporary variable and constant in C++?


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.


Solution

  • I wonder if the temp variable is a constant?

    No, it's just a temporary variable which will be destroyed at the end of the full expression in which it was created.

    Why can't I pass the temp variable to short &

    A temporary can't be bound for a non-const reference. But it could be bound for const reference, and the lifetime of the temporary will be extended to match the lifetime of the reference. That's why FunCon(iTest); is fine.

    why the temp variable can call non-const member function?

    It's fine. The only special thing is the temporary variable will be destroyed at the end of the full expression.

    Is the sentence right? and why?
    Temporary objects are automatically const

    No. Unless you explicitly declare it to be const.