Overlay subclass union ontop superclass

I am wondering if it is possible to add members to a C ++ union in a subclass.

class A { ... union { int a; int b; }; }; class B : public A { ... int c; //<- Can this use the same storage as the union? }; 

A more specific example would be the idea of ​​joining with tags, where you would like to have a subclass that adds a type to the union.

+7
c ++ inheritance unions
source share
2 answers

You said,

I am wondering if it is possible to add members to a C ++ union in a subclass.

The language does not allow to expand union . Adding members to union not possible.

Worse, unlike class es and struct s, which can be extended by subclassing (structs), union cannot have base classes. They also cannot be used as base classes.

+3
source share

Firstly, according to the standard, 9.5 points 1 in a union, no more than one of the non-static data members can be active at any time, that is, the value of no more than one of the non-static data elements can be stored in the union at any time.

In your case, since c is an int, there is no benefit in adding a member to the original union. Just repeat one of the existing ints. Or anticipate all possible tag members from the very beginning in the union.

However, you could define c as a link and assign it the address of a union member, bearing in mind that all non-static data members of the combined object have the same address (Β§ 9.5 / 1):

 class B : public A { int& c; //<- Can this use the same storage as the union? public: B() : c(A::a) {} void test() { a = 10; std::cout << "a=" << a << "; "; std::cout << "c=" << c << "; "; c = 20; std::cout << "a=" << a << "; "; std::cout << "c=" << c << "; "; } }; 

The contract of a member of an active trademark remains, of course, in force.

By the way, why is it impossible to divide the same union between the base class and the derived class? Because the standard says:

  • Unless indicated in a derived class, members of the base class are also considered members of the derived class (Β§ 10 clause 2)

  • Non-stationary data members (non-union) of a class with the same access control are allocated so that later members have higher addresses in the class object. (Β§ 9.2 paragraph 13)

  • Thus, members of a derived class have a higher address than members of a base class.

  • But all non-static data members of the combined object have the same address (Β§ 9.5 / 1)

  • Therefore, it is not possible for members from a derived class to belong to a union in the base class. Q.E.D.

+2
source share

All Articles