After researching a bit I don't understand the output (source code below):
42
42
45
I'm fine with the second, but why I get this output? It's coming from fooling around with avoiding global constants and variables in a bigger project. Could someone please explain it to me?
#include <iostream>
class Const
{
public:
Const() = delete;
static auto foo(int val = 42) -> int&;
};
auto Const::foo(int val) -> int&
{
static int sval = val;
return sval;
}
int main()
{
std::cout << Const::foo() << std::endl;
Const::foo(24);
std::cout << Const::foo() << std::endl;
Const::foo() = 45;
std::cout << Const::foo() << std::endl;
return 0;
}
42all three times. I suppose the initialization is only done once, sofoo(24)and subsequent calls offoo()don't change the value, but because it returns a referenceConst::foo() = 45does change it?45before 3rd print.Const::foo() = 45;changes the value ofsval. I'm surprised thatConst::foo(24)(and, similarly, the final call toConst::foo()) don't.Const::foo(). if there was anothersval = val;beforereturn,Const::foo(24)could change the result, but otherwise it's only changeable via the returned reference and parameter is ignored.