0

I'm new to C++ and read about curly bracket initializer which is available in C++ 11. I try to create a simple union which looks like this

union UExample {

  UExample(const uint12_t value = 0) : raw{value} {}

  uint12_t raw;

};

When I try to compile the file I get this error

./stack.h:18:57: error: expected member name or ';' after declaration specifiers
  UBankedAddress(const uint12_t value = 0) : raw{value} {}
                                                        ^
./stack.h:18:49: error: expected '('
  UBankedAddress(const uint12_t value = 0) : raw{value} {}
                                                ^
./stack.h:18:55: error: expected ';' after expression
  UBankedAddress(const uint12_t value = 0) : raw{value} {}

Dose anyone has an idea to solve this?

$ g++ --version
Configured with: --prefix=/Library/Developer/CommandLineTools/usr --with-gxx-include-dir=/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/c++/4.2.1
Apple clang version 12.0.0 (clang-1200.0.32.29)
Target: x86_64-apple-darwin20.3.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin
Markus
  • 1,909
  • 4
  • 26
  • 54
  • You declared a `union` but it looks like you are trying to give it a `class` constructor? – Cory Kramer Apr 26 '21 at 18:39
  • Compiles for me - live - https://godbolt.org/z/rd66K5n9f Looks like it could be an error on the previous (not shown) line. – Richard Critten Apr 26 '21 at 18:43
  • 2
    Your error message does not match the code provided. Please give use a [mre] and the matching error. – NathanOliver Apr 26 '21 at 18:44
  • 2
    @NathanOliver I stand corrected: `A union can have member functions (including constructors and destructors), but not virtual functions.` I haven't used unions in decades so was out of practice. (Personally, I don't like them.) – Casey Apr 26 '21 at 18:46

1 Answers1

2

I found a solution for this problem. It relates to the g++ compiler on MacOS. clang++ should be used instead.

Before (not working):

g++ stack.cpp -o stack

After (working):

clang++ -std=c++11 -stdlib=libc++ stack.cpp -o stack
Markus
  • 1,909
  • 4
  • 26
  • 54
  • 2
    What happens if you pass `-std=c++11` to `g++` ? – Richard Critten Apr 26 '21 at 18:53
  • Then probably your installation of `g++` is old and is defaulting to a pre C++11 standard. See also https://stackoverflow.com/questions/44734397/which-c-standard-is-the-default-when-compiling-with-g – Richard Critten Apr 26 '21 at 19:20
  • 1
    Your code is valid C++11, but not valid C++98. That's the issue. You were using a very old C++ standard. – Drew Dormann Apr 26 '21 at 19:32
  • That is interesting. I have a new MacBook from late 2020. Did not think that Apple delivers with such old versions preinstalled :D – Markus Apr 26 '21 at 20:08