C++ operators, to be a member or not!

  • SpooF
  • ٩๏̯͡๏۶
  • Bronze Member
  • User avatar
  • Posts: 3423
  • Loc: Richland, WA

Post 3+ Months Ago

Okay, so I'm writing a class called bigint for my computer science class and I can make my operators member operators or I can make them non member operators. However, I'm really clueless to the advantage/disadvantage of either of them. Im going into tomorrow to ask my Prof but just thought I would through this out there for anyone else to ponder. I'll report back with what my prof says as well.
  • spork
  • Brewmaster
  • Silver Member
  • spork
  • Posts: 6296
  • Loc: Seattle, WA

Post 3+ Months Ago

It depends on the particular operator you're overloading. Some operators such as stream insertion/extraction (<<, >>) cannot be member operators because the leftmost operand belongs to the stream object, not your class.

For example, if you want to overload the stream insertion operator for your class so that you can write your class to a stream (cout, for example), you'd want to be able to use it like this:

Code: [ Select ]
MyClass obj;
cout << "Printing my object: " << obj << "...done\n";
  1. MyClass obj;
  2. cout << "Printing my object: " << obj << "...done\n";

Let's try implementing the "<<" operator as a member function. Our function should accept an output stream as an argument, right? Our function would end up looking something like this:

Code: [ Select ]
ostream& operator<<( ostream& os );

So far, so good. But based on this semantic, look what happens when we go to use the operator:

Code: [ Select ]
MyClass obj;
obj << cout;
  1. MyClass obj;
  2. obj << cout;

That's obviously not correct since the stream object must be the left operand in the statement. Crap. In order to do that, we'd have to modify the operator "<<" for the output stream class instead of our own class.

Since we cannot modify C++ library classes, we must use a non-member function to ensure the operands are in the correct order:

Code: [ Select ]
ostream& operator<<( ostream& os, const MyClass& o );

This will allow us to correctly use the output stream with our class:

Code: [ Select ]
MyClass obj;
cout << obj;
  1. MyClass obj;
  2. cout << obj;

Most operators can and should be implemented as members whenever possible. There are just a few times when you must use non-member functions.

Post Information

  • Total Posts in this topic: 2 posts
  • Users browsing this forum: No registered users and 75 guests
  • You cannot post new topics in this forum
  • You cannot reply to topics in this forum
  • You cannot edit your posts in this forum
  • You cannot delete your posts in this forum
  • You cannot post attachments in this forum

© 1998-2017. Ozzu® is a registered trademark of Unmelted, LLC.