First of all, you don’t seem to need a union
. CNPJ and CPF are descriptive data and should be strings and not numbers, which already kills the need for union.
union
with two fields of the same type does not make much sense. Just to use a different name? I see no advantage in C. C++ has better mechanisms. Anyway, it’s not even what you need.
One union
without tag, one of the criticisms of the C mechanism, is not good for much, so C++ has better structures than union
in the library if necessary. But of course you can always use a tag own extra on own struct
to know what to take in each case, only has the problem that this is an abstraction leak.
union
was created to solve issues of lower level, it seems to me that is mixing different levels of abstraction.
For all this I prefer not to even try to solve your specific problem and solve the real problem that is wider. Solving the question problem is a palliative that will still keep wrong in the general concept.
If you do it right, you’ll only have room for string of the CNPJ which is larger, and of course, a tag extra that seems to me fundamental anyway in this register. This is a case that put the inline string in struct
seems appropriate.
I strongly question whether I should use a struct
for a Cliente
. But okay, it’s just a start, and technically it will change little use to a class, it will just give a more appropriate semantics, and it will indicate more that this should probably be a type by reference. But I won’t insist on that because right now it’s too simple a code.
That would be a better solution:
struct Cliente {
string nome, email, tipo, documento;
};
I put in the Github for future reference.
There are other issues that probably indicate that the code is mixing C with C++ and is the last century’s way of doing in C++.
Which makes you conclude that
Cliente::documento
is a data member and not a definition ofunion
?– Mário Feroldi
Hi Mario! My question is basically in this. I did a validation before but presented the same error: cli->document.Cpf or cli->document->Cpf or cli->document::Cpf gave the same error. I started to see this language this semester, and I still have some doubts (this particular one I did not find examples anywhere).
– Luis Felipe Mello