C++ Returning a Reference
- by Devil Jin
Consider the following code where I am returning double& and a string&. The thing works fine in the case of a double but not in the case of a string. Why is this difference in the behavior?
In both the cases compiler does not even throws the Warning: returning address of local variable or temporary as I am returning a reference.
#include <iostream>
#include <string>
using namespace std;
double &getDouble(){
double h = 46.5;
double &hours = h;
return hours;
}
string &getString(){
string str = "Devil Jin";
string &refStr = str;
return refStr;
}
int main(){
double d = getDouble();
cout << "Double = " << d << endl;
string str = getString();
cout << "String = " << str.c_str() << endl;
return 0;
}
Output:
$ ./a.exe
Double = 46.5
String =