8

I've recently started learning C++, and I enjoy it a lot.

I've often read it's easier to write bad code in C++ than in most languages, and that it is a lot deeper than what it seems.

As I'd like to avoid writing bad code, I was wondering what exactly I shouldn't do, and what I should do, to write good code in C++.

DistantEcho
  • 1,196
  • 1
  • 10
  • 14
  • 1
    What C++ books have you read, or are reading? – Fred Nurk Feb 01 '11 at 10:39
  • None yet. I was looking for good books too, but I've found too many of them and now I don't know where to start (http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) – DistantEcho Feb 01 '11 at 10:42
  • Don't get confused with books, I will recommend either Robert Lafore's (http://www.amazon.com/Object-Oriented-Programming-4th-Robert-Lafore/dp/0672323087) or C++ Premier (http://www.amazon.com/dp/0201721481/?tag=stackoverfl08-20) as you will progress by writing more code you yourself will come to know what you should avoid. As you don't know much about C++ i don't think you will be able to understand (Practically) what is being advised to avoid in the answers here. – Ranger Feb 01 '11 at 14:07
  • 3
    When the only tool in your toolbox is C++, everything looks like a thumb.... – CurtisHx Jun 03 '15 at 12:04

6 Answers6

21

The pitfalls

There are so many pitfalls in C++, that if you don't know them you will create very unstable code, with tons of memory leaks and buffer overruns. Compared to more modern languages with garbage collection, you must release all memory yourself. Also, the code is very low-level. There is nothing preventing you from overwriting your own program code (which has been exploited by many IE hacks).

So the next you must learn are the programming practices that mitigate these risks, e.g. using smart pointers to handle freeing objects, wrapping byte arrays in classes handling the data, etc.

I can recommend Scott Meyers' books "Effective C++" and "More Effective C++".

Those books essentially taught me the beauty of C++. Note that these are not beginners books. They assume that you are already familiar with the language.

Pete
  • 8,916
  • 3
  • 41
  • 53
  • 4
    "Accelerated C++" by Koenig and Moo is a good book for new C++ programmers, as it introduced templates and classes by showing examples of use first, then design and creation. I found it easier to understand why to use them with that approach. – Larry Coleman Feb 01 '11 at 13:30
  • I've started reading Effective C++, and it really does help a lot. Thank you ! – DistantEcho Feb 01 '11 at 16:31
  • 2
    "*There is nothing preventing you from overwriting your own program code*" Huh? What? This isn't the fault of the language - indeed, in most operating systems this isn't actually doable unless you actively take steps to make it possible. And poorly written programs are potentially exploitable regardless of the language they're written in. Yes, C++ is low-level and, yes, it has its flaws, but let's not go overboard with nonsense like that. – Nik Bougalis Nov 17 '12 at 04:46
  • @NikBougalis The OS prevents it -- in cases where the OS prevents it -- but C/C++, by design, gives you a method of doing it, in cases where the OS doesn't prevent it; whereas many other languages don't. So it's not really nonsense to characterise this as a language issue -- but I agree the original point is rather overstated. – greggo Sep 05 '14 at 16:50
  • 5
    @greggo it is nonsense - one may as well complain that a coffee mug doesn't protect you from accidentally pouring salt in your coffee. The fact is this: C and C++ don't know anything about your program or the system it's running on. The language could not possibly address the "zomg! my program was overwritten" concern without us first fundamentally altering the underlying assumptions on which the language is built. – Nik Bougalis Sep 06 '14 at 00:15
20

Idioms

C++ supports a great variety of features. Likewise, one can be easily tempted to use it in many different ways or styles. Unfortunately, it doesn't suit many of them well - and thus becomes tedious, error-prone or slow if in such manner.

Or phrased differently, without really knowing what you do, it's incredibly easy to use C++ in a wrong way (which would much better supported in other languages). Plain learning by doing can therefore lead in a wrong direction - so reading good books is probably more important than in other languages (see this post on the same topic).

Java for example is an inherently object-oriented language. You can't program it much different that. In C++ however, you can. You can use it like you'd do in C or Java - and neither way is what C++ excels in, so you'd better stay with C or Java in these cases.

Therefore, you really need to know the proper style and idioms to get C++ right, right from the beginning. Unfortunately, they can be quite complex at first, but here are some - from simple to advanced.

  • Use const
  • Don't worry about micro-optimizations (should I inline a function, << or * etc.?)
  • Refrain from using raw pointer or arrays wherever possible (especially void*). Use references or smart pointers
  • Write generic code = Understand templates
  • Understand headers/code files/preprocessor (but avoid macros)
  • Use the STL (and understand the underlying concepts)!
  • Use boost
  • Get your mind around object lifetime and scope - Manage RAII
  • Don't write object-oriented code (i.e. lots of runtime polymorphism, inheritance) in the first place - there are much better OO languages out there
  • Use objects instead
  • Prefer static polymorphism
  • Use compile-time functions
Dario
  • 1,618
  • 10
  • 13
  • Thanks for the advices. I don't really get why I should avoid writing object-oriented code, though; or did you mean some parts of OOP specifically? – DistantEcho Feb 01 '11 at 16:36
  • 1
    OOP does not solely mean programming with objects, it implies certain design-patterns, runtime polymorphism through inheritance, class hierarchies ... C++ is not really great in expressing these - you need (smart) pointers and often explicit memory management for runtime polymorphism, it's relatively slow and full of pitfalls (ever forgot a virtual destructor?). You often have cleaner ways of expressing the same with pure objects and e.g. generic programming / static polymorphism. – Dario Feb 01 '11 at 18:52
  • 2
    @Niphra: it's not about not using OOP, it's about not restraining yourself to OOP. C++ offers multiple paradigms, and good C++ programs use most, if not all, of them. – Matthieu M. Feb 01 '11 at 18:55
  • 3
    None of these are idioms. The OOP advice is questionable at best and seems to rely on fear rather than any technical reason. – Edward Strange Feb 10 '11 at 18:20
  • "ever forgot a virtual destructor". Yes - important to turn on compiler warnings. Another one: 'function returning a value may not actually return a value' - in a case where the returned value requires a constructor. kaboom. IMHO that warning should be on by default. – greggo Sep 05 '14 at 16:55
13

C++'s power is that it's an awesome language. C++'s drawback is that it's an awesome language. It can be both awe-ful and awful at the same time.

If you want to learn it -- and there's no reason you shouldn't -- you will need to learn it well. You will need to read a lot. There are a few books that will help you on your way: Accelerated C++ will get you started, especially if you do the exercises. Effective C++, Effective STL, Exceptional C++, and their continuing series are among the best in the game for bite-size hints of how to improve your ways of working.

Kaz Dragon
  • 878
  • 5
  • 12
4

I think one thing that will help along your road of good code is experience. For now, just get stuck into the language and don't worry too much about "best coding practices" until you are comfortable enough with it to start looking at ways to improve your usage. You will learn to recognise what's good and what's bad. Once you have the language down, then you can look back and think "ok, I should have implemented this differently", or "this looks messy, how can I improve it?"

I think about it like this: If you learn a new spoken language, you don't dive straight in and learn every single grammatical rule before you start learning simple words or how to say "where is the bus stop?". Programming (IMO) is like a second language (or third, fourth, etc). Treat it like you would any other language and learn by doing. The rest will come with time.

badgerr
  • 395
  • 1
  • 7
1

I've often read it's easier to write bad code in C++ than in most languages, and that it is a lot deeper than what it seems

clarification: in C++ it is easier to write bad code unintentionally than in other languages. You can write bad code in any language but in C++ you set out with the best of intentions but often end up somewhere unexpected because C++ - after you move from "novice" to say "advanced beginner" you get the false impression that C++ is easier than it actually is. But C++ is evolving and all new template libraries make your life easier (and safer).

AndersK
  • 1,016
  • 7
  • 9
  • 2
    This also depends on how you learn C++. If you start learning it as an enhanced C, you're more likely to get yourself into trouble at that stage than if you just learn it as C++. – David Thornley Feb 01 '11 at 15:57
  • Time for the obligatory Stroustrup quote: "C makes it easy to shoot yourself in the foot; C++ makes it harder, but when you do it blows your whole leg off" – Mawg says reinstate Monica Jun 03 '15 at 11:38
-1

Two things:

  1. How does Memory Management work using C++ ?
  2. How does Pointers affect Memory Management in C++ ?
Rachel
  • 767
  • 5
  • 18