Dear Jonathan, Dietmar or anybody else,
I'm doing some exercises and I tried enum class as a type embedded in a
class scope which is the ancestor of a two-level hierarchy.
My aim was to use bool as underlying type, and this was accepted by the
compiler...
Nevertheless, transmitting a value for a member variable of the enum
class type through the chain of constructors, I found it finally changed
without any evident reason, even if it had the value I expected during
its whole history.
There should be something wrong in my code I can't find, and your help
would be highly appreciated.
Here follows the code: it is, I hope, short enough to be easily
debugged. As you can see main declares an object of class Third and
thereafter ask for the value returned by its giveMe public method.
The Third's ctor sends a value up to the constructor of the ancestor
class, which uses it to initialize a member variable, which, in my
opinion should be inherited by Third.
But the value written is the opposite I expected...Why?
///////// code
# include <iostream>
using namespace std;
class First
{public:
enum class Alpha : bool {A=false, B=true};
protected:
Alpha alpha;
First(Alpha b)
{alpha = b;
clog << "First's ctor set " << static_cast<bool>(alpha) << endl;}
};
class Second : First
{
protected:
Alpha First :: alpha; // to reset from private
public:
First :: Alpha; // to reset Alpha type as public
Second(Alpha b) : First(b)
{
clog << "Second's ctor handles " << static_cast<bool>(b) << endl;
}
};
class Third : Second
{
public:
Alpha giveMe() // Alpha is recognized without scope resolution (by
inheritance...)
{// alpha should be inherithed from First, through Second...or NOT?
clog << "Second :: giveMe returns " << static_cast<bool>(alpha) <<
endl;
return alpha;}
Third(Alpha b = Alpha :: A) : Second(b)
{
clog << "Third's ctor handles " << static_cast<bool>(b) << endl;
}
};
int main( )
{
Third aaa;
clog << "in main one finds " << static_cast<bool>(aaa.giveMe()) << '\n';
}
////////// end code