HN Academy

The best online courses of Hacker News. [about]

C++ For C Programmers, Part B

Coursera · University of California, Santa Cruz · 47 HN points · 1 HN comments

HN Academy has aggregated all Hacker News stories and comments that mention Coursera's "C++ For C Programmers, Part B" from University of California, Santa Cruz.
Course Description
This course is for experienced C programmers who want to program in C++. The examples and exercises require a basic understanding of algorithms and object-oriented ...
HN Academy Rankings
Provider Info
This course is offered by University of California, Santa Cruz on the Coursera platform.
HN Academy may receive a referral commission when you make purchases on sites after clicking through links on this page. Most courses are available for free with the option to purchase a completion certificate.

Hacker News Stories and Comments

All the comments and stories posted to Hacker News that reference this course.
Oct 14, 2013 · 47 points, 52 comments · submitted by hydrology
nly
Imho, C++ should be thought of as a new language with a degree of backward compatibility with old C code, not as a 'bigger C'.

How I'd start:

    Lesson 1: Pointers don't exist in C++, we 
       have references.
    Lesson 2: malloc() doesn't exist in C++
    Lesson 3: Templates are awesome.
    Lesson 4: Smart pointers are awesome.
    Lesson 5: 'Structs' can have constructors, and 
       they're awesome!
    Lesson 5.5: Exceptions are awesome!
    Lesson 6: 'Structs' can have copy constructors and 
       assignment operators, but the default ones do 
       exactly what you'd expect so you shouldn't have 
       to write them often.
    Lesson 7: OK, OK... pointers still exist in C++ but
       smart pointers and references make them almost
       deprecated, right?
    Lesson 8: ...oh, and if you use raw C pointers you
      need to do all this extra donkey work when it 
      comes to handling exceptions, and write a lot 
      more of those pesky copy and move constructors 
      and assignment operators I told you you didn't 
      need to write.
      Example: writing a smart pointer (with C pointers!)
    Lesson 9: Implementing a safe, dynamic, exception-safe
      array in C++ using templates and C pointers.
    Lesson 10: back to sanity, the ease of using <vector>
      (or the output of lesson 9) in every day code. 
       Introduction to the STL, <string>, etc.
       
...and so on. The idea is to first teach the common C++ way, and then teach the penalty of ignoring it and going the C way, and then the places where you need to pay that penalty.

Imho teaching inheritance or virtual functions early is also a bad sign. I'd go with public/private access control first (leaving protected), then member functions, then pure virtual member functions and basic inheritance, all the while presenting no hint of Circles and Ellipses, just interfaces.

pjmlp
This is the approach taken by Bjarne in his new book "Tour of C++".

I tend to bash C and C++ a lot given their unsafe by default nature as a Pascal refugee, but at least C++ can be made safe when the right abstractions are used and I do like it anyway.

ErsatzVerkehr
The instructor's (self-written) textbook gets terrible reviews on Amazon. Not a good sign.

http://www.amazon.com/For-Programmers-Third-Edition-3rd/prod...

checker659
What's wrong with handling errors with status codes as opposed to exceptions? Just because it exists doesn't mean one has to use it, no?
nly
Exceptions allow you to leverage value semantics and safe reference semantic abstractions like smart pointers. If you fail to handle them properly you will also discover bugs a lot sooner.
skrebbel
Nice! However, I'd appreciate the converse more.

I'm pretty well versed in C++, and every time I try to write something in C, I fall back to C++. I find memory management a pain without RAII, error handling a hassle without exceptions, and, well, anything really a pain without some sort of standard container library.

I have the idea that there's good alternatives for these in C-land, but I'm unfamiliar with them and would love for an expert to teach me.

In general, I wonder whether there's really that many people who know C but not C++. This might just be me projecting myself onto the world, though. Anyone?

luikore
There's no replacement for exceptions, but you can use setjmp and longjmp if you really want to jump out many layers of nested calls.

In C11 there is type generic macros that helps writing C++-like overloaded functions.

There are several extensions in GCC too.

For RAII-like memory management, there are __attribute__((constructor)) and __attribute__((destructor)).

C++ does type reflection on constant expressions via type traits templates, in GCC there is simply typeof().

