Belin
Belin

Reputation: 33

I have difficulty initialising enum in constructor in C++

I am using enum to initialise the different genders. So my problem is that a do not know what exactly to put in this constructor.

class CPerson {
private:
    char* Name;
    enum class Gender { Male = 0, Female = 1 };
    Gender sex;
public:
CPerson(const char* szName, Gender s)
        :Name{ nullptr }
    {
        Name = new char[strlen(szName) + 1];
        strcpy(Name, szName);
        sex =s ;
    }

void main(){
Cperson("Simon",?????);
}

Upvotes: 0

Views: 117

Answers (2)

Mark Ransom
Mark Ransom

Reputation: 308206

Since your enum is part of the class, you need to reference the class name to get access.

And since you've made Gender a class instead of a simple enum, you'll have to reference it too.

CPerson("Simon", CPerson::Gender::Male);

Plus as noted in the comments, you need to make the enum public.

Upvotes: 2

allanbbs
allanbbs

Reputation: 48

To instantiate your Enum Class you should go for something like :

CPerson("Simon", CPerson::Male);

As a side note, if your Enum members will follow the order 0,1,2...., you don't need to explicitly type so :

enum class Gender { Male,Female};

should be enough.

Upvotes: 0

Related Questions