C++ brain teaser
- by mxp
I recently refactored code like this (MyClass to MyClassR).
class SomeMember
{
long m_value;
public:
SomeMember() : m_value(0) {}
SomeMember(int a) : m_value(a) {}
SomeMember(int a, int b) : m_value(a+b) {}
};
class MyClass
{
SomeMember m_first, m_second, m_third;
public:
MyClass(const bool isUp, const int x, const int y)
{
if (isUp)
{
m_first = SomeMember(x);
m_second = SomeMember(y);
m_third = SomeMember(x, y);
}
else
{
m_first = SomeMember(y);
m_second = SomeMember(x);
m_third = SomeMember(y, x);
}
}
};
class MyClassR
{
SomeMember m_first, m_second, m_third;
public:
MyClassR(const bool isUp, const int x, const int y)
: m_first(isUp ? x : y)
, m_second(isUp ? y : x)
, m_third(isUp ? x, y : y, x)
{
}
};
What is the error,
why does it compile (at least VC6 with warning level 3 doesn't complain) and
what is the right way of doing it?
I (assume) I already have all these answers but I think it's and interesting problem to share.