If you are bored about writing static function modifiers, you can write a function inside function.

If you want to allocate a vector which won't change capacity and be released when out of local scope , for example in C++:

    auto v = std::vector<int>(n);
With C99 dynamic arrays you can use this instead:

    int v[n]; // n is a variable determined at runtime
You can use the union trick to achieve safer type casts too.
roel_v
Use GObject (https://developer.gnome.org/gobject/stable/) and GLib. GObject is basically a bunch of macros to let you write OO code in C, GLib is a cross-platform set of libraries with somewhat of a 'standard library' of data structures, string handling stuff etc. It's the foundation of Gnome, it's also LGPL so that may be an issue. To be honest though I've never used it for strictly C-only code, I've only used it on Linux with gcc and it was 10 years ago.

Still, it's a nice hack for when you want to write C++-like code while still using C constructs only.

skrebbel
Thanks for the suggestion, I'll look into it.

That said, my first underbelly reaction is that I don't want to write C++-like code in C. Why would I do that? I might as well use C++ then. It's like writing functional code in Java. It's possible, but it's a hack.

What I'd like to learn is how to decently deal with memory, exceptional behaviour, common data structures, etc in modern idiomatic C. Some other people in this thread made some nice suggestions for that, btw, so thanks guys :)

frou_dh
May a thousand home-made hash tables bloom!
yoodenvranx
I kind of like the way how Zed does the error handling:

http://c.learncodethehardway.org/book/ex20.html

wrl
Here's my preferred way of handling errors: https://www.securecoding.cert.org/confluence/display/seccode...
paulbarker
I've done so little C++ so long ago that I may as well fall in the category of a C programmer who doesn't know C++. If I had spare time over the next 8 weeks I'd definitely do this as a refresher course.
ksk
>I find memory management a pain without RAII,

That statement is true. But, as you may be aware, it doesn't encompass quite a few use-cases. A lot of usecases require you to have fine control over performance and using RAII will cause random speed-bumps. for e.g. when a ref-counted smart pointer(s) goes out of scope and triggers 'heavy' destructors on held objects to free up resources - at a non-deterministic time.

amboar
The collection maybe a little eclectic, but ccan might interest you: http://ccodearchive.net
udp
> anything really a pain without some sort of standard container library.

It's certainly not standard, but I wrote a nice little generic list library you might be interested in: http://github.com/udp/list

It uses GNU extensions, but can fallback on C++ instead if you need to build with MSVC.

16s
I use C++ because of the std containers (vector, map, set, etc). I don't have to roll my own and I'm free to think about the problem at hand rather than how to get the proper data container for this, that and the other.
finnw
I can understand this - I know some C++ but I am not very good at it, so I usually go for C with "greenspunning", i.e. using an embedded scripting engine, e.g. guile/lua/spidermonkey
CraigJPerry
You're the first person i've heard of who falls back to C++, if that data point is of any value.

AIUI exceptions and RAII are mutually exclusive in C++. I don't know enough about C++ so i wouldn't be surprised to find out this is wrong.

jacobparker
> AIUI exceptions and RAII are mutually exclusive in C++

That is... very wrong. Exceptions are perilous unless you use RAII religiously (which you should; it's good.)

For more information, read up on RAII and search for "exception safety."

The definition of C++ RAII from Wikipedia: "In this language, if an exception is thrown, and proper exception handling is in place, the only code that will be executed for the current scope are the destructors of objects declared in that scope". Without this it is very hard to reap any benefits of exceptions (people have disagreements on what those are, if any, but that's another topic).

CraigJPerry
Up-voted a few of the others below too.

I also found this which I thought was a high quality summary: http://www.parashift.com/c++-faq-lite/ctors-can-throw.html

archangel_one
Exceptions and RAII match well, actually. Managing resources via RAII means that when an exception is thrown, the destructors of local objects are invoked so they'll release resources they've acquired.

In fact, I'd argue that you very often have to use RAII with exceptions, since there's no 'finally' block on a try-catch statement and hence it's the easiest way to ensure stuff gets cleaned up (well, except for catch(...) and rethrowing, but that's kinda ugly).

eliasmacpherson
correct me if I am wrong but you can't rethrow in a destructor and hence RAII is required if you are using exceptions - because the cleanup and reporting work must be done in the destructor - unless you use global state to track failures and check after every attempted release of a resource i.e. C error checking.
pjmlp
> You're the first person i've heard of who falls back to C++, if that data point is of any value.

Every time I write C code is at a gun point of being forced to do so. When I have the choice between C++ and C, I always pick up C++.

berkut
I've tried several times to write new projects of mine from scratch in C just for a challenge, and have gone back to C++ every time.
cldr
Not sure what AIUI means, but the very words "exception-safe" usually imply RAII.
dysoco
I heard awful things about this course. Just check the reviews for it's textbook: http://tinyurl.com/cppcprog

In general, anything that says "X for Y programmers" is not worth it.

If you really want to learn C++, and you already know C, I suggest either "Accelerated C++" or "The C++ Programming language"

16s
"Accelerated C++" is a fantastic book if you wish to pick-up idiomatic C++ quickly.
PLejeck
I'm slightly afraid to learn C++ after being told so many horror stories. But for the low low price of free? Count me in.
stinos
Forget about the stories. I have quite some experience with both C and C++, started with C. There's horror in both of them, if you do it wrong enough. Oh yes there's more horror in C++, there are more ways to do it wrong. But in the end it comes down to the same: learning curve. If you know it well enough there's no horror anymore, just joy.
pjmlp
Agreed, specially since C++11 provides better mechanisms for writing safe code if one needs to stay in C++ world.

Now C is a different matter.

tdsamardzhiev
Here's a little secret, guys: It's not the language that is bad. Although a lot of things can go out of hands and most of the added features seem extremely "tacked on", at the end of the day, it's us, the programmers, that write the bad code. C++'s main problem is allowing people to write stupid code... but then again, stupid programmers are stupid programmers, no matter the language... plus, every mainstream language has a lot of stupid programmers using it :)

Still, if you look at the Chromium code, or the Doom 3 BFG Edition code, it's really neat and readable.

progman
If you need C++ for a living then you have no other option. If you want to enjoy programming then I recommend to stay away from C++. I have written a lot of software in C and C++ in my programming career but C++ is not fun anymore. There are so many (even free) implementations of better languages. For instance C#, Python, Go.

If you want to learn a next generation language right now then you should look at Rust. It seriously has the ability to replace C++ in the long term. C++ will be remembered as the third dino besides Fortran and Cobol.

http://www.rust-lang.org

checker659
You think Rust is beautiful but C++ is ugly? You don't know what you're talking about, do you?
_pmf_
On another note: people claiming "C/C++" skills usually have neither.
hconceic-HN
That is exactly right... It is like they are assuming that by knowing C, then implicitly they know C++. That's tremendously wrong and they will notice that as soon as they work on a non-so-small project.
checker659
But, what about a C++ programmer who knows the quirks of C?
kbart
Not quite. It's fairly common in an embedded world for a system engineer that uses C for low level programming and C++ for application/UI level.
checker659
Why do you say that?
nephorider
By definition C++ is a different language (contrary to Objective-C that was "an extension to C"). It encompasses a lot (nearly all) of C but introduces also new concepts. For example and besides the evident OOP features, all the different types of casting, use of IO stream, default parameters...
dagw
People who know both languages well, also know that they are different enough to not be casually lumped together like that.
guard-of-terra
C++ for C programmers:

RUN

antimagic
Surely that would be BASIC for C programmers?
checker659
I think "Thinking in C++" is a good book for C programmers to get started in C++.
danso
OK I'm going to date myself here...when I studied comsci/CPrE in college, we started out with C and moved to C++ and then to Java. I guess it doesn't speak much for the depth of the classes that I found C++ pretty easy to get into and used it in higher level courses, such as one involving Open GL.

I guess what I'm asking is...who uses just C any more? I can only guess that if, by this point, your main expertise is C and you are still hacking away at it, you're a hacker who is beyond the need for any introductory C++ course and who could probably learn it on your own. If you're a C-person and just want to dabble in a more OOP language to do fun things, why wouldn't you just jump into Python? The world of mostly-and-only-C-programmers seems to be fairly small these days, and the ones who need to get into C++ -- in lieu of what's out there --- seems even smaller

To reiterate my thoughts, here's a review from someone who has read the recommended text book:

http://www.amazon.com/For-Programmers-Third-Edition-3rd/prod...

> I was initially dismayed by the large number of negative reviews, but now that I've completed this book I believe I understand why; this book is really intended for a very narrow target audience: very experienced C programmers with no knowledge of C++ -- i.e., Old Farts,... like me. Is there ANY school out there today teaching people C WITHOUT also teaching them C++? It seems unlikely, almost as unlikely as it would be to find a potential employer out there who is seeking Plain Old C programmers today. So if you are an Old C Dog like me looking to learn the "new" trick of C++, this book is for you and ONLY for you! I read it carefully and was able to pass a C++ test that I wouldn't have gotten a single answer right on before I read it. Anyone else looking to learn C++ would be better served by choosing C++ for Dummies or something similar.

KaeseEs
There are many, many people who use C and rarely or never use C++. Most embedded work is done in C, the Linux and BSD kernels are in C, etc. There are a variety of reasons for this, with audit-ability and debug-ability being two big ones. Code space is also a reason, although there are ways to make C++ mostly behave the way you want it to on all but the teensy tiniest platforms (although the resulting code is sometimes a questionable upgrade over just writing the thing in C). A great number of language interpreters are also written in C rather than C++ (cpython being one of them) - easier bindings are one reason for this.

As another datum, where I went to school the intro to CS data structures and algorithms courses were taught in C++ and the operating systems course was taught in C. In my day to day work I use C and a tiny bit of assembly (more reading than writing).

otikik
"Fly, you fools"
anon1385
>Please use a modern browser with JavaScript enabled to use Coursera.

One wonders how people who can't even create a static HTML page will manage to teach people a complex language like C++.

jmarin
Because this University of California professor runs the entire Coursera website.
anon1385
Well I don't know anything about who this organisation is or who in particular is running the course because I can't view the website!
timdiggerm
Perhaps they want to do things that static HTML can't do?
repsilat
As someone who has taken several Coursera classes (some bad, some very good), the site is a pile of crap. Most pages need far too many round-trips to load, and very few do anything "interesting". On my tablet I sometimes need to refresh pages several times to get them to load "all the way", because some request failed to fire or return or something. It works ok on the desktop, but on the whole it hasn't been thought out very well.

I'm trying to think of a page on their site where doing things "their way" (load a mostly empty page, fetch all the content later) is the right thing to do. Fittingly, I'm drawing a blank.

Quite frankly, I don't understand why people write encyclopedia sized books for CS topics. Firstly, the relevant themes change very quickly. Second, nobody has the time to read a 1000 page book, where one topic just follows the other. Third, after reading the whole book one might realize -- oh how do I use lambda's in C++[1], a new feature introduced recently? If people are buying books to learn lambdas, your entire effort might be rejected because of one topic.

As authors we need to understand that aspiring programmers have the whole web, where easy to read blogs and article surface on a daily basis. Paper books are more of an impulse buy than a self-education commitment. Books are too monotonous and incomplete to compete with the web.

That said, I will be honest and say that I will not buy this book. I will just Google for topics, read a book like Learn * the Hard Way [2] or take one of the Coursera courses [3] to get started. I would encourage you to find new ways to delivering study materials (through video for instance) than just writing a book -- which I personally think is a disruption waiting to happen.

On the other hand, if you succeed in writing a book like [4], then things are different -- you are explaining programming and not a language (syntax, features and caveats).

Good luck!

  [1] http://en.cppreference.com/w/cpp/language/lambda
  [2] http://learnpythonthehardway.org/
  [3] https://www.coursera.org/course/cplusplus4c
  [4] http://mitpress.mit.edu/sicp/
jbn
agreed, most people don't take the time to read such books... that's one reason for the sorry state of the SW industry!
HN Academy is an independent project and is not operated by Y Combinator, Coursera, edX, or any of the universities and other institutions providing courses.
~ [email protected]
;laksdfhjdhksalkfj more things
yahnd.com ~ Privacy Policy ~
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.