Jump to content

C++ Global Function/ Class Function


aimforthehead

Recommended Posts

So I'm studying for my final and I'm trying to understand what are some of the tradeoffs between creating a class function or a global function (consider operator functions I suppose, my professor mentioned that some operator functions MUST be global, and I didn't really understand). If anyone could help me understand this I would be grateful, thanks!

Link to comment
Share on other sites

Suppose you're writing classes to represent vectors as defined mathematicians. (Note: *not* the ugly things in the C++ standard library.)

 

For example, the product of a vector and a scalar is a vector. That's easy: Just overload operator* in your Vector class. However, the product of a scalar and a vector also is a vector. Now you've got a problem. The argument to operator* as a member function is a multiplier, not a multiplicand. You have but no choice but to make this overload a friend function rather than a member function.

Link to comment
Share on other sites

  • 3 weeks later...

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.