C++ for C programmers, part 1 of 2
As Stroustrup said, there’s no such programming language as C/C++. C and C++ are two different beasts.
I’m not going to argue here about which is better. For small or embedded projects, the complexities of C++ can get in the way. For larger projects, some of the features of C++ are very useful.
I’m simply going to list the features C++ adds to C, from an ex-C programmer’s point of view (yes, I was one of those people who believed that C++ was just “C with classes”). The idea is to follow the links to further information if you want to know more about any of them.
This is part 1 of 2, the non-OO features:
- Default arguments to functions: defining
int read(int bufsize =512)
means that if you callread()
without arguments it’s like you calledread(512)
. - Somewhat related is function overloading. You can define a function twice, with two different argument lists. The compiler will use the “closest match” when you call it. For example, defining
int print(int n) {...}
andint print(const char* s) {...}
means you canprint()
both ints and char strings. - The compiler uses ambiguity resolution to resolve all these overloaded functions.
- You can declare local variables wherever in the code you need them, not just at the start of a function (also a C99 feature). This means variables can be declared closer to where you use them. The variable is scoped to the
{...}
block you put it in. - References, as in
int& x
. This isn’t some weird Microsoft-only syntax for smart pointers. I started to think of these as pointers without all the*
‘s, but they’re quite different. An alias is another name for the referred-to object, usually used for pass-by-reference — and unlike pointers, you can call sayswap(x, y)
instead ofswap(&x, &y)
. Aconst
reference means you’re not allowed to change the object it refers to. - Const-correctness in general. This is not just a C++ thing, but C++ folks tend to be stricter about it (usually for good reason).
- A namespace just groups a bunch of names together (functions or variables). C should have had them all along, to avoid everyone having to use their own brand of
mylib_myfunc()
pseudo-namespaces. See also theusing
keyword in its various forms. - The built-in boolean type,
bool
, withtrue
andfalse
keywords (also in C99 viastdbool.h
). - The
inline
keyword and associated quirks, including implicit inlining and auto-inlining. - Most people don’t realise it, but
(not f or n == 5)
is both valid Python and valid C++, thanks to ISO646-style operator keywords. - A much larger standard library than C. The Standard Template Library (STL) is definitely worth knowing, especially the container datatypes like
vector
(growable array) andmap
(associative array), and the STL algorithms such asfind()
andsort()
. C++’s iostreams are just plain weird (I mean, using the bit-shift operators to print stuff out?), but they’re here to stay. Of course, you can still use all of C’s standard library, and if you#include <cstdio>
instead of<stdio.h>
, you’ll get the names in thestd
namespace, as instd::printf()
. - Linking C++ code to C code has several gotchas.
Please send your feedback, and let me know if I’ve missed any non-OO features. The following week’s entry contains the second part describing the object-oriented features C++ has added.
3 May 2010 by Ben 14 comments
14 comments and pings (oldest first)
Talking about gotchas, I prefer the FQA over the FAQ. Quite depressing, but more entertaining.
You might want to consider calling this part “1 of 2”. I was trying to figure out exactly what part one half meant. :-)
Hi !
The tutorial is excellent and is now part of my bookmarks, under the heading of useful tips.
However, i can’t let a comment pass uncommented. :)
The advice of not using new, new[] and their associates delete and delete[] is rather questionable.
C and C++ share the same philosophy of supposing a programmer aware of the risks. The languages usually trade extreme security for extreme performance.
And while malloc()/calloc() and free() should be generally avoided in terms of orthodox C++ programming, sometimes their use is recommended. For instance, when you got to pass a pointer to a C library.
Looking forward to part 2.
[…] Chris Lomont’s Publications page Toshi’s Project Page be nice to your cache bit twiddling hacks A Whirlwind Tutorial on Creating Really Teensy ELF Executables for Linux creating small win32 executables techniques for reducing executable size tiny pe references on coding for optimization on x86 architectures the impossibly fast c++ delegates member function pointers and the fastest possible c++ delegates const illustration in c++ rant on c++’s operator new optimizing c++ (pdf) c++ and the linker hidden features of c++ source code for data structures and algorithm analysis in c c++ for c programmers […]
[…] adds to C, from an ex-C programmer’s point of view. A couple of months ago I wrote part 1, which detailed the non-OO features. This second part details the object-oriented features, though I haven’t given them exactly […]
You might want to mention that `inline’ is also a co-feature with C99.
Thanks for posting this, I have this book, but a lot of things have changed since this book has been published. Thanks again for posting this! :-)
Thanks for posting this information, very helpful when comparing C and C++, thanks again! :-)
[…] C++ for C programmers, part 1 of 2 — the non-object oriented features […]
I would be interested to know why malloc is ‘acceptable’ in C yet frowned upon in C++.
@Geoffrey: in embedded systems, you often don’t use either malloc or free (heap allocation can be dangerous). But to answer your question more generally, here’s a StackOverflow answer on that — basically new is usually better because it’s type safe and calls your constructors.
Your post so is informative. I like C and C++ programming. thanks
You forgot the most important:
Don’t use malloc, free, new[], delete[], or even delete.
Do use std::string, std::vector<>, and smart pointers.