PDA

View Full Version : friends in C++...




Sean7512
Mar 1, 2006, 07:52 AM
Yesterday in my C++ class, we were talking about overloading operators so we can use them with our own classes. So our teacher says "Now, what is a friend?....Well, according to C++, a friend is someone who has access to your private parts!" :D I thought this was hilarious, what do you guys think?

I'm sure everyone will understand the joke.



cube
Mar 1, 2006, 10:05 AM
Friends don't let friends program in C++.

ChrisBrightwell
Mar 1, 2006, 10:12 AM
Yesterday in my C++ class, we were talking about overloading operators [...] what do you guys think?I think they need to quit teaching how to overload operators. ;)

jeremy.king
Mar 1, 2006, 12:26 PM
I thought they were called friends with benefits :confused: :eek:

bousozoku
Mar 1, 2006, 01:42 PM
I think they need to quit teaching how to overload operators. ;)

It's certainly ugly and they were considering adding it to Java.

Friends is an interesting idea and I've had to use it on occasion but I think a lot of people use it to avoid designing something properly.

You have to be careful in C++. It lets you do your worst and compiles it usually. ;)

zimv20
Mar 1, 2006, 01:54 PM
I think they need to quit teaching how to overload operators. ;)
what wrong with operator overloading? operator<< is great for testing and debugging.

netytan
Mar 1, 2006, 02:20 PM
what wrong with operator overloading? operator<< is great for testing and debugging.

