I wrote a program today which was giving me a real headache when it didn't work how I expected it to.
So I've written a short example which (almost)* reproduces the problem.
I hope this is fairly self-explanatory in what it is supposed to do.
#include <iostream>
class A
{
public:
enum class defaults
{
DEFAULT_A
};
A(defaults default_val)
{
if(default_val == defaults::DEFAULT_A)
{
A("hello world");
}
}
A(std::string str_)
{
str = str_;
flag = true;
}
std::string getStr()
{
return str;
}
bool getFlag()
{
return flag;
}
private:
bool flag;
std::string str;
};
int main()
{
A a(A::defaults::DEFAULT_A);
std::cout << a.getStr() << std::endl;
std::cout << a.getStr().size() << std::endl;
if(a.getFlag())
{
std::cout << "true" << std::endl;
}
else
{
std::cout << "false" << std::endl;
}
}
My compile and run code: g++ --std=c++14 main.cpp && ./a.out
Compiling on/with gcc version 5.2.1 20151010 (Ubuntu 5.2.1-22ubuntu2)
Output: [with line numbers]
1:
2: 0
3: true
(That first line is a blank line.)
*The only thing which is different from this example and the code I was working on today is that the flag in the code I wrote earlier was false not true, but this is still NOT what I expected it to be - I expected it to be true. And also, the string wasn't blank, but it did contain "nonsense values" - at least not what I expected it to contain.
What have I done wrong here? My guess is it's something really obvious, but I just can't spot it. (Perhaps I've been working on the same problem for too long now?)
Edit:
Can I do this to correct the problem?
A(defaults default_val)
{
if(default_val == defaults::DEFAULT_A)
{
*this = A("hello world");
}
}