Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why calling constructor with enum argument failed while using it as class field?

I wrote a simple class constructor with one argument of enum type.

enum Kind {
    One,
    Two
};
class KindClass {
private:
    Kind fKind;

public:
    explicit KindClass(Kind kind) : fKind(kind) {}
};

Then make a global constant of it and it work.

static const KindClass globalKindClass(One);

But when making const field of it compile failed with error : "error: ‘One’ is not a type"

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

class UserClass {
private:
    static const KindClass kindClass(One);
};

What’s the problem ? And how to solve it ?

https://godbolt.org/z/Yn45objnd

>Solution :

Use curly braces and constexpr to fix it:

class KindClass {
private:
    Kind fKind;

public:
    explicit constexpr KindClass(Kind kind) : fKind(kind) {}
};

class UserClass {
private:
    static constexpr KindClass kindClass{One};
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading