Is a union in C++ actually a class?

后端 未结 1 1456
不知归路
不知归路 2020-12-31 02:03

A junior developer asked me if it was possible to overload assignment operators for a union with POD arguments such that the corresponding data type within the union would g

相关标签:
1条回答
  • 2020-12-31 02:11

    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.

    0 讨论(0)
提交回复
热议问题