I observed peculiar behavior in g++4.6.3. When creating a temporary by calling class constructor File(arg) the compiler chooses to ignore the existence of arg and parse the expression as File arg;
- Why is the member name ignored?
- What does the standard say?
- How to avoid it? (Without using new
{}syntax) - Is there a related compiler warning? (I could use an arbitrary string arg and it would still work quietly)
Code:
#include <iostream>
class File {
public:
explicit File(int val) : m_val(val) { std::cout<<"As desired"<< std::endl; }
File() : m_val(10) { std::cout<< "???"<< std::endl;}
private:
int m_val;
};
class Test {
public:
void RunTest1() { File(m_test_val); }
void RunTest2() { File(this->m_test_val); }
void RunTest3() { File(fhddfkjdh); std::cout<< "Oops undetected typo"<< std::endl; }
private:
int m_test_val;
};
int main()
{
Test t;
t.RunTest1();
t.RunTest2();
t.RunTest3();
return 0;
}
Output:
$ ???
$ As desired
$ Oops undetected typo
The compiler treats the line:
as
so you’re actually creating a named object called
m_test_valusing the default constructor. Same goes forFile(fhddfkjdh).The solution is
File(this->m_test_val)– this tells the compiler that you want to use the member to create create a named object. Another would be to name the object –File x(m_test_val).