Reputation: 99
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?
Upvotes: 5
Views: 19231
Reputation: 3358
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) {};
Upvotes: 10