markzzz
markzzz

Reputation: 48065

Why can't access to enum here?

Here's my code/namespace:

namespace myNamespace { 

enum MyType {
    ASD1,
    ASD2,
    ASD3
};

struct MyClass {
    MyType mMyType;

    MyClass(MyType myType = MyType::ASD1) : mMyType(myType) {

    }
};

}

Now if I try, within another struct, this code:

struct X
{
    myNamespace::MyClass *pMyClass1 = new myNamespace::MyClass(myNamespace::MyType::ASD2);
};

it works perfectly, but if I try this:

struct X
{
    myNamespace::MyClass mMyClass1(myNamespace::MyType::ASD2);
};

it says 'myNamespace::MyType::ASD2' is not a type.

Since its all declared before, why this?

Upvotes: 3

Views: 91

Answers (2)

Vlad from Moscow
Vlad from Moscow

Reputation: 311186

You have to use the brace-or-equal-initializer. You may not use an initializer in parentheses without the sign =.

From the C++ Standard (12.2 Class members)

member-declarator:
    declarator virt-specifier-seqopt pure-specifieropt
    declarator brace-or-equal-initializeropt
    identifieropt attribute-specifier-seqopt : constant-expression

For example

myNamespace::MyClass mMyClass1 { myNamespace::MyType::ASD2 };

or

myNamespace::MyClass mMyClass1 = myNamespace::MyType::ASD2;

The last initialization is valid because the constructor is a conversion constructor

Upvotes: 3

Jarod42
Jarod42

Reputation: 218333

Inside class, you might use {..} or = .. syntax, not (..):

struct Test {
    myNamespace::MyClass mMyClass1{myNamespace::MyType::ASD2};
    // myNamespace::MyClass mMyClass1 = myNamespace::MyClass{myNamespace::MyType::ASD2};

};

Upvotes: 5

Related Questions