I recently tested the simple following program on an online compiler. See live demo here. It compiles fine & gives the expected output but when I tested it on Dev C++ IDE it fails during the compilation.
Here is my program:
#include <iostream>
class Test
{
int s=9;
public:
int get_s()
{
return s;
}
};
int main()
{
Test s;
Test& t{s}; // error in C++11 but not in C++14 why???
std::cout<<t.get_s();
}
It gives me following error:
[Error] invalid initialization of non-const reference of type 'Test&' from an rvalue of type '<brace-enclosed initializer list>'
I also tried it on code blocks 13.12 IDE & it gives me the same error as Dev C++ gives.
Is this a new C++14 feature? Why is it not working in a C++11 compiler?
It works on C++14 and also works on C++11. You're very likely using an out-of-date compiler.
There's a fixed bug (https://gcc.gnu.org/bugzilla/show_bug.cgi?id=50025) for your exact issue (cfr. DR 1288)
C++0x initialization syntax doesn't work for class members of reference type
Quoting from Jonathan Wakely
The original C++11 rules required a temporary to be created there and the reference member binds to that temporary.
Sources: Defect Report 1288