Jump to content
  • Advertisement
Sign in to follow this  

friends and operator overloading in C++

This topic is 5007 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

This is a pretty rudimentary C++ question: If you're declaring a standard vector class for example and you want to overload the + operator, what's the difference between (1) declaring it as a public member function as so: Class vector { public: vector operator+(const vector& v) { // add and return a new vector }; }; (2) declaring it as a seperate function outside the class such as: vector operator+(const vector& v1, const vector&v2) { // add and return }; and finally (3) declaring it as a friend function within the class itself: Class vector { public: friend vector operator+(const vector& v1, const vector&v2) { // add and return }; }; Assuming your member variables (i.e. x,y,z) are delcared public are these not functionally equivalent with the first one being the simplest and the second one being perhaps the most readable?

Share this post

Link to post
Share on other sites
Case 1 has some interesting properties when you try to define something like:

vector operator*(const int) {blah}

In this case, you can only do:

new_vector = old_vector * 2;

You can't do:

new_vector = 2 * old_vector;

which is technically : 2.operator*(const vector&)

However, in your example of addition, this isn't a problem.

The difference between 2 and 3 is pretty much what you highlighted - solution 3 works if the class data are private, and 2 won't. You may want to search the site a bit to find some discussions on why class data should / shouldn't be private (although most people just use a POD for vector classes).


Share this post

Link to post
Share on other sites
Additionally, for non-member operators, implicit conversions will occur on the left-hand side parameter. For example, if you do

struct vector
vector operator+(const vector&);

vector operator-(const vector&, const vector&);

2+v will not work.
v+2 will work.
2-v will work.
v-2 will work.

Share this post

Link to post
Share on other sites
Sign in to follow this  

  • Advertisement

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!