Why the following code doesn't compile in MSVC and does in g++?

Viewed 153

I am trying to use the constructor initializer list with the colon in main, but it doesn't compile in Microsoft Visual Studio 2019 (Error: identifier "name" is undefined & expected a '}') , but it compiles and prints the output without any problem in g++ (version 10.2.0) in Linux.

I have also tried different versions of MSVC, like C++14, C++17 with no result. I know all the possible initializations of C++11 but I must use the one with the colon( : ).

Is there a way to do it in MSVC?

Thanks in advance!

#include <string>
#include <iostream>

class Spell {
private:
    std::string name;
    std::string action;

public:
    Spell(std::string name, std::string action) : name(name), action(action) {}

    void print() {
        std::cout << name;
    }
};

int main() {

    Spell* spell = new Spell{ name : "test", action : "lol" }; //HERE
    spell->print();
}
1 Answers

That syntax is a non-standard GNU extension, and thus is not (and likely never will be) supported by any version of Microsoft Visual C++.

Designated initializers were standardized in C++20, but the syntax is different and they are only available for aggregate initialization. The equivalent standard designated initializer syntax would be Spell{.name = "test", .action = "lol"}. That won't work in this case either though, since Spell is not an aggregate because it has private data members and a user-defined constructor.

Related