Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialising enum via constructors

I have an enum as a public memebr of a class as follows"

class myClass
{
    public:
        enum myEnum
        {
            myEnum1,
            myEnum2
        };
};

I also declare a constructors, a public parameterized one as follows:

myClass(myEnum);

I define the same outside the classs definition as follows:

myClass :: myClass(myEnum E)
{
}

How do I initialise myEnum with default arguments?

I tried:

i)

myClass :: myClass(myEnum E = 0); //to int error

ii)

myClass :: myClass(myEnum E = {0}); //some error

iii)

myClass :: myClass(myEnum E = {0, 1}); //some error

One thing I still don't seem to understand.

How do I pass enum values to the constructor. I still get an error. And, I need to do it this way:

derived(arg1, arg2, arg3, enumHere, arg4, arg5); //call

Function definition:

derived(int a, int b, int c, enumHere, int 4, int 5) : base(a, b);

Where am I supposed to initialise the enum, as one of the answers belowe do it?

like image 724
Kuttu V Avatar asked Sep 23 '12 10:09

Kuttu V


1 Answers

Seems like you've mistaken type declaration with field. In your class myEnum is declaration of type, and class itself does not hold any field of that type.

Try this:

class myClass
{
    public:
        enum myEnum
        {
            myEnum1,
            myEnum2
        } enumField;
};

Then, your constructor should use member initialization:

myClass::myClass() : enumField(myEnum1) {};

If you want parametrized constructor:

myClass::myClass(myEnum e) : enumField(e) {};

If you want parametrized constructor with default argument:

myClass(myEnum e = myEnum1) : enumField(e) {};

If you want to use aforementioned constructor in derived class:

myDerived(myEnum e) : myClass(e) {};
like image 89
Bartosz Avatar answered Sep 19 '22 19:09

Bartosz