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;
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.
Christophe
source share