When to use friend, and union?

Started by
12 comments, last by DevLiquidKnight 20 years, 1 month ago
The C++ faq lite section on friendship

Edit: Also consider looking at these resources, here, here, and here.

[edited by - pinacolada on March 7, 2004 6:19:54 PM]
Advertisement
quote:Original post by me22
Can you use that to get the bit representation of a float in an unsigned long as an integer without the indirection of a *( (unsigned long*)&my_float_val )?

Yup. For D3D it''s one of the handier places to use a union.
quote:Original post by DevLiquidKnight
I was wondering when do you use the "friend" statement or whatever in C++. Also when is it best to use a union?

My friend said unions were faster then a typedef struct because he said they are in the same location in memory, which makes them not use as much memory or something. Im not sure if this is right. Im also not sure when to use it if anyone can give me an idea of when id use it?

I also was wondering when you use a friend data type or object type and what type of things it will allow me to do that I can not do normally?


Friend is a cheating way around some OO rules. Use sparingly - lots of posters seem to have posted good links about this already. Particularly useful for operator overloading.

Union - useful for creating something equivalent to a visual basic variant - and COM uses the mechanism to do something like that. Like friend though, it''s use should be sparingly. Optimisation of this sort should really only be bothered with if a. You are a flash git looking for trouble or b. you are working with very limited memory. Nowadays for PC programmers (and in the gaming domain) unless your union is doing something very very generic (buffer for network comms perhaps?) you are probably a.
Anything posted is personal opinion which does not in anyway reflect or represent my employer. Any code and opinion is expressed “as is” and used at your own risk – it does not constitute a legal relationship of any kind.
I''d use unions when I wanted to view the same data in different ways (the rgba color is a perfect example of this).

An example of friend usage would be making an overloaded operator to multiply a vector3 object by a matrix3x3 object. At least I think that''s a good example - never actually used it in real life!

This topic is closed to new replies.

Advertisement