3

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?

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
markzzz
  • 47,390
  • 120
  • 299
  • 507
  • 2
    Probably something like the compiler understand the second code as a forward declaration of a function – Xatyrian Nov 21 '19 at 09:10
  • 1
    `myNamespace::MyClass mMyClass1(myNamespace::MyType::ASD2);` is read as a *function* declaration – Caleth Nov 21 '19 at 09:10
  • 2
    Ah, looking at your code sample, the problem is that you're trying to declare a member variable with initializer in a way that you can't do at class scope. Try `int x(3);` - that's also not allowed. Nothing to do with namespaces or `enum`s. At class scope the compiler thinks that's supposed to be a function, not an initialization. – Max Langhof Nov 21 '19 at 09:11
  • 1
    Use the unified initialization syntax instead `myNamespace::MyClass mMyClass1{myNamespace::MyType::ASD2};` – Albjenow Nov 21 '19 at 09:11
  • Better: use left-to-right initialisation (at least at non-class scopes): `auto mMyClass1 = myNamespace::MyClass{myNamespace::MyType::ASD2};` – underscore_d Nov 21 '19 at 09:12
  • Didn't fail with g++ – Tony Tannous Nov 21 '19 at 09:12

2 Answers2

5

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

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

};
Jarod42
  • 203,559
  • 14
  • 181
  • 302
3

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

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335