Is a union in C++ actually a class?

好久不见. 提交于 2019-11-30 08:12:22

Is a union in C++ actually a class?

Yes. In C++ a union is a class: a special kind of class.

C++11: 9 Classes (p5):

A union is a class defined with the class-key union; it holds only one data member at a time


Is it actually common to overload constructors etc for unions in this way?

A union is a special class with some restrictions:

9.5 Unions (p2):

A union can have member functions (including constructors and destructors), but not virtual (10.3) functions. A union shall not have base classes. A union shall not be used as a base class.

11 Member access control (p3):

Members of a class defined with the keyword class are private by default. Members of a class defined with the keywords struct or unionare public by default.

So, you can overload constructors, destructors and operators similar to as you can do in a class.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!