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."
How about eliminating the buffer overflows?
BOO! TERRO
> What do you think of Java ?
PLEASE don't ask that. The guy is a bit touchy on the subject.
Javascript + Nintendo DSi = DSiCade
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.
Err... I know topics with a title that begin "Interview with" usually mean you can ask questions to the person... but this is an interview done by another site...
Actio personalis moritur cum persona. (Dead men don't sue)
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
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
Let me answer that for you, since this is a story *about* an interview that has already taken place, not a story for gathering questions for an interview:
:)
"I think Java is kinda nifty."
Best answer you'll get.
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'
It lacks operators, seriously : when I had to develop my cellar for Qtopia, it saved me a huge time and code ergonomy to just use some operator to add new records to my db...
Trolling using another account since 2005.
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
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
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.
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.
>>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.
Try his FAQ: http://www.research.att.com/~bs/bs_faq.html#Java
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++.
I explicitely wrote about my code ergonomy : C++ is a language...
Related behavior depends on the compiler as well as on the code cleanness.
Now, I just prefer a language with which I can add different kinds of virtual objects using the fanciest syntax I may imagine instead of some rigid language like Java in which anything has to be.like(this).
Trolling using another account since 2005.
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)
What do you think of Java ?
Argh! I hate it when people ask this question! I heard it asked to him on more than one occasion. I dislike it only because it shows a lack of knowledge on the asker's part.
C++ and Java are two very different languages that just happens to share syntax. A good C++ programmer is not necessarily a good Java programmer and vice versa. In fact, its probably harder to be a good Java programmer if you already have a good amount of experience with C++ (an argument Bjarne himself makes for those going from c to C++).
C++ and Java are two different languages that are best used for different purposes. If you don't believe then try: dynamic server pages in C++, hardware-accelerated 3D gaming in Java, platform-independent applications in C++, or embedded systems in Java.
Just because a program _can_ be written in a certain langauge doesn't mean it's the best option.
-B
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)
> or embedded systems in Java.
J2ME.
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.
people are still using java and C++? Did I migrate completely to C# to early??? Dang!
/* oops I accidentally made a comment, sorry */
C++ and Java are two very different languages that just happens to share syntax. A good C++ programmer is not necessarily a good Java programmer and vice versa.
Well...
Java works very much like a (poor) subset of C++.
My own experience is that, having learned C++ well (and it is a steep learning curve), I was able to easily pass Sun's own Java certification before I had compiled a single Java program (Ok, I did one "Hello World"), because of the surface similarities of the languages.
One data point only, but either it says something about the similarity of the languages, or what Sun, at least according to its certification, expects of a Java programmer.
But you are right about the differences required in good programmers in the respective languages. Perhaps the biggest problems in Java are dangling pointers (null pointer exception) and pointer aliasing. The first Java deals with with a run-time exception -- and run time is too late, in my opinion. The second is dealt with by making most language/library objects (String, primitive wrappers (Integer, Boolean, etc.) immutable -- but while immutable objects dion't suffer from pointer aliasing, they're also not efficient (to "change" a value, you have to new up a new instance, and point all pointers to it, often not easy in Java because you can't pass a pointer-to-pointer), and most user objects aren't made immutable anayway.
C++, on the other hand, strives mightily to treat everything as a value object, even (especially?) when it's not a value object -- thus references, and smart pointers, and the handle-body idiom in general. A down-side can exist when what would be cheap and efficient on a primitive, such as pre-increment (++i) can be very inefficient on an object of class type (thus the C++ism of using post increment even for primitives in for loops, to strengthen the habit of only using pre-increment when trult needed.
More generally, C++ allows the programmer a great deal of freedom, and expects him to use it wisely (e.g., operator overloading); Java doesn't trust programmers but paradoxically allows dangling pointer problems and unecessary casts that C++ will catch at compile time.
The run-time versus compile-time costs are perhaps the biggest practical differences of the two languages: C++ requires much more of the compiler (think templates) and of the programmer (e.g, remember method overridding does not happen until an object is fully constructed) in order to endsure that as many costs as possible are paid once, at compile time and not at run-time; Java prefers to pay run-time costs, on the theory that machines are fast enough to pay the run-time costs and the benefit comes from easier, quicker coding. Which trade-off you prefer must really come down to where you fell you can best pay the costs; my take is that good C++ code will be more ribust in general, if robust is what you need.
Opinions on the Twiddler2 hand-held keyboard?
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 think you just made the grandparent's point by example. I wasn't going to respond, but I had to ask one question:
> but paradoxically allows dangling pointer problems
WTF are you talking about? Java doesn't even have the concept of pointers, much less the ability to leave them dangling. Everything in the system is an Object reference. When all the references no longer point to an object, the object magically goes away. Either you've got an object or you've got a null reference (which IS NOT a critical issue in Java like it is in C/C++).
Javascript + Nintendo DSi = DSiCade
In five years we'll wonder why anybody even mentioned Java.
<P>
People have been saying that for the past 5 years. It's just as wrong today as it was then.
<P>
Java doesn't even have the concept of pointers, much less the ability to leave them dangling.
If you truly believe that, you really are a dumbass. Why do you think there's a NullPointerException in Java?
It's always a long day... 86400 doesn't fit into a short.
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.
Everything in the system is an Object reference. When all the references no longer point to an object, the object magically goes away.
(Well, your "magic" is my "serious overhead that makes real-time programming esentially impossible".)
But you are correct that I wrote "dangling" when I should have written "null".
However, I don't agree that a null pointer exception is "IS NOT a critical issue in Java like it is in C/C++)". Java's "deals with" unexpected null pointers by throwing an exception; a exception does (or should) signal a critical problem.
Part of the problem with Java is that run-time exceptions (which are expensive) are used far mmore causually than they ought to be, in some cases even taking the place on nominal program flow.
Opinions on the Twiddler2 hand-held keyboard?
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
JOGL (www.javagaming.org)
Yes this is my real UID. No, it was not bought from EBay.
Why do you need to interview Stroustrup to learn about getting maximum from C++?
// Than are dreamt of in your philosophy."
Just do #include <algorithm>
"There are more things in heaven and earth, Horatio,
Oh, and there's more to C++ than <algorithm>
StoneCypher is Full of BS
> Why do you think there's a NullPointerException in Java?
Because it has a NULL OBJECT REFERENCE. Like I stated above. Nulls are standard in Java and are quite often used without causing program crashes. Besides, it's hardly a dangling reference. You have to intentionally give a variable a Null value or the compiler will throw a fit.
Javascript + Nintendo DSi = DSiCade
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.
Oh, and the designers at Sun must have misspelled "Reference" as "Pointer". Right. Because those keys are right next to each other. Oh, wait... they're not.
References in Java are pretty much the same thing as pointers in C except that you can't do arithmetic on them.
In C, pointers have three uses: dynamic memory allocation, aliasing, and array iterators. Java removed the last of those uses (which removed the need for pointer arithmetic), threw on some syntactic sugar (automatic dereference in most contexts) and called them "references" so people like you wouldn't be scared off by the big bad boogeyman.
Saying Java doesn't have pointers is disingenuous. It's like me saying I don't have a television because I watch TV using my TV tuner card.
It's always a long day... 86400 doesn't fit into a short.
> (Well, your "magic" is my "serious overhead that makes
> real-time programming esentially impossible".)
Let's be realistic here. How often do you *really* need those few hundred extra nano-seconds that the generational collector uses? You could create 50 temporary string references and they'll be deallocated *way* faster than most C code that does it manually.
> However, I don't agree that a null pointer exception is "IS
> NOT a critical issue in Java like it is in C/C++)". Java's
> "deals with" unexpected null pointers by throwing an
> exception; a exception does (or should) signal a critical
> problem.
If you try to use a Null object, you do have a serious problem. However, there are only two ways to get a Null object:
1. You coded an object to be set to null.
2. You didn't check if a return value was null.
In both of these instances, the Null is an expected result that due to a failure to check the value, you have inadvertently used. Look in some professional Java code sometime. You'll see Nulls used all over the place. It simply means "No object could be obtained". (e.g. If I can't find a user preference in a Properties object, I get a Null.) 99% of nulls used in Java do not result in NullPointerExceptions.
> Part of the problem with Java is that run-time exceptions
> (which are expensive) are used far mmore causually than
> they ought to be, in some cases even taking the place on
> nominal program flow.
This is not a problem. It is a feature. Just like in Lisp, Smalltalk, Eiffel and a variety of other languages. If you absolutely need the performance that is lost by exception and bounds checking, then don't use Java. Use a real time language such as C in situations where the risk to performance tradeoff is acceptable. But if you're going to try to convince me that your word processor needs those few extra cycles brought about by program safeguards, you might want to check your facts.
BTW, in my experience, Java is fast everywhere except for windows. This is apparently because of Windows' Virtual Memory which is far to aggressive for programs with larger memory footprints. BSD, Linux, Solaris, Mac OS X, etc. all run Java programs just as fast as native. OS X even allows for Cocoa apps to be written in Java by way of an automatic Java to Object C bridge!
Javascript + Nintendo DSi = DSiCade
Without "syntactic sugar" you have to deal with expressions like this:
equals(a, plus(minus(c,(plus(d,e))),f))
> Saying Java doesn't have pointers is disingenuous. It's
> like me saying I don't have a television because I watch
> TV using my TV tuner card.
Statements like this show how little people know about Comp-Sci these days. A pointer and a reference are two separate concepts. A reference CAN be implemented under the hood with a pointer, but there are other ways of doing it (including hardware).
> References in Java are pretty much the same thing as
> pointers in C except that you can't do arithmetic on them.
The primary difference in real world programming is that a reference is managed. You can't arbitrarily assign things to it like you can with a pointer. Plus, you are always guaranteed that you'll have a whole object on the other end, unlike pointers which may point to memory that doesn't even exist!
> In C, pointers have three uses: dynamic memory
> allocation, aliasing, and array iterators. Java removed the
> last of those uses (which removed the need for pointer
> arithmetic)
Actually, Java references do only the second. Dynamic memory is allocated outside of the Java program. Your best attempts at allocating new memory in Java may only result in a reuse of memory and objects without your knowledge. That's one of the advantages to references vs. pointers. They are safe and a party outside your program can use system resources in the most effective way possible instead of allowing your program (which may know very little about the system it's on) to manage memory willy-nilly.
Javascript + Nintendo DSi = DSiCade
Just FWIW, there was a time when Pascal was the language you taught to first-year Comp Sci. students and you could find a surprising amount of employment using it in the real world.
Note where Pascal sits now.
Canthros
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...
Sir, that is the funniest thing I have read all day. Bravo on your excellent grasp of pointers, references, and the languages of C++ and Java.
Canthros
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.
Thank you for your support. I wasn't really trying to be funny, but if it brought a smile to someone's face, I'm happy.
;-)
I just wish I could beat some sense into these Young'uns.
Javascript + Nintendo DSi = DSiCade
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.
Heh. How about:
> hardware-accelerated 3D gaming in Java
JOGL, JOAL, and JInput. Arguably, most programmers aren't familiar with these APIs since they are rather new. And people have made the (somewhat valid) point before that J2ME devices go beyond being embedded devices and really become small computing platforms. Still, the grandparent post is correct about using the right tool for the right job.
Javascript + Nintendo DSi = DSiCade
Not really. If there was a difference, why do "smart pointers" employ a "reference count"? Sometimes, the term "pointer" can imply an iterative functionality, but that is not strictly so (cf. "smart pointers").
It has nothing to do with whether they're managed or not. You can have managed pointers, even in C. Heck, you can even plug them into a full-blown garbage collector (or another type of allocator).
I was going to drop the first use of also, but I decided not to. Every object in Java is "dynamically allocated", so I left it in.
Again, you're confusing allocators with handles. Even the C++ free store allocator generally has that behavior. It's not uncommon that if you do
int *p = new int;
delete p;
p = new int;
then p will receive the same address it had before. Reuse of memory is, again, not a difference between C pointers and Java references.
It's always a long day... 86400 doesn't fit into a short.
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
> Not really. If there was a difference, why do "smart
> pointers" employ a "reference count"? Sometimes, the
> term "pointer" can imply an iterative functionality, but
> that is not strictly so (cf. "smart pointers").
Apples and Oranges. I didn't mention reference counts because they are not inherent to references. Externally managed objects are. As I said before, a reference guarantees that the object on the other end is whole and of the type expected. Pointers don't do that without the compiler doing a little helpful checking for you (that works out to a few warnings).
> Again, you're confusing allocators with handles.
No, you are. An object/reference system is completely different from a memory/pointer system. The reason why you're getting confused is that modern day object/reference systems are mapped on top of memory/pointer systems. Machines have existed in the past (Symbolics for example) that quite literally had the hardware designed around the object/reference design.
BTW, here's an example for you of how you could end up with the same thing:
String string1 = new String("Hello World!");
String string2 = new String("Hello World!");
Without even realizing it, string1 and string2 are quite likely the same object (depending on your VM). The reason is that the Virtual Machine is an external party who is smart enough to know how to give out references that meet the needs of your program. If it can obtain those references by reusing existing objects, it will. Obviously, this example won't work with classes outside of the Java core (the VM isn't quite THAT smart), but it should give you an idea of what I'm attempting to communicate.
In a similar fashion, the VM may pool shells of objects and initialize them on demand. Or it may preallocate memory for short lived objects and dump the entire memory block when most of the objects are dead (i.e. generational collection). It might defrag memory to make sure that bytes aren't going to waste. It might move an object in memory because it has "outgrown" the block it's in.
Most of those examples would break pointers since they always point to a specific location. If you moved an object in memory, you need to update all pointers to it. A VM implementation might simply hold a lookup table for the current location of objects in memory and hand out lookup entries as object references. At that point, references would fail to meet the criteria of a pointer. You could still argue that it's "just like a pointer, but with indirection", but all you'll accomplish is displaying how poorly you comprehend CompSci.
Javascript + Nintendo DSi = DSiCade
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
If you define the word "reference" to mean "exactly what Java's references do" and define "pointer" to mean "exactly what C's pointers do", you'd have a point. But that's not the language-independent definition of those terms. References predate Java, and pointers predate C.
/nothing/ in the C standard that prevents this.
/precludes/ them for corresponding, but it's not necessary.)
As far as ensuring that a Java reference always refers to a valid object (or null), that's the business of the allocator. It's got nothing to do with the reference itself. You could design a free store allocator for your C runtime that does the exact same thing (so long as you don't use pointer arithmetic, of course). There's
And as far as your example of the VM remapping memory, that meets the criteria for a pointer. Go read Knuth sometime. Really. Pointers have nothing to do with memory locations. (Nothing
It's always a long day... 86400 doesn't fit into a short.
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.
Sir, you are amazingly dense. I will leave it at that.
Javascript + Nintendo DSi = DSiCade
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!
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
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
Wow, I started that... :)
Kudos to your Java knowledge. While my knowledge of C++ is good and mine of the STL has recently improved, my Java knowledge is only to the extent that I realize that its only a falicy: (anything Java can do, C++ can do more efficiently.)
Ironically, an IBM consultant was the one that changed my thinking...
-Brian
... 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
Best troll ever.
Show me on the doll where his noodly appendage touched you.
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."
Answered in the comp.std.c++ FAQ.
http://www.jamesd.demon.co.uk/csc/faq.html
A minor correction: for VM in your post write "automatic memory manager" throughout. There exist numerous native-code runtimes which do all these things.
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.*woosh*
"Verbing weirds language." -- Calvin
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
Interesting post, a lot of which I agree with.
There is however one thing I don't understand. I am assuming that the distinction you draw between object-oriented and class-oriented designs / languages is the one about the desirability of run-time binding a la Smalltalk, Python etc. versus compile time al la C++. However, you then say 'if you write Java in a true OO manner' you don't get those types of problems. But Java hasn't got run-time binding, so what am I missing?
> There exist numerous native-code runtimes which do all these things.
Correct. I was simply flowing with the Java example I gave since I had already stated that the JVM was an example of an external party/entity responsible for handling references.
Javascript + Nintendo DSi = DSiCade
Dewd:
You came to the rongg place, you were looking for thoughtful, objective dialogue.
R,
C
Get thee glass eyes, and, like a scurvy politician, seem to see things thou dost not.--King Lear
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.
The ARM was not the standard, and is not. That book was published before the standard became available.
The PDF of the spec is available for As for "every time the standard advances" ... it has only "advanced" once -- in 1998 when the first standard came out. I think there will probably be a new standard within 10 years of 1998, and you
will probably have to spend a whopping $20 or so on that too.
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)
Then shut up until you do know something about 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.
C++ is a big language. There are a lot of books. Perhaps you should read some of them.
And ever tried reading someone else's C++ code?
Yep.
The language makes so many things implicit that understading the code can be pretty challenging compared to understanding an equivalent C program
Especially if you don't know C++. Likewise, Chinese is worse than English because I can't read Chinese.
but when you're trying to _read_ the code, it makes for trouble
Only if you don't understand the language.
Just my experience,
Which, by your own admission, is minimal.
Comment removed based on user account deletion
If more people took this advice there'd be a lot less buffer overruns in this world
Yes, that's fallacy number one. Java isn't necessarily slower (or faster). (Often, the VM is a bottleneck, but that's a QOI issue; it has nothing to do with the language per se.)
:-} (A rose, by any other name...)
Fallacy number two, of course, is that Java doesn't have pointers.
Scratch that... that's fallacy number three. Fallacy number two is that Java is platform-independent. (Hint: the JVM is a platform.)
It's always a long day... 86400 doesn't fit into a short.
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
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