Advertisement Jump to content


This topic is now archived and is closed to further replies.

Wormy Hellcar

[C++] unnamed anonymous union initialization problem

This topic is 5434 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hello. I''m using VS.NET 2k3 and I''m running into some problems initializing an unnamed union that contains references. The simplified code is
struct MyStruct
	union { int& i; int& j; };

	MyStruct(int &a) : i(a) 
	{ }
It gives me the error
error C2758: ''MyStruct::__unnamed::j'' : must be initialized in constructor base/member initializer list 
This seems a little silly as it shouldn''t have to initialize the memory twice, and doing so infact gives me a warning. Giving it a variable name and using that in the initializer list works, but that defeats the whole purpose of using it. Does anyone have any suggestions on how to get this to work or is it not supported by C++ at all?

Share this post

Link to post
Share on other sites
A union with members of reference type is illegal C++. (From Section 9.5, paragraph 1 in the C++ Standard: "If a union contains a static data member, or a member of reference type, the program is ill-formed.")

Share this post

Link to post
Share on other sites
G++ gives a similar error, so it isn''t the compilers fault.

I think the problem here is that references ALWAYS have to point to a valid object. What happened if you added a non reference type to the union. If you were ever to use it, then the reference would be invalid. It just doesn''t make sense to put a reference in a union. Don''t do it.

Share this post

Link to post
Share on other sites

  • Advertisement

Important Information

By using, you agree to our community Guidelines, Terms of Use, and Privacy Policy. is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!