I don't use C++, it's more than a little too ugly for me to want to be `that' close a friend with it ;).

Operator overloading isn't inherently bad but when every tom dick or jane overload every operator for every single class like they do things become very hard to follow very fast.

The sad thing is that C++ programmers think it's oh so powerful but in reality it's next to useless; it serves no practical use and it's a hopeless way of developing an abstraction.

If you get wet for operator overloading that way then you should look at macros in Lisp :D.

Take care,

Mark.

zimv20
Mar 1, 2006, 02:38 PM
The sad thing is that C++ programmers think it's oh so powerful but in reality it's next to useless; it serves no practical use and it's a hopeless way of developing an abstraction.

****read* thread = new ****read("http://forums.macrumors.com/showthread.php?p=2190373");

BBUser* user1 = new BBUser("zimv20", "#jdie$oLL4");

thread->login(user1);
thread->postNew("i disagree");

cout << thread << endl;

BBUser* user2 = new BBUser("netytan");

user1->addToFriends(user2);

cout << user1 << user2 << endl;

in my years of coding C++ professionally, this is an example of how i might write a unit test file. i'd overload << in order to facilitate testing.

and since i was a server tier guy, i'd write a command-line program to test all the CORBA interfaces. operator<< was extremely useful in that, too.

so i disagree that overloading is useless, and i must admit i don't know what you mean about using overloading to "develop an abstraction".

and i'll never agree that a language should be dumbed down to try to avoid programmer abuse. that's what coding standards and lead developers are for.

notjustjay
Mar 1, 2006, 02:56 PM
a friend is someone who has access to your private parts!

I think technically it's access to your private members.

:)

therevolution
Mar 1, 2006, 03:09 PM
cout << user1 << user2 << endl;

In that situation, why can't you just write:

cout << user1.toString() << user2.toString() << endl;


Overloading << doesn't really have any advantages, save slightly more terse code (which isn't necessarily a good thing). If you prefer the style of your way, then okay, but style isn't a great reason to argue for a feature's usefulness.

zimv20
Mar 1, 2006, 03:51 PM
Overloading << doesn't really have any advantages, save slightly more terse code
i understand your point, but i believe it goes beyond the convenience of the shorthand (which i do find convenient).

one of the things i like about class-based languages is this idea of extensible data types. i like that C++ allows me to define a class which has access to +, ==, <<, et. al., just as an int does.

so it goes beyond practicality and towards ideology.

that said, of course operators should be overloaded only when it makes sense for an object of that class.

so far, the objections to overloading have been about confusing code* and programmer abuse. but i seem to be the only one who appreciates what a well-defined operator can add to the simplicity of the project. is this the case of the good outweighing the bad? frankly, i'm not used to programmers who want less from their tools.

* defining an operater really isn't all that difficult. yeah, it clutters up the class a little bit, but, c'mon, we're programmers and pattern matchers to boot. once you get used to seeing the class code, what's the worry? plus, my classes have always been quite easy to grok and support, as are the classes of those working for me. i see to that. and it makes the code using those objects more elegant, imnsho.

i'm a bit concerned by this "we can't understand it" crap. if one of my programmers complained to me that simple language constructs were too difficult to understand, well.... they'd get themselves reassigned pretty quickly. no room for such whinging on my projects.

netytan
Mar 1, 2006, 04:16 PM
...in my years of coding C++ professionally, this is an example of how i might write a unit test file. i'd overload << in order to facilitate testing.

and since i was a server tier guy, i'd write a command-line program to test all the CORBA interfaces. operator<< was extremely useful in that, too.

so i disagree that overloading is useless, and i must admit i don't know what you mean about using overloading to "develop an abstraction".

and i'll never agree that a language should be dumbed down to try to avoid programmer abuse. that's what coding standards and lead developers are for.

I have to say it; quasi-typical C++ programmer attitude with the language being dumbed down comment ;).

You should be aware that C++ was developed to make programming in C easier and more abstracted by moving up a tier.

Ultimately the misguided belief of most programmers that there language of choice is as good as it gets is what turns the learning curve upside down the dumbing down of the industry though this effect is in my honest opinion the reason you need "lead developers".

I'm not saying everyone should be a programmer, quite the contrary I have amazingly high standards and don't think 80-90% of programmers are good programmers (it's also known as being opinionated ;)).

Operator overloading is generally in my experience is most commonly used to build up a more abstract syntax for interaction between class instances. Using + to concatenate two strings together for instance is very common in a lot of languages that support overloading and I can say without doubt that this has been implemented for C++ somewhere :rolleyes:.

The problems come when you're trying to read code that looks like this:


#include "Place.h"

Place n = 2, d = 1;

printf("%s", a / b);


The problem should be very clear. If the class overloads operators then how are you supposed to know what this does? At a glance you wouldn't have a clue, i'd be inclined to think division, and that's when the trouble starts.

This is done ALOT from what I've seen and heard, it's a very common annoyance :). Why is it so bad? Because operator oversloading isn't powerful enough to make a usable abstraction, instead take this code:

#import "Place.h"

Place *n, *d;

*n = [Place initWithI: 2];
*d = [Place initWithI: 1];

NSLog(@"%@", [place the:n over:d]);

Objective-C is hardly the most beautiful language but it should be immediately more clear what the codes doing. This is only touching the iceburg of what can be done in some languages for instance recently I added the foreach loop to a language I was using for a project in 5 lines. This is a usable abstraction.

There very silly examples that would never be seen in the real world; in the real world things are worse! I think C++ users enjoy nothing more than overloading this and that just for the hell of it and the result isn't pretty :(.

I'm not trying to be offensive so please don't take it that way. I just find it amusing that the masses love such a deficinent language and featured abstraction :).

Take care,

Mark.

therevolution
Mar 1, 2006, 04:29 PM
i seem to be the only one who appreciates what a well-defined operator can add to the simplicity of the project.
Maybe you are. ;) I just don't see a compelling use for it that isn't a matter of style. And as anyone who has maintained someone else's code knows, beautiful code is in the eye of the beholder.

Personally, I don't mind being a little more verbose (as with 'cout << user.toString()' vs. 'cout << user') to remove a possible point of ambiguity - to me, that is what makes elegant code. I will admit that this particular example probably isn't the most compelling piece of evidence for my point of view - '<<' is pretty straightforward and obvious - but with different operators, that might not be the case.

netytan
Mar 1, 2006, 04:34 PM
so far, the objections to overloading have been about confusing code* and programmer abuse. but i seem to be the only one who appreciates what a well-defined operator can add to the simplicity of the project. is this the case of the good outweighing the bad? frankly, i'm not used to programmers who want less from their tools.

* defining an operater really isn't all that difficult. yeah, it clutters up the class a little bit, but, c'mon, we're programmers and pattern matchers to boot. once you get used to seeing the class code, what's the worry? plus, my classes have always been quite easy to grok and support, as are the classes of those working for me. i see to that. and it makes the code using those objects more elegant, imnsho.

i'm a bit concerned by this "we can't understand it" crap. if one of my programmers complained to me that simple language constructs were too difficult to understand, well.... they'd get themselves reassigned pretty quickly. no room for such whinging on my projects.

Lol, awesome :).

But it's not about misunderstanding, its about inelegance. It's about being able to read code from a large project without having to crawl though the definitions of each class to figure out wtf it's doing when you see x operator.

It's about not wasting valuable time that could be spent auditing producing less buggy code. On the occasions were you make the assumption that you KNOW what's going on... and you're wrong you can end up causing a lot of problems. Confusion is contagious.

I'm all for abstraction, I love it! It makes programs more beautiful to look at, easier to read, easy to debug, shorter. What I have a problem with is such a weak method for adding abstraction to programs being drool over by a whole culture who don't know any better.

Give me a good method for implementing abstraction and I'll give you code you wouldn't believe; give me operator overloading and i'll laugh and hand you my resignation it's just that simple. No need for reassignment :).

I will agree that they can make trivial code simpler on occasion.

Mark.

zimv20
Mar 1, 2006, 04:45 PM
I have to say it; quasi-typical C++ programmer attitude with the language being dumbed down comment ;).
:-)

i am arrogant. then again, most good programmers are.

C++ was developed to make programming in C easier and more abstracted by moving up a tier.
from what i've read, stroustrup never intended for C++ to replace C. C is reserved for its strength -- highly efficient, lower-level coding, while C++ was intended to add user-defined datatypes and provide for higher quality libraries (both OTS and custom). so i agree with the "more abstracted" bit.

Ultimately the misguided belief of most programmers that there language of choice is as good as it gets is what turns the learning curve upside down
i don't want to imply that i think C++ is the end-all and be-all of languages. it's not. it excels at my area of expertise, and that's server-tier OO services.

for GUI, i'd rather use something else. for 2-tier web development, i like php. languages are made for specific purposes, and no one language excels at them all.

what bristles me are people designating C++ a poor language for the wrong reasons. yes, it has its quirks and issues, but the availability of operator overloading is not one of them. indeed, it goes a long way towards the goal of creating high-quality libraries.

no one seems to complain that string classes overload operator== and operator=, for example.

I have amazingly high standards and don't think 80-90% of programmers are good programmers
put me in the 98-99% range. (more arrogance :-)

The problems come when you're trying to read code that looks like this:
check your code, a and b are undefined. but i know what you're getting at.

there is no excuse for creating a class with a confusing interface. when i'm creating classes, libraries and services, my number one goal is to make the API logical and easy for the users of my API to understand and program to.

if i have a choice between making the interface better or the code easier to implement, i will always choose the former.

my number two goal is to make my implemenation code as easy to support as possible.

C++ gives me the tools to make that possible. disallowing operator overloading would hinder that. that's really the only point i'm making.

I'm not trying to be offensive so please don't take it that way. I just find it amusing that the masses love such a deficinent language and featured abstraction :).
you're not being offensive at all, no worries. regarding C++ being deficient, i'm curious as to what you mean by that beyond granting the ability for developers to write bad code.

i'm also interested in knowing the criteria for a language being deficient. is it as compared to other languages in vogue at the same time? is it looking at how well the language supports its design goals? or is a comparison between languages which work in the same solution space?

zimv20
Mar 1, 2006, 04:50 PM
it's not about misunderstanding, its about inelegance. It's about being able to read code from a large project without having to crawl though the definitions of each class to figure out wtf it's doing when you see x operator.
indeed. as i stated above, there's no excuse for a confusing interface. i hope we can all agree that granting a string class these operators makes sense: +, =, ==, <<

but i haven't seen a string class that supports the % operator. why not? it makes no sense.

if one of my developers added operator+ to a StreetAddress class, i'd ask him what he was on about. but operator= and operator== make sense, imo.

operator overloading is really no different than any other interface concern. ALL methods must make sense in the context of the class. otherwise, i've got an issue.

zimv20
Mar 1, 2006, 05:33 PM
I don't mind being a little more verbose (as with 'cout << user.toString()' vs. 'cout << user') to remove a possible point of ambiguity
that won't cover all situations, though. let's say i'm writing a music app and i find it useful to add together notes and chords. i suspect that in doing so, i'll want to check for duplicate notes and determine if the new chord is greater than the sum of its parts. for example:

Note a3(A3);
Note e4(E4);

Chord chord1 = a3 + e4;

Note c4(C4);

Chord chord2 = chord1 + c4;

cout << chord2 << endl;

Note f3(F3);

chord2 += f3;

cout << chord2 << endl;

i'd get output something like this:

Am
Fmaj7

(musicians please check my chord nomenclature)

i think the sample code above is intuitive and easy to read. disagreements?

netytan
Mar 1, 2006, 05:42 PM
indeed. as i stated above, there's no excuse for a confusing interface. i hope we can all agree that granting a string class these operators makes sense: +, =, ==, <<

but i haven't seen a string class that supports the % operator. why not? it makes no sense.

if one of my developers added operator+ to a StreetAddress class, i'd ask him what he was on about. but operator= and operator== make sense, imo.

operator overloading is really no different than any other interface concern. ALL methods must make sense in the context of the class. otherwise, i've got an issue.

Of course I agree with that however the fact remains that the vast majority of C++ classes aren't so tidy or idealistic. Would you overload anything for a Mortgage class? Can you think of any operators that might be useful for that? You may not but thousands would :rolleyes:.

Classes with operator overloading become inconvenient when you're reading someone else's code because without first reading and remembering the code for all the classes being used you don't have the information you need yes there is usually documentation but the point stands.

Unless you have a very small context and are using descriptive variable names operator overloading will have detrimental effect on how easy the code is to understand, and so how quickly you'll be able to work on it (to put things into terms industry is concerned with) and how many bugs there'll be at the end (something the industry isn't so concerned with).

What I was trying to impart is that operator overloading is a poor excuse for abstraction at any level and serves little use for 99% of classes IMPS :).

I would take the fact that people want to use operator overloading so much as a hint that we need to be using more expressive languages that provide ways of producing highly abstracted and understandable code.

I guess it comes down to this: giving you're programmers a hammer to work with and telling him/her to fix a super computer isn't going to lead to any result you'll like :).

Take care,

Mark.

zimv20
Mar 1, 2006, 05:51 PM
Classes with operator overloading become inconvenient when you're reading someone else's code
are we talking about class implementation or code using that class?

the fact remains that the vast majority of C++ classes aren't so tidy or idealistic.
i think we're agreeing on just about everything. i'll suggest that we're spending too much time blaming the tool and not the developers. no language is going to be idiot-proof.

Would you overload anything for a Mortgage class? Can you think of any operators that might be useful for that?
to start, i'd overload operator<< for unit test purposes. it would do nothing more than dump the values of the object vars in human readable format. i wouldn't expect anyone else to use it, though.

depending on the project, i'd consider operator= and operator== (and operator!= to complement ==). it may be useful to compare the terms of two mortgages to determine if they're the same offer. operator= would be handy for copying mortgage terms for a new offer.

nothing else jumps to mind.

Sean7512
Mar 1, 2006, 05:59 PM
:confused: :confused: My simple, easy to understand joke turned into a huge debate at which i am confused on a lot of? Haha, I guess thats because I'm only a freshman in college, in my 2nd C++ class.

Too add to the debate, we wrote a class that reads in Cereal information (name, amt of ounces, price, and cost per ounce) from a data file. We had to then overload the << operator, so you can easily print all of the cereals information (Ex. cout << CerealA; ) We also looked at all of the other operators, >,<,=,==,!=, etc. Since I was just taught, obviously I do not know much, but I think for what we did, it was alot easter instead of including a "Print function" in our class. (CerealA.print(); vs. cout << CerealA; )

That is all I know on this topic, haha....:o

Edit: For our unrealistic example, I could see using the <,> operators to compare the cost per ounce, so one would know which brand Cereal gives you the most for your money. As long as your code is well commented, it should not be THAT hard for someone else to interpret, correct???

zimv20
Mar 1, 2006, 06:04 PM
we wrote a class that holds Cereal information (name, amt of ounces, price, and cost per ounce).[...] We also looked at all of the other operators, >,<,=,==,!=, etc.
some of those don't make sense for a Cereal class. i don't know what it means to ask:

Cereal lucky("Lucky Charms");
Cereal ccrunch("Cap'n Crunch");

if (lucky > ccrunch)
....

it's nice that you're learning some domain-type design, though.

therevolution
Mar 1, 2006, 06:14 PM
i think the sample code above is intuitive and easy to read. disagreements?
No, I won't disagree. But I don't think it's better than:


Note a3(A3);
Note e4(E4);

Chord chord1(a3);
chord1.addNote(e4);

Note c4(C4);

Chord chord2(chord1);
chord2.addNote(c4);

cout << chord2.toString() << endl;

Note f3(F3);

chord2.addNote(f3);

cout << chord2.toString() << endl;


Your code is more terse and two lines shorter, sure. That's kind of nice, I suppose, but IMO not nice enough to warrant the existence of operator overloading. Is my version really that much worse?

zimv20
Mar 1, 2006, 06:18 PM
Is my version really that much worse?
no. it's perfectly readable and understandable. i do feel mine is more elegant, and probably more accessible to non-coders (for whatever that's worth).

these are really fine details about readability. looks like we'll just have to disagree. no worries.

Sean7512
Mar 1, 2006, 06:22 PM
some of those don't make sense for a Cereal class. i don't know what it means to ask:

Cereal lucky("Lucky Charms");
Cereal ccrunch("Cap'n Crunch");

if (lucky > ccrunch)
....

it's nice that you're learning some domain-type design, though.

I agree that they don't make sense, I think the teacher was just introducing us to the concept.

What is domain-type design?

therevolution
Mar 1, 2006, 06:30 PM
these are really fine details about readability. looks like we'll just have to disagree. no worries.
Yep, no worries. :)

I don't mean to come across as argumentative just to hassle you. I think it's an interesting debate. I certainly see why people would choose to use them; I just question their ultimate usefulness. But I suppose we agree that "usefulness" isn't why you use them - you think it makes for more elegant code, which is fine.

I just hope I never have to maintain the code written by the guy who thought it would be a good idea to say 'chord1 *= chord2' :D

netytan
Mar 1, 2006, 06:35 PM
are we talking about class implementation or code using that class?


i think we're agreeing on just about everything. i'll suggest that we're spending too much time blaming the tool and not the developers. no language is going to be idiot-proof.


to start, i'd overload operator<< for unit test purposes. it would do nothing more than dump the values of the object vars in human readable format. i wouldn't expect anyone else to use it, though.

depending on the project, i'd consider operator= and operator== (and operator!= to complement ==). it may be useful to compare the terms of two mortgages to determine if they're the same offer. operator= would be handy for copying mortgage terms for a new offer.

nothing else jumps to mind.

Ok I can see what your saying and in these cases operator overloading is a handy way of applying polymorphism to objects you've created but only because of the syntax of the language that you don't have any power over.

I guess the major problem is when you do something unusual like overload = to be used in the same was as == or anything you wouldn't expect right off and ues programmers do stuff like this. Especially those who like other languages such as BASIC *shudders*.

I believe programmers should write good, clean, concise code or leave me alone but I do feel that the language used is a big factor in this because they're more than just tools. There mediums for expressing thought and the more clearly and precisely you can do that in a language the more challenging projects you'll be able to take head on easily.

Much as I like to blame the developers and the "tools" separately I think it's probably a mixture of the two. I've found that I can write code as a newbie to any language I've used (and I've used more than I can name) that would be on par with a medium level developer or in some cases even higher.

So I think it has a lot to do with the mindset you have at your disposal the more you ideas you're exposed to the larger the mindset you can use to solve a problem.

You should try programming in Lisp and if you like it recommend it for your next big project. I think you'll find the level of abstraction that is accessible to the developer far outstrips any other language and even if it doesn't its worth learning because it'll twist your brain inside out lol.

Once you've been exposed to this you should be able to understand what I mean when I say it's a poor excuse for an abstraction method.

It did mine, take care man.

Mark.

zimv20
Mar 1, 2006, 06:37 PM
What is domain-type design?
modeling realworld concepts. C++ is much more interesting when doing class and OO stuff than, say, generating a fibonacci sequence.

netytan
Mar 1, 2006, 06:39 PM
I think it's an interesting debate. I certainly see why people would choose to use them; I just question their ultimate usefulness. But I suppose we agree that "usefulness" isn't why you use them - you think it makes for more elegant code, which is fine.

I just hope I never have to maintain the code written by the guy who thought it would be a good idea to say 'chord1 *= chord2' :D

I agree entirely with this and I can flat out say I'd refuse to work on that project. The moment you see that kind of weird thinking you should know it's going to be bad and walk away lest you do permanent damage ;).

zimv20
Mar 1, 2006, 06:41 PM
You should try programming in Lisp and if you like it recommend it for your next big project.
i did a small bit of Lisp programming nearly 20 years ago and really liked it. haven't looked at it since, though.

funny thing about the industries i've worked in, Lisp would be a nearly impossible sell. on one java project, after being commanded to think outside the box, i suggested Prolog for doing some business rule stuff.

i was nearly run out of the building. in the end, the "thinking out of the box" people decided to stick with java for that part, even though they'd spent a year on it and couldn't get it to work.

people are funny.

zimv20
Mar 1, 2006, 06:45 PM
I don't mean to come across as argumentative just to hassle you.
i know, no worries.

I certainly see why people would choose to use them; I just question their ultimate usefulness.

i could make the argument that they're not needed at all for classes. after all, you demonstrated that with Chords and Notes. but they're still a part of the language, so i'll assume they remain solely for purposes of expression.

netytan
Mar 1, 2006, 07:18 PM
i did a small bit of Lisp programming nearly 20 years ago and really liked it. haven't looked at it since, though.

funny thing about the industries i've worked in, Lisp would be a nearly impossible sell. on one java project, after being commanded to think outside the box, i suggested Prolog for doing some business rule stuff.

i was nearly run out of the building. in the end, the "thinking out of the box" people decided to stick with java for that part, even though they'd spent a year on it and couldn't get it to work.

people are funny.

LOL nice work, next time you should run them out of the business. They're obviously not qualified to be making decisions like this :). If I ever decide to set up a business you'd be just the type of programming I'd be looking for, maybe have to outlaw the use of C++ though I'm really not a fan :D.

I've read a little on prolog but I haven't used it, I will eventually it's just not something I have a use for for the most part.

Mark.

zimv20
Mar 1, 2006, 07:34 PM
LOL nice work, next time you should run them out of the business. They're obviously not qualified to be making decisions like this :)
it's a difficult industry because of soooo many constraints: budgetary, skill levels, risk management, ass-covering, biases, egos, vendettas, time constraints...

most of my career has been as a consultant, so playing nice is as important as delivering the goods. while i wished i could have enforced my will to try the prolog route, i really didn't have a choice.

If I ever decide to set up a business you'd be just the type of programming I'd be looking for
ha, thanks for that.


I've read a little on prolog but I haven't used it
like Lisp, it's something i tried in the 80's but never got a chance to use in the industry. neat language. i really thought it'd work well in the situation i described above.

Soulstorm
Mar 2, 2006, 03:12 AM
I am not a proffessional programmer (yet) but I am not a beginner either. I still have much to learn, but as far as I have been involved with C++, I see that the lat thing that one should complain about, iis operator overloading.

Operator overloading exists for a reason. And it may has many cons, but it seems that the pros were many enough to have the creator/maintainers of C++ implement it in the language.

For me, it has proven useful in sone occassions. For instance:

I have a vector, full of objects of a class which contains many viariables. I want to output the contents of this vector into a file. So, I overload the operator "<<". Now, I can use it: 1)To display the private variables I want, through "cout << v[i]" and 2) To output the contents of the vector with only a statement of a kind of for(i=0; i<v.size(); i++){
myfile << v[i];
}
and that's about it. (my vector is named "v" and every place holds obbjects of a class). If it hadn't been for operator overloading, I would be forced to write many more lines of code.

I'm not trying to lecture anyone here, don't get me wrong, nor I believe that I am more experienced as a programmer as most of you probably are.

But I think that as most things in C++ operator overloading exists because there was the need for it. And it seems that many people think so, otherwise iit would have been abandoned long ago. If anyone thinks that code with operator overloadings is inefficient, then do not use it, and use what your expertise tells you. For me, operator overloading was handy in the above example...

ChrisBrightwell
Mar 2, 2006, 03:18 AM
Operator overloading exists for a reason. And it may has many cons, but it seems that the pros were many enough to have the creator/maintainers of C++ implement it in the language.I have been of the opinion, for a long time, that C and C++ go above and beyond the call of duty to let you do just about anything. They're so busy talking about the fact that they could that they never bothered to ask if they should.

Operator overloading, IMO, breaks one of my first rules of programming: Write code that is self-commenting. If that means writing more code, so be it. At least the poor guy who comes along behind you will be able to read your mess.

I have a vector, full of objects of a class which contains many viariables. I want to output the contents of this vector into a file. So, I overload the operator "<<". Now, I can use it: 1)To display the private variables I want, through "cout << v[i]" and 2) To output the contents of the vector with only a statement of a kind of for(i=0; i<v.size(); i++){
myfile << v[i];
}and that's about it. (my vector is named "v" and every place holds obbjects of a class). If it hadn't been for operator overloading, I would be forced to write many more lines of code.Why not implement a toString() or buildOutput() function for the objects being written?

Then you have something like this ... for(i = 0, j = v.size() ; i < j ; i++)
{
myfile << v[i].toString();
}Sure, the difference is subtle, but at least it's easier to read at first-glance.

zimv20
Mar 2, 2006, 03:53 AM
They're so busy talking about the fact that they could that they never bothered to ask if they should.
damn you! my C++ dinosaur-cloning program was almost complete!

ChrisBrightwell
Mar 2, 2006, 04:08 AM
damn you! my C++ dinosaur-cloning program was almost complete!Hah, you got me.

SamMiller0
Mar 2, 2006, 11:29 AM
for(i=0; i<v.size(); i++){
myfile << v[i];
}



Item #84 from Sutter & Alexandrescu's C++ Coding Standards: "Prefer algorithm calls to handwritten loops." I would change your code to look like this, or something similar. I can't remember the exact format.

This idea is from one of Herb Sutter's other excellent books, and his Guru of the Week usenet posting:
http://www.gotw.ca/gotw/074.htm


std::vector<Widget> v;
//fill the widget vector
std::copy(v.begin(), v.end(), std::ostream_iterator<Widget>(myfile));

netytan
Mar 2, 2006, 11:50 AM
...
Operator overloading exists for a reason. And it may has many cons, but it seems that the pros were many enough to have the creator/maintainers of C++ implement it in the language.
...
If it hadn't been for operator overloading, I would be forced to write many more lines of code.
...
But I think that as most things in C++ operator overloading exists because there was the need for it. And it seems that many people think so, otherwise iit would have been abandoned long ago.

Would you not find that all you've done is move the code you would have written into a method that overloads the operator rather than having it in a more versos method name i.e. toString().

Language design is a tricky thing, once you provide a feature it has to live on for compatibility. Even if overloading is only used by 5% of applications (it's not, but thats about as many as use it well) then it needs to be there :cool:.

The benefits visible in operator overloading really depend on who you ask, what looks good to one person might look terrible to someone else.

For instance I really love this piece of code here. It's clear to anyone who knows the language, it's elegant in size and flow; there's no duplicated code or variables to get in the way or cause bugs that are hard to track down.

Added to that you can see that the naming used makes a lot of sense even if you can't follow whats going on.


(define tree?
(lambda (lst)
(and (pair? lst) (or (pair? (car lst))
(tree? (cdr lst))))))

(define sum
(lambda (numbers)
"Adds the numbers in the numbers list and any sub-lists. If numbers is
a tree? then call sum recursively until there are only numbers and flat
lists left."
(apply + (if (tree? numbers)
(map (lambda (n)
(if (pair? n) (sum n) n))
numbers)
numbers))))


...
> (sum '(1 2 3 (1 2 3) 1 2 3 (1 (2 (3)))))
24
>


I included this code as an example because I'm sure looking at it will make just about all of you turning over in disgust ;). Look at all the parenthesis :o.

If this same code were produced using the style that operator overloading implies then it would be nearly impossible to follow this is an extreme case but it also proves unreadable in C++ code now and again.

It's all personal preference when it comes down to it, but I wont be using operator overloading any time soon simply because it's useless everywhere except in a few in very restricted languages.

As soon as things become more flexible operator overloading isn't used nearly as much. Or so the case studies would suggest :).

I'm by no means an expert, just have very strong opinions on what I like and what I don't either way just use whatever you think makes for better code :).

Take care,

Mark.