Interview With Bjarne Stroustrup
koval writes "artima.com has published an initial portion of interview with Bjarne Stroustrup.
The scope of first part is mostly about improving the style of C++ programming and getting maximum from a language."
What do you think of Java ?
Owner of a Mensa membership card.
How about eliminating the buffer overflows?
BOO! TERRO
Any language that allows for someone making a living pointing out everything one shouldn't do needs more than a face-lift.
I used to wonder what was so holy about a silent night, now I have a child.
Oh boy! I can't get enough of Bjarne and J-Lo!
Where do you see C++ going as a language?
I have over 70 freaks, do you?
Interviewer: Well, it's been a few years since you changed the world of software design, how does it feel, looking back?
Stroustrup: Actually, I was thinking about those days, just before you arrived. Do you remember? Everyone was writing 'C' and, the trouble was, they were pretty damn good at it. Universities got pretty good at teaching it, too. They were turning out competent - I stress the word 'competent' - graduates at a phenomenal rate. That's what caused the problem.
Interviewer: problem?
Stroustrup: Yes, problem. Remember when everyone wrote Cobol?
Interviewer: Of course, I did too
Stroustrup: Well, in the beginning, these guys were like demi-gods. Their salaries were high, and they were treated like royalty.
Interviewer: Those were the days, eh?
Stroustrup: Right. So what happened? IBM got sick of it, and invested millions in training programmers, till they were a dime a dozen.
Interviewer: That's why I got out. Salaries dropped within a year, to the point where being a journalist actually paid better.
Stroustrup: Exactly. Well, the same happened with 'C' programmers.
Interviewer: I see, but what's the point?
Stroustrup: Well, one day, when I was sitting in my office, I thought of this little scheme, which would redress the balance a little. I thought 'I wonder what would happen, if there were a language so complicated, so difficult to learn, that nobody would ever be able to swamp the market with programmers? Actually, I got some of the ideas from X10, you know, X windows. That was such a bitch of a graphics system, that it only just ran on those Sun 3/60 things. They had all the ingredients for what I wanted. A really ridiculously complex syntax, obscure functions, and pseudo-OO structure. Even now, nobody writes raw X-windows code. Motif is the only way to go if you want to retain your sanity.
[NJW Comment: That explains everything. Most of my thesis work was in raw X-windows. :)]
Interviewer: You're kidding...?
Stroustrup: Not a bit of it. In fact, there was another problem. Unix was written in 'C', which meant that any 'C' programmer could very easily become a systems programmer. Remember what a mainframe systems programmer used to earn?
Interviewer: You bet I do, that's what I used to do.
Stroustrup: OK, so this new language had to divorce itself from Unix, by hiding all the system calls that bound the two together so nicely. This would enable guys who only knew about DOS to earn a decent living too.
Interviewer: I don't believe you said that...
Stroustrup: Well, it's been long enough, now, and I believe most people have figured out for themselves that C++ is a waste of time but, I must say, it's taken them a lot longer than I thought it would.
Interviewer: So how exactly did you do it?
Stroustrup: It was only supposed to be a joke, I never thought people would take the book seriously. Anyone with half a brain can see that object-oriented programming is counter-intuitive, illogical and inefficient.
Interviewer: What?
Stroustrup: And as for 're-useable code' - when did you ever hear of a company re-using its code?
Interviewer: Well, never, actually, but...
Stroustrup: There you are then. Mind you, a few tried, in the early days. There was this Oregon company - Mentor Graphics, I think they were called - really caught a cold trying to rewrite everything in C++ in about '90 or '91. I felt sorry for them really, but I thought people would learn from their mistakes.
Interviewer: Obviously, they didn't?
Stroustrup:
Use Unlambda instead.
C++ has become a massive boondoggle of poorly-widely-understood and often inconsistently implemented features, in which class reuse is mostly unheard of and different C++ APIs can rarely communicate well with each other natively due to a widespread failure to actually use the standard STL classes (String, Vector, etc).
It is time to throw out the bathwater. Unlambda combines a strict sense of simplicity with the full power of functional programming, allowing you, once you become familiar with a small set of idioms of the langage, to utilize the same patterns and strategies you used in OO languages such as C++ in a more direct and evocative manner, without the verbose clutter and paperwork OO languages force you into. Have you ever noticed with C++ you spend more time serving the syntax than actually planning your object heirarchies? No more. Unlambda cuts through the crap and lets you write "what you mean" in your code.
The benefits of Unlambda have been shown in multiple studies. Think: after all the time and energy you have invested in C++, can you really say it has delivered on its promises? Consider using Unlambda for your next enterprise-class project instead.
The scope of first part is mostly about improving the style of C++ programming and getting maximum from a language.
Why do you need to interview Stroustrup to learn about getting maximum from C++?
Just do #include <algorithm>
Then you can use max() and max_element() on STL objects to your heart's content.
Speaking of C++, is there a compiler that complies with the ISO standard already? Does anyone use it?
Save your wrists today - switch to Dvorak
All he did was complain about over and under object-orienting c++ code. Not sure why that's useful... My Computer Science professors do that all the time.
--Slashdot readers delight in generalizing the behavior of other Slashdot readers.
I see that a lot of people here are confused and posting questions for Bjarne Stroustrup. This is not a slashdot interview where people post questions for the guru and the editors pick the top 5 for the interviewee to answer. This is an interview that was done by an external website and not interviews.slashdot.org.
Ever had a real programming language class?
Twin or more? ITA
Apache/Spring/La
This and this made me thought that the questions were being asked now, d'oh! Oh well, Bjarne if you're reading this... :)
I have over 70 freaks, do you?
Since you only got smart ass replies, here you go: Bjarne Stroustrup was the creator of C++.
Seriously, you can't seriously improve a language by telling people how to program with it. You also don't know if these so-called style improvements help anyone at all. This is just like Hungarian notation, where people stupidly decided they wanted to know the type of a variable by looking at its name. The C++ language is what it is. Whatever you can do with it is what it is. You can't make C++ into Java by telling people what they can't do. This is why C++ is not Java. The "problems" in its design are part of the language.
Please don't waste your time reading that interview. The interviewer is asking very irrelevant questions and doesn't seem to have a clue about what the other is answering. His answers are garbage anyways, the whole discussion is about invariants. It looks long because there's 4 pages, but if they'd use a normal font, it'd fit easily on a single page... Elementary school level interview if you ask me.
Real men code in assembler.
For very contorted definition of real men. OOP requires higher degree of abstract thought than assembler, and obviously not everyone can hack it. Assembler, Fortran and Visual Basic are for people whose brain can't handle abstraction, but rather just want to get their hands dirty doing stuff. People who would rather do than think what they are doing. Others take delight in creating abstract architectures and systems that Last.
Obviously many self-proclaimed C++ programmers belong in the assembler group, rather than the OOP group (where Python/Java/Smalltalk people dwell).
Save your wrists today - switch to Dvorak
The C++ Style Sweet Spot
A Conversation with Bjarne Stroustrup, Part I
by Bill Venners
October 13, 2003
Summary
Bjarne Stroustrup talks with Bill Venners about the perils of staying too low level and venturing too object-oriented in C++ programming style.
Bjarne Stroustrup is the designer and original implementer of C++. He is the author of numerous papers and several books, including The C++ Programming Language (Addison-Wesley, 1985-2000) and The Design and Evolution of C++ (Addison-Wesley, 1994). He took an active role in the creation of the ANSI/ISO standard for C++ and continues to work on the maintenance and revision of that standard. He is currently the College of Engineering Chair in Computer Science Professor at Texas A&M University.
On September 22, 2003, Bill Venners met with Bjarne Stroustrup at the JAOO conference in Aarhus, Denmark. In this interview, which will be published in multiple installments on Artima.com, Stroustrup gives insights into C++ best practice. In this first installment, Stroustrup describes how C++ programmers can reconsider their style of C++ use to gain maximum benefit from the language.
Climbing above C-level
Bill Venners: In an interview, you said, "The C++ community has yet to internalize the facilities offered by standard C++. By reconsidering the style of C++ use, major improvements in ease of writing, correctness, maintainability, and efficiency can be obtained." How should C++ programmers reconsider their style of C++ use?
Bjarne Stroustrup: It's always easier to say what not to do, rather than what to do, so I'll start that way. A lot of people see C++ as C with a few bits and pieces added. They write code with a lot of arrays and pointers. They tend to use new the way they used malloc. Basically, the abstraction level is low. Writing C-style code is one way to get into C++, but it's not using C++ really well.
I think a better way of approaching C++ is to use some of the standard library facilities. For example, use a vector rather than an array. A vector knows its size. An array does not. You can extend a vector's size implicitly or explicitly. To get an array of a different size, you must explicity deal with memory using realloc, malloc, memcpy, etc. Also, use inline functions rather than macros, so you don't get into the macro problems. Use a C++ string class rather than manipulating C strings directly. And if you've got a lot of casts in the code, there's something wrong. You have dropped from the level of types, a high level of abstraction, down to a level of bits and bytes. You shouldn't do that very often.
To get out of writing low level code, you needn't start writing a lot of classes. Instead, start using facilities provided in libraries. The standard library os the first and most obvious source, but there are also good libraries for things like math or systems programming. You don't have to do threading at the C level. You can use a C++ threading library. There are quite a few of them. If you want callbacks, don't use just plain C functions. Get libc++, and you'll have a proper library that deals with callbacks--callback classes, slots and signals, that kind of stuff. It's available. It's conceptually closer to what you're thinking about anyway. And you don't have to mess with error prone details.
Most of these techniques are criticized unfairly for being inefficient. The assumption is that if it is elegant, if it is higher level, it must be slow. It could be slow in a few cases, so deal with those few cases at the lower level, but start at a higher level. In some cases, you simply don't have the overhead. For example, vectors really are as fast as arrays.
Object-Orientaphilia
The other way people get into trouble is exactly the opposite. They believe that C++ should be an extremely high level language, and everything should be object-oriented. They believe that you should do everything by creating a class as part of a class hierarchy with lots of virtual functions. This is the ki
Here's another very interesting interview with the C++ creator. You'll be shocked, I promise ;)
Regards,
-pararox-
Quote Bjarne Stroustrup: Yes. If every data can have any value, then it doesn't make much sense to have a class. Take a single data structure that has a name and an address. Any string is a good name, and any string is a good address. If that's what it is, it's a structure. Just call it a struct. Don't have anything private. Don't do anything silly like having a hidden name and address field with get_name and set_address and get_name and set_name functions. Or even worse, make a virtual base class with virtual get_name and set_name functions, and override it with the one and only representation. That's just elaboration. It's not necessary.
.class files.
Thank You! This is the number one java peeve. Every time I just want to make a structure I've got to make a whole class. That's a whole file. That's a whole lot of extra code. In C/C++ I can make an equivalent struct in a few lines.
This is why I like python so much. I can do all the object-orientedness I want and all the proceduralness I want and they work together perfect. And everything pops out into super efficient C code and then into executable with my gcc. And if I want it cross platform I can just use jython and get workin
The GeekNights podcast is going strong. Listen!
Real programming class?
MOV AX, @DATA
LEA BX, DSARY
INC BX, 02
MOV AX, BNDMP
MOV CX, 10
BRD:
MOV [BX],AX
MOV AX, BNDMP
INC BX, 02
LOOP BRD
and your talkign about a REAL programming language?
Hardy har har...
I prefer
for(int x = 0, x=11, x++)
{
dsarray[x] = bndmp;
}
myself...
All he did was complain about over and under object-orienting c++ code. Not sure why that's useful... My Computer Science professors do that all the time.
Being that there is a large codebase out there that breaks either one of these rules I would venture a guess that is why he commented on it. He does not believe that there is a sliver bullet to solving software problems nor does he believe that C++ is one either. It is just a language he designed to solve problems he encountered while programming.
C++ is not object oriented. It has OOP support but does not mandate it. The other extreme is that it is not C. If you find yourself falling to one of these extremes in *EVERY* coding probem then there is a high probability you just might have missed his point.
BSD is designed. Linux is grown. C++ libs
...and getting maximum from a language.
Like English?
Real men code in assembler
Since when did Steve Gibson start posting here as an Anonymous Coward?
Some people use a screwdriver, others use a butter knife. That's the beauty of programming; there are numerous tools and technologies at your disposal that will all achieve the effect (or at the very least, a semblance of the effect) you desire. Business users typically don't know the difference anyway, so it's really a matter of programmer's preference. Pick those you feel most appropriate to your project, and leave the rest.
Most people I know don't get the beauty of something like C++. It's a massively complex language. So complex, as a matter of fact, that you can create OTHER languages with it (via templates). But, like any other, tool or technology, take what you want from C++, and leave the rest behind.
Spread the RC luvin'
Probably the main reason OOP exists is that it provides a mechanism by which new code can be added to old code, without having to dig into the old code to find just the right spot to make the function call to the new code.
See, in your assembly language, if you want to add new code, you have to not only write the new code, you have to dig through your Asm to find the little tiny spot where you JSR (or whatever your opcode may be) to the new code.
In my C++/Java, I just subclass that puppy when I write the new code, and my code gets called automagically. (Well, actually via a dynamic function call table, but you knew that.)
It doesn't help so much on a small, one-man project. But once you have more than one person and more than a thousand or so lines of code, suddenly OOP gets really, really useful.
I went to one of this guy's conferences on C++. I thought it'd be more in depth, but it was merely introduction to the features of C++. It does this, it does that. Neat libs like boost and the stl. Also has ACE libs for cross compatability
Well, as one may expect, someone asked about java. He got very biligerant and brief about it. "C++ is supported on N many more platforms than java." (Can't remember N). It was also the last question too, which left that "weird" sense in my mind's eye.
--
"I'm not bright. Big words confuse me. But Wanda loves me and that should be enough for you." - Cosmo
Bill Venners: In an interview, you said, "The C++ community has yet to
internalize the facilities offered by standard C++. By reconsidering the style of C++ use,
major improvements in ease of writing, correctness, maintainability, and efficiency can
be obtained." How should C++ programmers reconsider their style of C++ use?
Bjarne Stroustrup: It's always easier to say what not to do, rather than what to
do, so I'll start that way. A lot of people see C++ as C with a few bits and pieces added.
They write code with a lot of arrays and pointers. They tend to use new
the way they used malloc. Basically, the abstraction level is low. Writing
C-style code is one way to get into C++, but it's not using C++ really well.
I think a better way of approaching C++ is to use some of the standard library facilities.
For example, use a vector rather than an array. A vector knows its size. An array does
not. You can extend a vector's size implicitly or explicitly.
To get an array of a different size, you must explicity deal with
memory using realloc, malloc, memcpy, etc.
Also, use inline
functions rather than macros, so you don't get into the macro problems. Use a C++ string
class rather than manipulating C strings directly. And if you've got a lot of casts in the
code, there's something wrong. You have dropped from the level of types, a high level of
abstraction, down to a level of bits and bytes. You shouldn't do that very often.
To get out of writing low level code, you needn't start writing a lot of classes. Instead,
start using facilities provided in libraries. The standard library os the first and most
obvious source, but there are also good libraries for things like math or systems
programming. You don't have to do threading at the C level. You can use a C++
threading library. There are quite a few of them. If you want callbacks, don't use just
plain C functions. Get libc++, and you'll have a proper library that deals with
callbackscallback classes, slots and signals, that kind of stuff. It's available.
It's conceptually closer to what you're thinking about anyway. And you don't have to mess
with error prone details.
Most of these techniques are criticized unfairly for being inefficient. The assumption is
that if it is elegant, if it is higher level, it must be slow. It could be slow in a few cases, so
deal with those few cases at the lower level, but start at a higher level. In some cases, you
simply don't have the overhead. For example, vectors really are as fast as arrays.
He's discussing class invariants, and how they help one design interfaces, and how they must be maintained. But he's refused to put that into C++! For years he'd been asked about adding some form of contracting to the language, but he'd always come back with how that's not needed. (I always thought part of it was due to his hatred of Bertrand Meyer (of Eiffel fame)).
Has he now seen the error of his ways? Is contracting (in any form other than assert) going to get added to C++?
remember Sammy Jankis
The other way people get into trouble is exactly the opposite. They believe that C++
should be an extremely high level language, and everything should be object-oriented.
They believe that you should do everything by creating a class as part of a class hierarchy
with lots of virtual functions. This is the kind of thinking that's reflected in a language
like Java for instance, but a lot of things don't fit into class hierarchies. An integer
shouldn't be part of a class hierarchy. It doesn't need to. It costs you to put it there. And
it's very hard to do elegantly.
You can program with a lot of free-standing classes. If I want a complex number, I write
a complex number. It doesn't have any virtual functions. It's not meant for derivation.
You should use inheritance only when a class hierarchy makes sense from the point of
view of your application, from your requirements. For a lot of graphics classes it makes
perfect sense. The oldest example in the book is the shape example, which I borrowed
from Simula. It makes sense to have a hierarchy of shapes or a hierarchy of windows,
things like that. But for many other things you shouldn't plan for a hierarchy, because
you're not going to need one.
So you can start with much simpler abstractions. Again the standard library can provide
some examples: vector, string, complex number. Don't go to hierarchies until you need
them. Again, one indication that you've gone too far with class hierarchies is you have to
write casts all the time, casting from base classes to derived classes. In really old C++,
you would do it with a C style cast, which is unsafe. In more modern C++, you use a
dynamic cast, which at least is safe. But still better design usually leads you to use casting
only when you get objects in from outside your program. If you get an object through
input, you may not know what it is until a bit later, and then you have to cast it to the
right type.
Bill Venners: What is the cost of going down either of those two paths, being to
low-level or too enamored with object-orientation? What's the problem?
Bjarne Stroustrup: The problem with the C way is that if you write code C-style,
you get C-style problems. You will get buffer overflows. You will get pointer problems.
And you will get hard to maintain code, because you're working at a very low level. So
the cost is in development time and maintenance time.
Going to the big class hierarchy is again, you write more code than you need to, and you
get too much connection between different parts. I particularly dislike classes with a lot
of get and set functions. That is often an indication that it shouldn't have been a class
in the first place. It's just a data structure. And if it really is a data structure,
make it a data structure.
Borland C++ Builder 5.0 has an ANSI compliant compiler, including STL support. I'm sure 6.0 also does.
I remember that it was such a big deal that it was advertised on the box. Check it out.
Even though the original post was a troll , as someone who has coded in assmbler all the way up to C++ and other assorted languages (OO and functional)
I'm afraid that assembler IS for real programmers. Why? Because to do anything complex in it is DAMN hard and not only do you have to understand what data structures you require
(the abstraction) but you have to understand how to map them down efficiently in a way the computer architecture can handle. I'm sorry , but writing even complex C++ is like a walk in the park compared to writing a complex assembler program , especially if its on a RISC CPU or god forbid a parallel architecture such as a Transputer (ok , they're long defunct but you get the point).
well, you do have to know what you are doing, but the standard says:
vector::at
const_reference at(size_type off) const;
reference at(size_type off);
The member function returns a reference to the element of the controlled sequence at position off. If that position is invalid, the function throws an object of class out_of_range. That is just like Java. the code will look the same.
BUT
the if you use the '[]' operator with an out of range index, then the behavior is undefined. so it becomes an implementation dependent thing in this case. So its best to avoid depending on [] for portability sake.
He's also the inventor of the "Jump to Conclusions" mat that was widely advertised on TV during the 1980s.
Stroustrup and the interviewer miss one important point in the class vs. struct and invariant discussion: binary compatibility. The reason why you should not access variables in structs/classes directly is not always that their representation may change. More often it happens that you need to add a member, but this is not possible without breaking binary compatibility (at least on the usual Linux/Unix compilers). So you need to use the private class/d-ptr pattern to hide at least future members from the public class. This does not break apps that use the class members of earlier version, but it would make the API inconsistent, as the newer version would need to offer a different way of accessing the members. And the easiest one is to have get/set methods. So if you don't want to fall into the inconsistent API trap later, you should use get/set methods from the beginning. It's the only chance to have a consistent API over several evolving but still binary compatible versions.
one thing which I thought was interesting was the assertion: "you should have a real class with an interface and a hidden representation if and only if you can consider an invariant for the class."
That's very clear and succinct.
>>Instead, if you build a relatively simple interface to a Date class, you might have five or ten member functions that are there because they are logically necessary. [..] Then you get these five or ten operations, and you can build the other 50 in a supporting library.
I would disagree with that statement. While I can understand the concern (less dependence on data structures in the 50 methods), this creates an API that sucks. As a developer you want to have all helper functions for a data type at a single place. As the user of an IDE you want to see all available functions when you enter a variable with a given type. By spreading them into two or more places you increase the risk that somebody does not find them and reimplements them.
Yea those bitches were ruthless... and still are!!
maybe ...
for ( int x = 0; x != 11, x++ )
???
I don't know a hell of a lot about C++, but from what I've seen, I hate it.
There are multiple books written which may as well all be titled "How not to shoot yourself in the foot with C++", more books of this type than I have seen for any other language. The language brings some tools to help the programmer, but it brings far far more ways for the programmer to screw up.
And ever tried reading someone else's C++ code? The language makes so many things implicit that understading the code can be pretty challenging compared to understanding an equivalent C program.
If you're _writing_ a C++ program, and you've been doing it awhile, I'm sure all that implictness that comes with inheritance, etc. is a good thing, but when you're trying to _read_ the code, it makes for trouble. It is often very hard to understand just a piece of a C++ program. You have to understand a whole class hierarchy and all sorts of interrelationships in the code before you can begin to make more than the most trivial of changes. Most C programs I've seen, perhaps because they are less "tightly" designed, are more amenable to being modified sensibly by someone who doesn't have a complete understanding of the entire million lines of code in question.
Just my experience, C++ is a good thing for initial code writability, but it is a bad thing for code maintenance purposes. You're mileage may vary.
You can't improve a language by telling people how to program with it.
This koan is worthy of a "Programming Pearl" entry. If only it had come to Bjarne rather than some random Slashdot user, the C++ programming world would be a much better place in which to live and work today.
I've always liked C++. After reading about half (still working on the rest of it) of "The C++ Programming Language" by Bjarne, I've learned so much about what good C++ programming is about. During University, the C++ class I took covered so little. It was basically a C course except we implemented yet another string class. This book is great. Bjarne comes across as a really smart and logical person. The last few chapters about design are great. I skipped up to them after reading the first 2 sections or so. I love reading interviews of him and things he's written. Everytime I work on a personal project I try to add another idea he presents to my own work.
I seriously enjoy programming in C++.
Bjarne: "You oughta use vectors rather than arrays."
Thanks for the tip dude. Now I will finally take advantage of this cutting edge technology that C++ provides.
I've been preaching this song for the better part of 20 years. But people got very keen on putting everything in classes and hierarchies. I've seen the Date problem solved by having a base class Date with some operations on it and the data protected, with utility functions provided by deriving a new class and adding the utility functions. You get really messy systems like that, and there's no reason for having the utility functions in derived classes. You want the utility functions to the side so you can combine them freely. How else to I get your utility functions and my utility functions also? The utility functions you wrote are independent from the ones I wrote, and so they should be independent in the code. If I derive from class Date, and you derive from class Date, a third person won't be able to easily use both of our utility functions, because we have built dependencies in that didn't need to be there. So you can overdo this class hierarchy stuff.
// ...
Bjarne talks about this problem a little in his book (TC++PL), but I'm glad that he mentioned it here. Putting utility functions in derived classes is a mistake that is made far too often. How many times have you seen someone write something like this:
class MyString : public std::string {
public:
size_type find_no_case(const char *subStr) const;
};
Stop it! That should be a free-standing function. There is absolutely no benefit to using inheritance in the above code. The only thing it yields is a warm fuzzy feeling from using member functions instead of free-standing functions. Some coders just enjoy writing
MyString s("foobar");
i = s.find_no_case("foo");
instead of
std::string s("foobar");
i = find_no_case(s,"foo");
because it "feels right", even though it limits the reusability of the function. C++ programmers, please take note. It is a mistake that even book authors like Steve Heller make (Link)
A little background information would be useful. For all I know, he could be the Swedish Chef on the Muppets.
Bjarne Stroustroup in "Swedish."
Since the site is Slashdotted, here's a quote from the translated interview:
You can fake OOP - you just get a bad design...it'll still work, it'll just be crappy. If you attempt to fake assembler, the machines goes down.
VB supports OOP, BTW.
> Obviously many self-proclaimed C++ programmers
> belong in the assembler group
I think it's more "90% of Java developers belong in the crappy OOP group," which is way worse in my opinion.
We went through this with Wirth. Wirth devised Pascal, which had reasonable data structures, although not objects, terrible I/O, and strings that only worked if they were short. He then insisted that it shouldn't change. From this came a whole range of incompatible Pascal dialects (Turbo Pascal, Object Pascal, Clascal...), and some successor languages (Modula I, II, III). Modula III was actually rather good, but nobody except some researchers at DEC SRL (now an empty building in Palo Alto) used it. Two decades later, few use Pascal or its derivatives, and Wirth is a forgotten and bitter man in Switzerland.
This cycle is being repeated with C++. The first version of C++, before templates and the STL, was terrible. Without templates, horrible schemes involving huge defines were used to make generic objects. Strostrup used to have great hostility to run-time type information, which led to unchecked downcasts all over the place.
Round 2 of C++ came late, and it took a long time before the compilers did templates. Then came the STL, which is wierd and unsafe, although useful.
C has little abstraction and little safety. Java has both abstraction and safety. C++ has abstraction without safety, a terrible combination. The basic problem with both C and C++ is that the language requires the programmer to obsess on storage allocation and release, yet gives no assistance in this. Attempts to encapsulate storage allocation in C++ fail miserably (look at the history of auto_ptr). Attempts have been made to fix the language by adding another layer of rote ritual ("patterns") on top of it, but compilers can't check that, so it doesn't reduce bugs.
Another area of trouble comes from the history of C++ as a preprocessor for C. Bell Labs had a tradition that "you can't change the linker". (This is probably because the original UNIX linker was written in assembler and had few comments.) Because of this, some tasks that should be deferred to link time (such as building vtables) are done at compile time.
The price paid for not changing the linker is substantial. Private function members appear in header files so that vtables can be built at compile time. That's the real reason, despite what you read. If it weren't for that, you could have much stronger separation between declaration and implementation. And you wouldn't be recompiling class users just because the class implementation changed. Ada and Modula got this right, but C++ got it wrong. And Strostrup refuses to fix it.
Yes, there are "patterns" for working around this. But they're workarounds. The programmer is doing the compiler's job. This imposes a cost on every programmer and distorts C++ programs.
Strostrup still insists there's nothing really wrong with his language. Read what he's written about the C++200x standards revision cycle. Meanwhile, C++ is being abandoned for Java, C#, C, and scripting languages.
He is not Swedish, he is Danish.
I mis-read the title. Thought it said "interview with a mousetrap"
oooops...
So rise up, all ye lost ones, as one, we'll claw the clouds.
It depends what you consider "real" Hungarian used "reasonably".
The idea of annotating variables to show certain fundamental properties has merit. For example, using "m_" or something similar to distinguish member variables can be useful to avoid name-clashes or developers resorting to not-quite-pseudonyms. Using "n" as a prefix consistently to indicate that the variable is a count of something can be useful.
Notice, however, that neither of these is explicitly embedding type information in the variable name. Using "m_fValue" for a member value of type float is foolish, because if you ever change the value to be of type double, or LibraryExtendedPrecisionDouble, your name is now worse than useless, it's misleading. This is why MicrosoftHungarianNotation(TM) sucks.
The only exception to the latter that I make with any regularity is prefixing pointers with p+ (that's a regular expression :-)) to indicate the level of indirection can be useful. It's rare for that property of a variable to change, and saves looking up whether you defined something to be a pointer or a reference later. Of course, then you have to worry about how to represent iterators, smart pointers, names of arrays, etc.
The best one I ever saw was someone who insisted on prefixing all variables of reference types with "r", e.g., "rValue" instead of "value". That demonstrates a spectacular misunderstanding of both the value of warts and the implications of using a reference, all with one letter. :-)
If you disagree, post your argument. (-1, Overrated) isn't your personal censorship tool for views you don't like.
Looking through, I can't believe I didn't see someone else asking it...
Xaotik Designs
It's not "probably" fake. It's complete crap. He debunked this in his FAQ a couple days after the first troll posted it.
You cannot apply a technological solution to a sociological problem. (Edwards' Law)
Most people I know don't get the beauty of something like C++. It's a massively complex language. So complex, as a matter of fact, that you can create OTHER languages with it (via templates).
How funny it is that I consider Lisp a quite simple language (at least syntactically) and it still can do all this OOP, language-in-language stuff, etc., despite being ~20 years older...
Anyway, go Python :P
How do you know that? How do you know the intent of the poster?
The language was certainly colorful, and implies a certain degree of immaturity or personal involvment in the issue. It wasn't a detached and cool assesment. The implied criticism of zealots in such a passionate post is mildly amusing. However, there is a point of sorts. Here's the original post:
Suppose the poster had written this instead: (I'm not sure that's exactly the posters intent, due to the style, but it will serve as an example.)
If the poster had used more moderate language, would you still have called the post a troll? Doesn't the language the poster used also support an alternative interpretation, in which not only are they not trolling (posting with intent to "attract predictable responses or flames"), but in which these are their genuine feelings? In fact, doesn't the language used support the idea that this person genuinely, if somewhat un-thoughtfully, despises OOP?
There's a Slashdotter who sometimes signs just his name, and sometimes signs with "Esq." after. He says his ratings of "Troll" and "Flamebait" rise dramatically when he uses "Esq.". All of this implies that moderators are rating not the content, but the style.
Personally, I'd like to see the likes of "Troll" and "Flamebait" replaced by something along the lines of "Imprecise" or "Emotional". Maybe "Offtopic" could be replaced by "Tangential".
mods metamodded as "Unfair"
Why? Adding all the supporting functions into the type itself just clutters the interface and makes it hard to find the "heart" of what the class does. As mentioned in the interview, it also removes much of the benefit of abstraction and encapsulation.
That argument doesn't generalise, though. How do you find functions that work with two user-defined types? (Cue deep and meaningful discussion of double-dispatching implications. :-))
The correct answer to this problem is to put all your related types, supporting functions, enumerations, typedefs, templates and other gear into well-organised modules. C++ doesn't have a great module system, but it does provide namespaces, which could be used for this purpose if you chose to do so.
The fact that you want an IDE to give you a display of all the functions you might want is a sign of weakness in your IDE (for not taking full advantage of the abstraction mechanisms offered by the language), your documentation system (which should be what tells you which functions to use when) and, depending on what exactly you meant, possibly yourself (since you shouldn't be calling any function when you don't know what it does anyway).
If you disagree, post your argument. (-1, Overrated) isn't your personal censorship tool for views you don't like.
I like bjs. As long as it's not from "uncle" eddie.
if an oop guy can do oop, he can do it in any language- assembly, basic...it doesn't matter. the language merely presents the oop approach the language designer (stroustrup) thought out.
assembly language does not really have any support for oop. you are free to implement oop however you see fit. assembly is probably the most flexible oop language in existance.
although some find assembly to be a difficult language, it's hard to disagree that the native language is not the best approach for programming. not only for the sake of the processor but for the programmer as well.
why add layers to the cake? why all the flash and glitz? just get down to what your going to do anyways and avoid the middle man...it's a tough concept, and mostly rejected.
there's a shitload of people that can't program. they will continue to try. people will continue to make languages, paradigms, methods, etc so the people that can't program can basically hide the fact that they can't program (so they can get a job to buy an suv...) this will never change. most programmers arent innovators, they're followers and imitators. nothing is wrong with this. it's just kind of boring.
i wish programming could be like live performance music. it would be perfectly clear who could program. the turkeys would get weeded out almost instantly.
The MOV AX, BNDMP within the loop is not necessary. Additionally, IIRC it's faster to decrement cx and branch vs using loop on the 8086 (and definitely faster on more recent processors).
I programmed in C for years, mostly due to the performance of the early machines I used. Today, I wouldn't consider going back to C unless it was for time critical functions. Everything I do these days is in an environment that protects me from the gory details of memory management and pointers of doom. If I really need performance, I am going to profile my code and find the parts that really need the boost, and then recode the classes as C++ COM or more recently C++ assemblies for .NET. It is the same procedure I used to use when C was my primary language: find the performance hot spots and drop to assembly if needed.
The discussion of class design has nearly nothing to do with C++. I can use Java to build overly complex towers of inheritance. I can also use it to build poorly defined libraries. One think I *can't* easily do is blow myself (and the underlying OS) up do to a memory allocation problems.
I see C++ remaining for many years to build those "cycle critical" components, which are going to be consumed by languages with a guard over the chainsaw blade. Programmer efficency should always trump speed concerns until you have exhausted *algorithmic* improvement. I don't know how many times I see programmers saying "I'm using C++ for performance" while simultaniously writing something that is going to run in o(n^2) time, when a o(log(n)) algorithm is available. Yes, your C code will run your inefficent algorithm quicker than I would in a protected environment, but if my protected environment allowed me to see the abstraction that runs the fastest algorithm, my code will still be faster for large data sets.
Sig under construction since 1998.
... Mr Mensa, you'd realise that this isn't a slashdot interview. :-)
Stick Men
I started OO programming in 1987 with Smalltalk and continued with Objective-C in 1988. In 1989, I started using C++ and continued using it for about 7 years.
The one thing I noticed when I was programming C++ (when compared to Smalltalk or Objective-C) was that it is damn near impossible to implement a real OO design in C++. One is always having to struggle with the language and the result is pretty much always hacking the code to simply make it work.
I have always believed that BJ simply doesn't understand OO and this interview has really confirmed it for me.
Here are a couple of quotes which make me believe that:
Again, one indication that you've gone too far with class hierarchies is you have to write casts all the time, casting from base classes to derived classes.
What he describes above is not a problem with Object-Orientation (ie. this problem just doesn't happen in languages like Smalltalk or Objective-C), this is a problem with the hideously poor implementation of the C++ language. His comment here really shows that what he *thinks* is OO is really Class-Orientation. Pretty much all of the C++ code I've seen is Class-oriented and not Object-Oriented.
The differences may appear to be subtle, but the impact is profound. In OO programming, the complexity of the system is managed by a dynamic structure (the object model). In Class-oriented programming, there is no object model to speak of (except as it is derived from the class model) and the complexity has to be maintained within a static structure (the class model). The result is a whole lot of extra code to write because the class structure is more complex than it needs to be.
They believe that you should do everything by creating a class as part of a class hierarchy with lots of virtual functions. This is the kind of thinking that's reflected in a language like Java for instance, but a lot of things don't fit into class hierarchies. An integer shouldn't be part of a class hierarchy. It doesn't need to. It costs you to put it there. And it's very hard to do elegantly.
"A lot" of things don't fit into a class hierarchy? If he really believes this, he simply doesn't know what object-oriented is. The majority of things fit well into an object framework... it is only a few things which don't and the only reason they don't is because of optimization.
C++ programmers are absolutely rabid about optimization; even when it is completely unnecessary. It has become a religious area for them and they are completely unaware that they derive no benefit from it whatsoever 99.999% of the time.
Going to the big class hierarchy is again, you write more code than you need to, and you get too much connection between different parts.
This is a symptom of class-oriented programming NOT object-oriented programming. Again, this point is completely moot because these problems just don't occur in languages like Smalltalk or Objective-C. If you write Java like C++, then you get those problems, but if you write Java in a true OO manner, then you don't.
Again, BJ really seems to think that Class-Oriented programming and Object-Oriented programming are the same thing. They are VASTLY different.
But what kind of Danish? Apple?
That is true but nobody should pass a struct to anything which can be considered third party.
If you use your struct to pass data between methods widthin your program there is no problem with binary compability.
I was programming in assembly about the same time that I was programming in qbasic back in middle school. I started moving away from assembly my freshman year of high school when I took a Pascal class, followed by C the next year, and C++ and Java my senior year. Now I mostly just use assembly when I want to get to special instructions, and I expect to use it in a compilers class I'm taking this term. Aside from that the benefits aren't worth the extra typing.
VB isn't too bad, if you're writing something cheap that you expect to throw away next year, and seriously hate gui programming in other languages.
Real programmers use whatever's best for the task at hand. Just ask Steve Gibson of Gibson Research.
Java has freakin' wrappers for ints, an abysmally slow start-up, and is just getting generics. I could go on for hours on how Java is a brilliant marketing effort but a miserable, byzantine morass of hierarchies, but I'll stick responding to your comments.
C++Aaannnggghhh! Wrong. Please refer to the header in the STL, to use only when the many various STL containers somehow are insufficient for your job.
Strostrup still insists there's nothing really wrong with his language.Uhh, okay, but Sun is all too willing to discuss flaws with Java? And God knows, Microsoft is always willing to discuss anything the user is concerned about.
Wirth is a forgotten and bitter man in Switzerland.Is Wirth really bitter? I wouldn't know, but he's hardly forgotten. There's a whole school of programmers that advocate Delphi which, last I checked, was still being sold to this day. If you don't know what Delphi is, then hit borland.com and educate yourself.
Ada and Modula got this right, but C++ got it wrong. And Strostrup refuses to fix it.I'm skeptical that Ada has gotten much right, but speaking to the illusion that Stroustrup is Lord God King -- Stroustrup is only one member of a rather large team that actively develops C++ and the STL. It's a committee now, and it ain't solely up to him.
Meanwhile, C++ is being abandoned for Java, C#, C, and scripting languages.Uh, not for systems, games, or high-performance rapid development it isn't, and you can take that to church, buddy. Also, C is still in widespread use, but Java and C# are suffering the same competition, where there is competition in certain applications, from scripting languages that every non-scripting language suffers. Also, Java and C# are platforms, not simply languages, they're proprietary, and they're proponents depend heavily on making the development community believe that everyone(!) is jumping C++'s ship. Well, everyone isn't. Some developers, especially those that need to, see through the marketing spooge and use what's best for the job, not what Sun and Microsoft tell them to use. Jesus, if we all did what Microsoft wanted us to, we'd all be using VB.NET.
C has little abstraction and little safety. Java has both abstraction and safety. C++ has abstraction without safety, a terrible combination.This is just a doofy sentence. C has "little" safety but C++ is "without" safety? Dude, learn a language before you start spouting marketing crap. If you don't know why your sentence is completely wrong, then you're not qualified to comment.
Chr0m0Dr0m!C
Nope, I believe EDG's kit (as used in Comeau compilers, for example) is currently the best on paper. It does support things like export, detailed template mechanics and so on.
Visual C++ .Net 2003 (i.e., the second .Net version sometimes referred to as VC++ 7.1) is also pretty good, but does have acknowledged limitations.
g++ has a long way to go. It was never great, though when the 3.x series first arrived it was better than many. It's a relatively long way off the pace of the serious players now, though, both in standards compliance and in performance. I guess that's the price you pay for keeping the back-end code so widely portable.
However, please note that Boost (or at least its test suite) is a data point the maintainers specifically ask you not to use as a gauge for things like standards compatibility. See various recent threads in comp.lang.c++.moderated or comp.std.c++ for details.
Play fair... :-)
Hiring two big names in the C++ world in recent months probably did a lot of good. However, the killer with Microsoft was that until last year, their most up-to-date compiler (VC++ 6) was around five years out of date, as was its standard library implementation. It's unsurprising that, in comparison, the standards compliance of other tools was better, given that VC++ 6 actually predates the standard. That said, they had a pretty good idea of what was going to be in it and did a fairly decent job, considering.
If you disagree, post your argument. (-1, Overrated) isn't your personal censorship tool for views you don't like.
Structs should be disjoint from the API.
If you're publicizing an API, then you should be dealing with classes, not structs, for those reasons and more.
If you're using a struct, you're making some very strong assumptions about your data structure. You're also making an optimization in the process, whose validity depends on those assumptions.
You're assuming it has no behavior. You're assuming it will NEVER have behavior. You're assuming it's simple enough that you don't need to check for value constraints, or anything like that.
As a result, you should not let anyone, including yourself, extend that struct, either to add data members or behavior. If you have to, your assumptions were wrong... if you even imagine you might have to, your assumptions are wrong. Don't use a struct.
If the rules changed for you in the middle of the game and you need to replace the struct, you are then forced to communicate to everyone else that the assumptions have changed by changing the type. I would consider this a good thing.
Obviously, you should think carefully before sharing structs with others. But this applies to any data type that implies very strong assumptions which might not be shared with others... you have to wonder if your users need that, and if they do you have to enforce and document those assumptions before they break your application.
Freedom is the freedom to say 2+2=4, everything else follows...
Though I agree with some of your stuff, I think C++ could be improved even if you don't improve the linkers.
Your explanation that the vtable must be built from the public headers is wrong. All the modern compilers build it only in one source file (the rules vary but typically the one containing the first virtual function). It should be possible to add syntax to allow this to be more supported.
My proposal:
1. You should be able to define a new private member function at any time. Just write "int Foo::bar() {...}" and you will have a private method called bar(), whether or not it is defined in the header. This does not break any object-orientedness, as only other private members can call this. But it does get rid of a lot of annoyance in implementing classes, where you have to debate whether to change the header files or instead duplicate code or use pointers in order to get the implementation you want. Also private static data, and private static methods (probably by putting "static" before them).
2. Allow the token "..." to be at the end of a class definition. This is an indication that there are more items afterwards. This means the sizeof() and entire vtable is not yet determined. However a lot of inline functions can be declared. C++ already supports this as saying "class Foo;" is the same as saying "class Foo {...};" in this new syntax. You can also declare the rest of a class by declaring it again with "..." at the start, if the compiler sees this it knows that the vtable can be defined now.
While we are at it, I would really like to see a phony type called "0" which can be used as an argument class. "0" is unique in that it is the only type that can be automatically cast to a pointer or a number. A function declared as "int foo(0)" would be called in preference to "int foo(int)" when the argument is a literal zero. This would allow classes to match pointers better, and allow the compiler to compile around the "if" that is normally needed in the common case where initializing to a null or zero value is significanlty different that initializing to anything else.
However, you very much can improve how a language is used by telling people how to program with it. The single biggest problem C++ has isn't dangerous pointers, or ugly template syntax, or lack of a garbage collector, it's lack of good programmer education. C++ is a power tool, and requires skill to use. When most of the C++ textbooks in the world are teaching decade-old crap themselves, and most of the university professors don't know their own subject, it's not too surprising.
I can sympathise a lot with Stroustrup here. His tool is unjustly battered by the ignorant more than perhaps any other mainstream language today, and it creates a self-fulfilling prophecy: most people who learn C++ learn it badly, and write code with buffer overflows and other kindergarten mistakes. Others pick up on this, and learn from people who themselves learned badly, and write more code with kindergarten mistakes. It's about time the C++ programming industry reached High School, but few ever seem to, and when they do, they aren't valued as much as they should be.
If you disagree, post your argument. (-1, Overrated) isn't your personal censorship tool for views you don't like.
As Bjarne notes, class invariants are incredibly important, as are routine pre- and post-conditions -- the tenets of Design-by-contract, but they are mysteriously never considered as actual language features in C++. Want a language that actually does help with class and code correctness (allowing developers to specify usage rules)?
Use Eiffel.
Fully encapsulating the complexity of an abstract data type without just giving up and making many of the important decisions in the language itself is an extremely difficult problem in language design. I find the first poster's sentence, while obviously an exageration, to be rather insightful.
C++ has high aspirations in terms of giving the programmer complete control but ultimately fails due to the emergent complexity that results from the inability to fully encapsulate all of the design decisions.
Why?
I know only two computer languages which require money to get full spec: C++ and Eiffel (and I've met ("learnt" would be too big word) really many comp languages, it is my hobby)
To get *full* Eiffel spec, you must buy B. Meyer's book.
To get *full* C++ spec, you must buy Stroustrup's book, or pay fee to ANSI or ISO.
I bought Stroustrup's book years ago (printed in 1993), so it doesn't cover latest language features. Am I supposed to by his book each time C++ standard advances ?
Consider these facts:
1. overwhelming popularity of C++ worldwide
2. numerous incompatiblities between C++ compilers
3. enormous level of complication in syntax and semantic rules C++
(2. and 3. are often very subtle, but it does not help at all)
In this context, unavailablity of spec is outrageous, harmful and shameful, IMO.
I'm not saying that's necessarily a bad thing.
The interview is interesting in that it confirms the impression I've had from using and/or struggling to use C++. When I try to do anything object-oriented, specifically anything involving polymorphism, it seems to be fighting me all the way. After some struggling I usually emerge triumphant, but it's almost always a battle.
What Stoustrup seems to be saying is that classes should be treated as a special big deal, and shouldn't be used unless you're sure they're necessary. He seems to be recommending that there be, um, a class of elite programmers who put in the intense work to develop good, usable, well-debugged classes, and that the rank and file should, by all means use those classes but should not aspire to write new ones.
And this is not unreasonable, given the effort of writing classes and getting the storage management right and so forth.
The thing is, it's not a big deal to use classes in a truly object-oriented language. I'm not just talking about Smalltalk. Heck, they're trivial to use in REALbasic.
Well, is that good? It certainly leads to overuse of OOP. To a man with a hammer everything is a nail, and every programming language tends to encourage overuse of the things that it facilitates. Every programming language has a tendency to induce brain-warp.
C++, for better or for worse, does not induce object-oriented brain-warp.
People who try to use OOP in C++ because it's cool or because of some article they read (or some instructor they had) find that C++ punishes such behavior. And Stoustrup is right: when you are programming in C++, OOP should be used sparingly and only when it's needed.
Again, I'm not saying whether that's bad or good. That will depend on the degree to which you think OOP ought to be encouraged. If you think OOP should be just as much a part of a programmer's mental toolbox as iteration, or recursion, then it's not good. If you think OOP was the overhyped IT fad of the nineties, then it's not bad.
What I'm saying is that it has always seemed to me that C++ is not a very object-oriented language, and Stoustrup's remarks seem to me to confirm the objective validity of that observation.
"How to Do Nothing," kids activities, back in print!
Come on. If you're talking about vectors, lists, sets, queues, stacks, hash_maps, etc., then I think the STL does, via templates, quite a stunning job of encapsulation. Stroustrup's comment in the article concerns wider adoption of the STL as a starting point for more developers, and I challenge straightforward applications developers to disagree with that. In reviewing others' code, I'm frequently surprised to see arrays being used where vectors or lists would suit as well and be safer, and frequently disappointed to see many functions implemented without templates where they could be effectively abstracted and made much more reusable (and refactorable, if that's a word) by using templates. Please tell me where vectors, as an example, fall short in the encapsulation goal.
Where have other languages succeeded? Java provides a base int type and an Integer wrapper, and this is a fundamental data type. Is this success? I just think it's confusing. And what about operator overloading in Java? Yes for Strings but no for user types? I think operator overloading, in a dedicated OOP language of all things, is very important to encapsulation, but Java says "too dangerous"!
Rubbish. And I'm not really meaning to pick on Java. My overall point is that on an application level there is a pie-in-the-sky goal that might be feasible in terms of encapsulation and that's what I believe we should strive for. But on a library or language level, saying C++ is at fault for not ensuring "perfect" encapsulation (and I'm not sure what that is) throughout the libraries is a little naive. Please point out the language that gets anything fully correct without sacrificing something else. I mean, isn't this why we have different languages for different things?
Finally, I don't find that sentence insightful. Saying C++ is "without" safety is only illustrating a complete lack of familiarity with the STL. The programmer does have to keep track of things at times, but nothing even approaches real difficulty until you start creating your own ADTs. Mainstream types of the "Shape" or "Person" or "Animal" ilk are fine and dandy and really no more difficult or "dangerous" than Java or C#. It's not until you get into the implementation of things like "vertex_queue" or "parallel_list" that you, admittedly, start to get into much slower going territory. But there's also a lot of power there, too, power that's taken away in other languages, such as Java, because it's too "dangerous".
Chr0m0Dr0m!C
I always thought Pascal was another MS-related casualty.
In the 80s, everybody was talking about Pascal being the next great language. There were already descendants like Modula2 and ADA that were gaining market share. (This upset me because I learned Pascal, then C, and C looked more logical, so I hoped it would win.)
Then MS introduced QuickBasic, which turned into VisualBasic. (I have a book published by IBM stating "VisualBasic is a trademark of IBM.") Around 1992, you could probably translate programs from Pascal to VB or v.v. by substituting the keywords. The structure and the syntax was almost identical.
VB became the language of choice for beginners. It filled the same ecological niche as Pascal, so Pascal withered.
---
The difference between Pascal-based languages and C-based languages:
Pascal-based languages allow "procedures". Procedures can define multiple inputs and multiple return values. VB and the Windows API follow this syntax. It is easier for beginners to understand, but maintenance is difficult because the programmer needs to remember which variables can be changed safely and which will be returned.
C-based languages insist everything is a function. Functions have 0 or 1 return value.
When the C algorithm for returning multiple values by passing a pointer to a struct became difficult for maintenance, they invented classes, which allowed the multiple values to be retrieved. That was C++, but most early tutorials explained it as an addition to C, rather than a move to OOP. This is still evident in the ease of mixing C and C++ code in the same program.
Then Java added easier memory management and notification of errors (and reintroduced the virtual machine for sandboxing.) It follows the C++ model, but prefers OOP design.
I spend my life entertaining my brain.
If I write something like:
class F {
float a;
public:
F(float a0) : a(a0) { }
template<class X> X operator()(X x) const { return X(a)+x; }
}
is it OOP? It looks like OOP: it has a member variable, a method, a constructor and so on. But actually I'm defining a function closure. In Haskell you coud write an F(a) object as (a+).
My point is this: for many programmers today objects are often a(n awkward) vehicle for computing with closures. This has many payoffs: it gives the ease of functional programming but also potentially provides many performance benefits. I code like this all the time as do hundreds of others. This is how you need to code if you actually want to do anything non-trivial with the STL.
So in some sense I'm an OOP programmer. But in another sense I'm not. I'm not writing my code this way because I want to work with objects - I do it because this is the only way I know to treat a polymorphic function as a first class object in C++. Really I'm a functional programmer forced to use C++. It seems to me that many of Bjarne's remarks are way off the mark for programmers like me. We have to define classes for every damn little thing!
Doesn't it make you feel good to know that our freedoms are protected by politicans, lawyers and journalists.
More often it happens that you need to add a member, but this is not possible without breaking binary compatibility (at least on the usual Linux/Unix compilers).
By adding a member you are modifying an interface. What binary compatibility do you expect here ? If you need to extend a class-based interface, derive new class, add your new member there and publish it. If you are merely adding public data to your interface, you should simply add new access method(s). What Mr.Straustroup says is that in this case your data does not belong to the class, but a struct and your API should not be class-based. Feel the difference.
Invariant-based criteria for choosing between the struct and the class is the guideline for designing clean and elegant C++ code.
3.243F6A8885A308D313
You fairy, you company man.
Functions that change the data should be instance members. Functions that only read the data should be static members.
And use struct instead of class when you don't have to maintain an invariant (consistency amongst the class's data).
It's pretty common sense, but I agree with him that many people don't have it.
Intelligence shared is intelligence squared.
First, although it's not normally as efficient as explicit allocate and free, it is more efficient on average than something like reference counting. Even ignoring the fact that reference counting can allow mutually referenced objects to linger (ex. "a.next = b; b.next = a" will never reach a count of 0, and will never be freed), there is an overhead because every assignment to a pointer requires the compiler to insert extra reference counting code (or call a subroutine). That's a cost spread through the entire program.
Typically, a garbage collection system will traverse all live objects - and only the live ones. That means that it will take the same amount of time no matter how much garbage there is - only live objects are checked.
Most of the time only recently allocated objects are discarded, while older ones stick around a lot longer. The current Java system uses generational garbage collection, in that only recent objects are even looked at most of the time - objects that survive collection for several times are moved to a middle aged generation, and are looked at only incrementally (a fraction each cycle, not the complete group). The total number of live objects checked each time then becomes a very small number - in a long running program, probably less than 1% of the new objects, and maybe 0.1% of all objects.
Middle aged objects that survive enough incremental passes are moved to an old age generation - these are only checked rarely, when a decision needs to be made about expanding the heap.
The young generation garbage collection uses a copying method - this is important because it compacts the gaps between objects, defragmenting memory. A language like C or C++, which allocates using pointers, can't do this, otherwise the pointers will point to the wrong places. When there are gaps in memory (especially small ones), memory slows down because these gaps need to be checked each time, but are never large enough so the time is always wasted.
I wrote a program once which did a bunch of allocation and freeing for initialization, then a bunch of bigger allocations and frees for processing. After profiling it, it turned out that the program ran about 20% faster by just allocating the initialization objects, and leaving them there as garbage - they were too small to be allocated for the main program, so freeing them just created gaps which malloc() had to check each and every time. Good garbage collection eliminates this problem entirely as a side-effect.
In a Java program, you can give hints that it should do garbage collection at convenient times by calling the system/runtime garbage collection method gc() when it wouldn't be a problem. And there are products that give you better control over memory management (such as managing memory explicitly, as you would in C++).
In summary, garbage collection isn't nearly as expensive or scary as many people think, and can even improve performance significantly.
Bjarne Stroustrup: Yes. If every data can have any value, then it doesn't make much sense to have a class. Take a single data structure that has a name and an address. Any string is a good name, and any string is a good address. If that's what it is, it's a structure. Just call it a struct. Don't have anything private. Don't do anything silly like having a hidden name and address field with get_name and set_address and get_name and set_name functions. Or even worse, make a virtual base class with virtual get_name and set_name functions, and override it with the one and only representation. That's just elaboration. It's not necessary.
No! No! No! If you don't like the tedious task of writing the getters and setters, use an IDE which does this for you. But no structs that get used everywhere else. The other code has to know the struct's fields, and _if_ you have to change something (and there is always something), the struct approach requires numerous adjustments everywhere else. No good!
If you have a perfect architecture, all designed and documented, and no code will ever have to be reused, structs may look like a good idea. But in the real world that doesn't happen. With modern IDEs, there's no reason to avoid getters and setters.
Java wasn't even the first C-like language that was "object-oriented from the ground up." Java can't to be said to have begun until 1995. Objective-C definitely antedates it.
And for the same reason, I'm not sure that you could call C++ was the first C-like OO language.
C++ and Objective-C began at very nearly the same point in time. I wouldn't want to swear in a court of law which came first, but both were "in the air" circa 1990 or '91. They were perceived as being in competition, and the outcome was perceived to be in doubt.
Objective-C indeed attempted to be truly object-oriented. At the expense of adding new syntax and breaking compatibility with C.
C++ tried to be an improved C, adding various features including OOP while retaining full backward compatibility with C.
"How to Do Nothing," kids activities, back in print!
The D Programming Language is the evolutionary successor to C++ and does have class invariants, preconditions, postconditions, and Design by Contract built in to the core language.
Oh, please. Do you realize how many optimizations your compiler is doing so that you don't have to write really frigging difficult to understand code? Do you *really* want to perform manual loop unrolling (which is easy, but looks ugly)? Find out every function that can be inlined and specify them as such? Array Value Propagation? Array Blocking?
At least in the form of optimizations, if the programmer had to take care of things like these he'd have to make a choice between good, easily readable and maintained code, and fast code. And if you work in the real world, you know that you're not the only one actively maintaining your code. If the 10 other people working on it have to work hard to understand it, this wastes time, thus companies would be leaning towards the slow, but readable code. However, since the compiler recognizes that when you have your nice little loop performing matrix multiplication, you can actually get better performance by using blocking (performing operations on a small sub-matrix instead of going through rows and columns operations and thus reducing cache misses), you get the best of both worlds.
If you hate C++, it's unfair to suggest you read a book on it. But if you have any fondess for C++, or use C++ (even if you dislike it), Design and Evolution of C++ is probably worth your time. You learn why C++ is the slightly confusing mess that it is, and why Stroustrup believes it's the only way it could have succeeded. Having a grasp on why C++ is C++ (and not Objective C or Java) can improve your C++ coding abilities. And understanding why behavior you don't like is there can at least help minimize the suffering ("This is stupid, but there really isn't any way to change it.").
Search 2010 Gen Con events
Dr Stroustrup is one of the most intelligent people on Earth, and C++ is the most powerful language ever invented.
You don't have to make a new file for a 'struct' in Java. You can make Inner or Nested classes. And as another poster replied, you can just use public members.
// Rest of Outer's body...
public class Outer {
public static class MyStruct {
public int x;
public int y;
}
}
Perhaps your frustration with Java is misplaced?
I think perhaps there's a misunderstanding in the grandparent post. Stroustrup, and others on the standards committee, are on record as saying that they don't see the need for many language changes. They do, however, propose to make extensive library changes. Their reasoning is simply that there is likely to be more than one sensible way to approach topics such as, say, concurrency and synchronisation, and thus building them into the language itself is unduly limiting.
If you go to Stroustrup's home page (sorry, don't have a link handy, but it'll easily Google) and then look for his comments on C++0x, I'm guessing the slides from his presentation describing the above are still available.
If you disagree, post your argument. (-1, Overrated) isn't your personal censorship tool for views you don't like.
well, you can mismanage memory. You can have too many references to an object and cause a "leak". Seen it.
You can horrendously mismanage memory in Java, and are more likely to because of all the people telling you that you don't have to "worry" anymore.
Hey, it was no worry, worrying about memory management is my job. And guess what, allocating and deallocating the bits is THE LEAST OF IT.
I agree with everything else you say, e.g., algorythm design is the most important source of optimization.
-pyrrho
... a couple registers in our 6502.
-pyrrho
I think programmers are getting a bet self indulgent. Two languages are equivalent in some respect if the syntax of the source is equivalent!?!?
How about comparing what they compile to? Just to humor the old-school?
-pyrrho
Yeah. I think he's talking about within an app or module. If you need binary compatibility, then you need to start looking at some of the COM - like abstractions, what they do, and why.
Avoid Missing Ball for High Score
No silly, it's "down with OPP".
Yeah, you know me.
My thoughts exactly!
The interview changed my mind about C++. Before, I felt that it was only my ineptitude that made it hard for me to create classes in C++. Now, I understand that I may not be alone in my ineptitude (being part of the "rank and file" as you nicely put it), and that there is nothing wrong with using C++ simply as a way to access nice higher-level libraries and ADTs that couldn't have existed in pure C.
If a purer OO approach is needed, then just use a pure OO language instead! (insert Ruby/Smalltalk/... based on your religion)
"In our tactical decisions, we are operating contrary to our strategic interest."
Do them, and do them properly, and the problem is largely mitigated. Add to that a reasonable overall process, and you will be in good shape.
If management doesn't want to invest the time and resources necessary to develop good code... well that's a management decision and they should be willing to accept the consequences. In reality they management never takes the blame, it's always those damn lazy, sloppy engineers.
First off, you don't need a separate file to make a Java class. Secondly, making a separate Java class is not "a whole lot of extra code".
public class myStruct
{
public String name;
public int address;
}
How exactly is that any more code than with a struct? I'm afraid I don't see any merit in your claims.
What C++ really needs is more features... LOTS more features. The language is not "rich" enough. C++ should add many other features to its syntax.
- For example, the ability to name identifiers with any character in any character set.
- As C++ is not complicated enough, we need a way to dynamically create syntax. It would work like operator overloading, but much more complicated. And it would be called Syntax Overloading. For example, the code, ("for (" class "in" class ")")() { [insert code here] } would allow you to specify a new type of for loop with your own syntax. The compiler, upon reading this line, would add the new syntax to its language rules. Then, you could type for (className in otherClassName) { some.code.here(); } and it would work as expected.
- The language desperately needs some built-in cryptography functions. For example, the function const unsigned void do_it(const unsigned short void const crypto % arg) takes one parameter, arg, which is encrypted inside a processor register and cannot enter main memory for security reasons.
- More complicated template syntax is needed. For example, suppose you want to create a class that is unknown at compile time... obviously, a way to specify runtime template processing is desperately needed.
- Support for returning multiple return values from a function. For example, the function const unsigned short, const int *, const long long grok_the_file(void) might return three different return values, seperated by commas, as in, return i, j, size; Oh yeah, and you could specify functions that return an unknown number of values using ellipses, as in unsigned short... function_name() or simply
... function_name(). Suppose you want to call a funciton that takes 3 parameters... you could instead pass it one function that returns 3 return values and C++ would know what to do with it.
- C++ needs a reserved word, like please_reconsider_cast, or something, that uses common sense to figure out what the heck you're trying to typecast into what, so that even if the code is faulty, the compiler will figure out what you really mean.
These are all just a drop in the bucket. C++ is obviously too small and simple of a language.One of the challenges of C++ as a programming language, is that it requires the developer to truly understand what the compiler is doing or going to do in various conditions. In fact. there are many cases where you need to know what a compiler will do when you dont do something (e.g. when you dont write a copy constructor).
I cannot think of a another programming language that does this to the same degree.
no, that doesn't mean you suck. However, if you have the self-discipline to change languages over such issues, why not use a pointerless paradigm and appropriate class systems in C++.
In other words, what's wrong with C++ that a good class system doesn't answer? And why redeem C++ this way? Because of it's no-overhead philosophy --- that is, if you love garbage collections, a C++ garbage collecting class is going to be more efficient and more tunable to your particular needs. Why not use that if the result is more efficient?
As you point out, the tools to find memory leaks are quite mature and plentiful. The tools to avoid them, patterns of development, are equally mature. I think it's useful to learn them. Running away from them cannot succeed, as the issues are those of basic logical style. Open paren, close paren. Open bracket, close bracket. Allocate, Free, New, delete. This bookending of control is ubiquitous. When you allocate something, you have to free it. In java this means setting the reference to null, not thinking about it is a recipe for disaster.
It's been a long time since I've blown past the end of an array is use the standard vector class now.
-pyrrho
and be multiparadigmed, and you shall be the light.
-pyrrho
the key to what C++ gives you is in Stroustrups comments one enforcing invariance. C is missing some syntax that helps one accomplish this.
-pyrrho
Statistically speaking there is danger in allowing a car to exceed the speed limit, but that danger is difficult to quantify and it may very well be exceeded by the improvement in travel efficiency when folks speed.
OTOH a pistols generally tend to hurt more people than they help. Some people successfully defend themselves from other people (with guns), but the more frequent scenario is that someone carelessly leaves their gun unsecured and an inexperienced user hurts or kills themselves with it. C/C++ is more like that gun. There are systems programmers that really need the extra speed, but most people, like Homer Simpson, use it to turn off the lights or open a beer. They would be better served with a safer, more featureful language like Java.
but with '//' comments.
why? C is a paradigm available in C++ and if it's really best, it is available.
Of course, no doubt, a few contructors and other lightwieght C++ idioms would sneak in, becuase they introduce no overhead.
-pyrrho
C++ is not an object oriented language, it's a multiparadigmed language with some OO idioms available for the paradigm you use in the end.
even the standard library is not object oriented.
-pyrrho
the vector is not as basic as you seem. The array, with no bounds checking is primative, vectors, which resize and guard their bounds are not as primative, and there are many ways to do this.
Besides, many people consider something that is a part of a languages standard library as part of the language. I'm with you though, and vector was worth having when it was separate, and part of the STL.
-pyrrho
I see what you are saying. I came to C++ the "easy" way... I programmed in C and slowly adopted C++ idioms that made sense (I still am not fond of iostream classes). So for years I did not use exceptions or template classes. I have only in the last couple of years started using STL in earnest, now that it's settled down.
Even though the compilers have mostly caught up to the language, I still think this is the way to go with C++... you don't use C++ full bore using all it's fun idioms, C++ is multiparadigmed, your program isn't supposed to be. Even with good compilers you need to limit yourself to the tools C++ offers that fit your problem domain.
PS: there is little doubt in my mind that the VM is becoming specialized, and if it becomes specialized then it really can outperform a compiled language IN is special domain. The domain of Java is Busines To Business, and it's so well supported in that sphere, even I would not argue that it's not becoming the best platform for the kind of applications you mention.
cheers.
-pyrrho
This indeed a very important issue on linux.
Go to his homeoage, find the list of publications, and read the article that he published on April 1st, back in '96 or so. It's six pages of extraordinarily wacky stuff written in a completely serious tone. (Until the very end.)
Like, we can now assume that every computer display is capable of at least 256 colors, so make the color of the identifier part of its name. I.e., "int i;" in a red font is a different entity than "int i;" in a yellow font, even though they're in the same scope.
This is the same paper that proposes to overload whitespace.
You cannot apply a technological solution to a sociological problem. (Edwards' Law)
If an issue with a language happens is a deployment issue specific to a particular OS, then it normally indicates a questionable software design in first place
Minor bug in your code: DS not loaded.
mov ax, @data
mov ds, ax
mov cx, 10
mov di, offset dsarray
mov ax, bndmp
cld
rep stosw
Comment removed based on user account deletion
Stop posting as an AC to try to get karma.
Your question is complete nonsense.
It's a C++ to C covnerter which uses gcc/msc/bcc or whatever as a backend. Why would you want to use comeau when you have g++, escapes me. Obviously, "export" is too trivial. If it was of any practical use, it would have been implemented in g++.
I think you make an interesting point about a lot of this depending on the quality of C++ programmer, and I would extend that to admit that there are certain level of programmer that will always need a simplified environment, and that's fine.
But for professional developers, wouldn't it be best if we just focussed on making he best tools and educating our industry to use them properly?
I mean, if you look, there are a lot of tools of convienience in the hardware store that professional builders don't use. You can duct tape something and it's good to go, but that's not what you train engineers... though they might use duct tape in a pinch.
I think you might be onto something about Java for newer programmers. I already have learned about all the things Java is to save me from, like the ins and outs of memory management, so I don't notice an speed up when I code in Java. The kinds of bugs I have to hunt in my stuff is not particularly addressed, and can't really by, by any language.
If a java program was written in a couple days, and the C equiv in a month... that implies something. There is not that much difference in the language. That sounds like library availability, the C programmer had to write something that was already available in Java, which begs the question... was there a good library available they didn't know about and could they have used C++. The 10% would still make it a better tool and worthwhile.
But where we really will probably have to agree to disagree is just on the "needless complexity" issue. That needless complexity is C++ giving you more than you need --- so you can decide what you need and have a wide range of paradigms under which you can code. That is C++ not trying to second guess for you. If C++ give an automagical solution, it also give no-solution so you can build your own automagic. If you don't like cout, there is still printf and if you don't like exceptions, it's up to you and your Coding Standards to decide is you have to use them.
It's that old choice vs. chaos. Personally, I can handle the chaos of choice.
-pyrrho
I've interviewed "senior" programmers a fair bit, and I'm invariably struck by how many of them (basically all) can't do something as simple as a thread-safe getter/setter in C++, but even the more junior programmers can get it right in Java on the first try. These are the kind of mistakes that literally steal weeks of productivity.
:)
but aren't you implying we baby this condition? These guys are frauds. They need more education. They could get that education on-line! They could get it from good books. Amazon can even lead them to good books (if they know one good book).
Programming in C may be like free climbing, but C++ isn't... that's the point of contructors and the class idiom in C++... ropes and wedges and all the rest. You don't have to touch a pointer in C++.
I think people are objecting (I don't know about you) to the fact that you are ALLOWED to free climb in C/C++... but they claim you HAVE to.
-pyrrho
Er, rtfa? If you follow his very first recomendation and use the STL for vector and string (correctly) then you won't overrun.
Innocent people shouldn't be forced to pay for inferior software development.
--"Code Complete" Microsoft Press
is a big fat I-can-do-anything Virtual Machine to slow it down, remove power, and slow it down without giving any noticeable benefits.
Luckilly Microsoft has given us this.
- x->lock(); x->foo = "bar"; x->unlock();
- x->set_foo("bar");
/* atomoic lock, set, unlock */
I highly recommend using the second method unless you have a performance-critical reason to try using the first method.I started programming in Apple Basic. Within six months it was 6502. Pointers made perfect sense to me. I am baffled why people find them confusing.
Of course there are difficulties handling pointers, but mostly because we use so many of them... conceptually it's not difficult.
PS: You had 256 whole bytes of ram? why back in my day... oh no wait, you've got me beat.
-pyrrho