Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

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++.

share|improve this question
    
What C++ books have you read, or are reading? –  Fred Nurk Feb 1 '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 (stackoverflow.com/questions/388242/…) –  Niphra Feb 1 '11 at 10:42
    
Don't get confused with books, I will recommend either Robert Lafore's (amazon.com/Object-Oriented-Programming-4th-Robert-Lafore/dp/…) or C++ Premier (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 1 '11 at 14:07

6 Answers 6

up vote 17 down vote accepted

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.

share|improve this answer
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 1 '11 at 13:30
    
I've started reading Effective C++, and it really does help a lot. Thank you ! –  Niphra Feb 1 '11 at 16:31
    
"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 4:46

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
share|improve this answer
    
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? –  Niphra Feb 1 '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 1 '11 at 18:52
    
@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 1 '11 at 18:55
    
Oh, alright, thank you for clarifying. –  Niphra Feb 1 '11 at 19:17
2  
None of these are idioms. The OOP advice is questionable at best and seems to rely on fear rather than any technical reason. –  Crazy Eddie Feb 10 '11 at 18:20

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.

share|improve this answer

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.

share|improve this answer

Two things:

  1. How does Memory Management work using C++ ?
  2. How does Pointers affect Memory Management in C++ ?
share|improve this answer
    
its much more to c++ than just memory... –  Nazgob Feb 2 '11 at 0:17

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 "advanced beginner" gives the false impression that its easier than it actually is.

share|improve this answer
    
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 1 '11 at 15:57

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.