Mentioned in questions and answers.

This question attempts to collect the few pearls among the dozens of bad C++ books that are published every year.

Unlike many other programming languages, which are often picked up on the go from tutorials found on the Internet, few are able to quickly pick up C++ without studying a well-written C++ book. It is way too big and complex for doing this. In fact, it is so big and complex, that there are very many very bad C++ books out there. And we are not talking about bad style, but things like sporting glaringly obvious factual errors and promoting abysmally bad programming styles.

Please edit the accepted answer to provide quality books and an approximate skill level — preferably after discussing your addition in the C++ chat room. (The regulars might mercilessly undo your work if they disagree with a recommendation.) Add a short blurb/description about each book that you have personally read/benefited from. Feel free to debate quality, headings, etc. Books that meet the criteria will be added to the list. Books that have reviews by the Association of C and C++ Users (ACCU) have links to the review.

Note: FAQs and other resources can be found in the C++ tag info and under . There is also a similar post for C: The Definitive C Book Guide and List

Beginner

Introductory, no previous programming experience

  • Programming: Principles and Practice Using C++ (Bjarne Stroustrup) (updated for C++11/C++14) An introduction to programming using C++ by the creator of the language. A good read, that assumes no previous programming experience, but is not only for beginners.

Introductory, with previous programming experience

  • C++ Primer * (Stanley Lippman, Josée Lajoie, and Barbara E. Moo) (updated for C++11) Coming at 1k pages, this is a very thorough introduction into C++ that covers just about everything in the language in a very accessible format and in great detail. The fifth edition (released August 16, 2012) covers C++11. [Review]

  • A Tour of C++ (Bjarne Stroustrup) (EBOOK) The “tour” is a quick (about 180 pages and 14 chapters) tutorial overview of all of standard C++ (language and standard library, and using C++11) at a moderately high level for people who already know C++ or at least are experienced programmers. This book is an extended version of the material that constitutes Chapters 2-5 of The C++ Programming Language, 4th edition.

  • Accelerated C++ (Andrew Koenig and Barbara Moo) This basically covers the same ground as the C++ Primer, but does so on a fourth of its space. This is largely because it does not attempt to be an introduction to programming, but an introduction to C++ for people who've previously programmed in some other language. It has a steeper learning curve, but, for those who can cope with this, it is a very compact introduction into the language. (Historically, it broke new ground by being the first beginner's book to use a modern approach at teaching the language.) [Review]

  • Thinking in C++ (Bruce Eckel) Two volumes; is a tutorial style free set of intro level books. Downloads: vol 1, vol 2. Unfortunately they’re marred by a number of trivial errors (e.g. maintaining that temporaries are automatically const), with no official errata list. A partial 3rd party errata list is available at (http://www.computersciencelab.com/Eckel.htm), but it’s apparently not maintained.

* Not to be confused with C++ Primer Plus (Stephen Prata), with a significantly less favorable review.

Best practices

  • Effective C++ (Scott Meyers) This was written with the aim of being the best second book C++ programmers should read, and it succeeded. Earlier editions were aimed at programmers coming from C, the third edition changes this and targets programmers coming from languages like Java. It presents ~50 easy-to-remember rules of thumb along with their rationale in a very accessible (and enjoyable) style. For C++11 and C++14 the examples and a few issues are outdated and Effective Modern C++ should be preferred. [Review]

  • Effective Modern C++ (Scott Meyers) This is basically the new version of Effective C++, aimed at C++ programmers making the transition from C++03 to C++11 and C++14.

  • Effective STL (Scott Meyers) This aims to do the same to the part of the standard library coming from the STL what Effective C++ did to the language as a whole: It presents rules of thumb along with their rationale. [Review]

Intermediate

  • More Effective C++ (Scott Meyers) Even more rules of thumb than Effective C++. Not as important as the ones in the first book, but still good to know.

  • Exceptional C++ (Herb Sutter) Presented as a set of puzzles, this has one of the best and thorough discussions of the proper resource management and exception safety in C++ through Resource Acquisition is Initialization (RAII) in addition to in-depth coverage of a variety of other topics including the pimpl idiom, name lookup, good class design, and the C++ memory model. [Review]

  • More Exceptional C++ (Herb Sutter) Covers additional exception safety topics not covered in Exceptional C++, in addition to discussion of effective object oriented programming in C++ and correct use of the STL. [Review]

  • Exceptional C++ Style (Herb Sutter) Discusses generic programming, optimization, and resource management; this book also has an excellent exposition of how to write modular code in C++ by using nonmember functions and the single responsibility principle. [Review]

  • C++ Coding Standards (Herb Sutter and Andrei Alexandrescu) “Coding standards” here doesn't mean “how many spaces should I indent my code?” This book contains 101 best practices, idioms, and common pitfalls that can help you to write correct, understandable, and efficient C++ code. [Review]

  • C++ Templates: The Complete Guide (David Vandevoorde and Nicolai M. Josuttis) This is the book about templates as they existed before C++11. It covers everything from the very basics to some of the most advanced template metaprogramming and explains every detail of how templates work (both conceptually and at how they are implemented) and discusses many common pitfalls. Has excellent summaries of the One Definition Rule (ODR) and overload resolution in the appendices. A second edition is scheduled for 2017. [Review]


Advanced

  • Modern C++ Design (Andrei Alexandrescu) A groundbreaking book on advanced generic programming techniques. Introduces policy-based design, type lists, and fundamental generic programming idioms then explains how many useful design patterns (including small object allocators, functors, factories, visitors, and multimethods) can be implemented efficiently, modularly, and cleanly using generic programming. [Review]

  • C++ Template Metaprogramming (David Abrahams and Aleksey Gurtovoy)

  • C++ Concurrency In Action (Anthony Williams) A book covering C++11 concurrency support including the thread library, the atomics library, the C++ memory model, locks and mutexes, as well as issues of designing and debugging multithreaded applications.

  • Advanced C++ Metaprogramming (Davide Di Gennaro) A pre-C++11 manual of TMP techniques, focused more on practice than theory. There are a ton of snippets in this book, some of which are made obsolete by typetraits, but the techniques, are nonetheless useful to know. If you can put up with the quirky formatting/editing, it is easier to read than Alexandrescu, and arguably, more rewarding. For more experienced developers, there is a good chance that you may pick up something about a dark corner of C++ (a quirk) that usually only comes about through extensive experience.


Reference Style - All Levels

  • The C++ Programming Language (Bjarne Stroustrup) (updated for C++11) The classic introduction to C++ by its creator. Written to parallel the classic K&R, this indeed reads very much alike it and covers just about everything from the core language to the standard library, to programming paradigms to the language's philosophy. [Review]

  • C++ Standard Library Tutorial and Reference (Nicolai Josuttis) (updated for C++11) The introduction and reference for the C++ Standard Library. The second edition (released on April 9, 2012) covers C++11. [Review]

  • The C++ IO Streams and Locales (Angelika Langer and Klaus Kreft) There's very little to say about this book except that, if you want to know anything about streams and locales, then this is the one place to find definitive answers. [Review]

C++11/14 References:

  • The C++ Standard (INCITS/ISO/IEC 14882-2011) This, of course, is the final arbiter of all that is or isn't C++. Be aware, however, that it is intended purely as a reference for experienced users willing to devote considerable time and effort to its understanding. As usual, the first release was quite expensive ($300+ US), but it has now been released in electronic form for $60US.

  • The C++14 standard is available, but seemingly not in an economical form – directly from the ISO it costs 198 Swiss Francs (about $200 US). For most people, the final draft before standardization is more than adequate (and free). Many will prefer an even newer draft, documenting new features that are likely to be included in C++17.

  • Overview of the New C++ (C++11/14) (PDF only) (Scott Meyers) (updated for C++1y/C++14) These are the presentation materials (slides and some lecture notes) of a three-day training course offered by Scott Meyers, who's a highly respected author on C++. Even though the list of items is short, the quality is high.

  • The C++ Core Guidelines (C++11/14/17/…) (edited by Bjarne Stroustrup and Herb Sutter) is an evolving online document consisting of a set of guidelines for using modern C++ well. The guidelines are focused on relatively higher-level issues, such as interfaces, resource management, memory management and concurrency affecting application architecture and library design. The project was announced at CppCon'15 by Bjarne Stroustrup and others and welcomes contributions from the community. Most guidelines are supplemented with a rationale and examples as well as discussions of possible tool support. Many rules are designed specifically to be automatically checkable by static analysis tools.

  • The C++ Super-FAQ (Marshall Cline, Bjarne Stroustrup and others) is an effort by the Standard C++ Foundation to unify the C++ FAQs previously maintained individually by Marshall Cline and Bjarne Stroustrup and also incorporating new contributions. The items mostly address issues at an intermediate level and are often written with a humorous tone. Not all items might be fully up to date with the latest edition of the C++ standard yet.

  • cppreference.com (C++03/11/14/17/…) (initiated by Nate Kohl) is a wiki that summarizes the basic core-language features and has extensive documentation of the C++ standard library. The documentation is very precise but is easier to read than the official standard document and provides better navigation due to its wiki nature. The project documents all versions of the C++ standard and the site allows filtering the display for a specific version. The project was presented by Nate Kohl at CppCon'14.


Classics / Older

Note: Some information contained within these books may not be up-to-date or no longer considered best practice.

  • The Design and Evolution of C++ (Bjarne Stroustrup) If you want to know why the language is the way it is, this book is where you find answers. This covers everything before the standardization of C++.

  • Ruminations on C++ - (Andrew Koenig and Barbara Moo) [Review]

  • Advanced C++ Programming Styles and Idioms (James Coplien) A predecessor of the pattern movement, it describes many C++-specific “idioms”. It's certainly a very good book and might still be worth a read if you can spare the time, but quite old and not up-to-date with current C++.

  • Large Scale C++ Software Design (John Lakos) Lakos explains techniques to manage very big C++ software projects. Certainly a good read, if it only was up to date. It was written long before C++98, and misses on many features (e.g. namespaces) important for large scale projects. If you need to work in a big C++ software project, you might want to read it, although you need to take more than a grain of salt with it. The first volume of a new edition is expected in 2015.

  • Inside the C++ Object Model (Stanley Lippman) If you want to know how virtual member functions are commonly implemented and how base objects are commonly laid out in memory in a multi-inheritance scenario, and how all this affects performance, this is where you will find thorough discussions of such topics.

  • The Annotated C++ Reference Manual (Bjarne Stroustrup, Margaret A. Ellis) This book is quite outdated in the fact that it explores the 1989 C++ 2.0 version - Templates, exceptions, namespaces and new casts were not yet introduced. Saying that however this is book goes through the entire C++ standard of the time explaining the rationale, the possible implementations and features of the language. This is not a book not learn programming principles and patterns on C++, but to understand every aspect of the C++ language.

I've been told by others on numerous occasions that my teacher's advice of exercising using namespace std in code was wrong. Hence, we should use std::cout and std::cin.

Why is using namespace std considered bad practice? Is it really that inefficient or risk declaring ambiguous variables (variables that share the same name as a function in std namespace)? Or, does this impact performance?

Short version: don't use global using declarations or directives in header files. Feel free to use them in implementation files. Here's what Herb Sutter and Andrei Alexandrescu have to say about this issue in C++ Coding Standards (bolding for emphasis is mine):

Summary

Namespace usings are for your convenience, not for you to inflict on others: Never write a using declaration or a using directive before an #include directive.

Corollary: In header files, don’t write namespace-level using directives or using declarations; instead, explicitly namespace-qualify all names. (The second rule follows from the first, because headers can never know what other header #includes might appear after them.)

Discussion

In short: You can and should use namespace using declarations and directives liberally in your implementation files after #include directives and feel good about it. Despite repeated assertions to the contrary, namespace using declarations and directives are not evil and they do not defeat the purpose of namespaces. Rather, they are what make namespaces usable.

It wasn't that long ago that I was a beginning coder, trying to find good books/tutorials on languages I wanted to learn. Even still, there are times I need to pick up a language relatively quickly for a new project I am working on. The point of this post is to document some of the best tutorials and books for these languages. I will start the list with the best I can find, but hope you guys out there can help with better suggestions/new languages. Here is what I found:

Since this is now wiki editable, I am giving control up to the community. If you have a suggestion, please put it in this section. I decided to also add a section for general be a better programmer books and online references as well. Once again, all recommendations are welcome.

General Programming

Online Tutorials
Foundations of Programming By Karl Seguin - From Codebetter, its C# based but the ideas ring true across the board, can't believe no-one's posted this yet actually.
How to Write Unmaintainable Code - An anti manual that teaches you how to write code in the most unmaintable way possible. It would be funny if a lot of these suggestions didn't ring so true.
The Programming Section of Wiki Books - suggested by Jim Robert as having a large amount of books/tutorials on multiple languages in various stages of completion
Just the Basics To get a feel for a language.

Books
Code Complete - This book goes without saying, it is truely brilliant in too many ways to mention.
The Pragmatic Programmer - The next best thing to working with a master coder, teaching you everything they know.
Mastering Regular Expressions - Regular Expressions are an essential tool in every programmer's toolbox. This book, recommended by Patrick Lozzi is a great way to learn what they are capable of.
Algorithms in C, C++, and Java - A great way to learn all the classic algorithms if you find Knuth's books a bit too in depth.

C

Online Tutorials
This tutorial seems to pretty consise and thourough, looked over the material and seems to be pretty good. Not sure how friendly it would be to new programmers though.
Books
K&R C - a classic for sure. It might be argued that all programmers should read it.
C Primer Plus - Suggested by Imran as being the ultimate C book for beginning programmers.
C: A Reference Manual - A great reference recommended by Patrick Lozzi.

C++

Online Tutorials
The tutorial on cplusplus.com seems to be the most complete. I found another tutorial here but it doesn't include topics like polymorphism, which I believe is essential. If you are coming from C, this tutorial might be the best for you.

Another useful tutorial, C++ Annotation. In Ubuntu family you can get the ebook on multiple format(pdf, txt, Postscript, and LaTex) by installing c++-annotation package from Synaptic(installed package can be found in /usr/share/doc/c++-annotation/.

Books
The C++ Programming Language - crucial for any C++ programmer.
C++ Primer Plus - Orginally added as a typo, but the amazon reviews are so good, I am going to keep it here until someone says it is a dud.
Effective C++ - Ways to improve your C++ programs.
More Effective C++ - Continuation of Effective C++.
Effective STL - Ways to improve your use of the STL.
Thinking in C++ - Great book, both volumes. Written by Bruce Eckel and Chuck Ellison.
Programming: Principles and Practice Using C++ - Stroustrup's introduction to C++.
Accelerated C++ - Andy Koenig and Barbara Moo - An excellent introduction to C++ that doesn't treat C++ as "C with extra bits bolted on", in fact you dive straight in and start using STL early on.

Forth

Books
FORTH, a text and reference. Mahlon G. Kelly and Nicholas Spies. ISBN 0-13-326349-5 / ISBN 0-13-326331-2. 1986 Prentice-Hall. Leo Brodie's books are good but this book is even better. For instance it covers defining words and the interpreter in depth.

Java

Online Tutorials
Sun's Java Tutorials - An official tutorial that seems thourough, but I am not a java expert. You guys know of any better ones?
Books
Head First Java - Recommended as a great introductory text by Patrick Lozzi.
Effective Java - Recommended by pek as a great intermediate text.
Core Java Volume 1 and Core Java Volume 2 - Suggested by FreeMemory as some of the best java references available.
Java Concurrency in Practice - Recommended by MDC as great resource for concurrent programming in Java.

The Java Programing Language

Python

Online Tutorials
Python.org - The online documentation for this language is pretty good. If you know of any better let me know.
Dive Into Python - Suggested by Nickola. Seems to be a python book online.

Perl

Online Tutorials
perldoc perl - This is how I personally got started with the language, and I don't think you will be able to beat it.
Books
Learning Perl - a great way to introduce yourself to the language.
Programming Perl - greatly referred to as the Perl Bible. Essential reference for any serious perl programmer.
Perl Cookbook - A great book that has solutions to many common problems.
Modern Perl Programming - newly released, contains the latest wisdom on modern techniques and tools, including Moose and DBIx::Class.

Ruby

Online Tutorials
Adam Mika suggested Why's (Poignant) Guide to Ruby but after taking a look at it, I don't know if it is for everyone. Found this site which seems to offer several tutorials for Ruby on Rails.
Books
Programming Ruby - suggested as a great reference for all things ruby.

Visual Basic

Online Tutorials
Found this site which seems to devote itself to visual basic tutorials. Not sure how good they are though.

PHP

Online Tutorials
The main PHP site - A simple tutorial that allows user comments for each page, which I really like. PHPFreaks Tutorials - Various tutorials of different difficulty lengths.
Quakenet/PHP tutorials - PHP tutorial that will guide you from ground up.

JavaScript

Online Tutorials
Found a decent tutorial here geared toward non-programmers. Found another more advanced one here. Nickolay suggested A reintroduction to javascript as a good read here.

Books
Head first JavaScript
JavaScript: The Good Parts (with a Google Tech Talk video by the author)

C#

Online Tutorials
C# Station Tutorial - Seems to be a decent tutorial that I dug up, but I am not a C# guy.
C# Language Specification - Suggested by tamberg. Not really a tutorial, but a great reference on all the elements of C#
Books
C# to the point - suggested by tamberg as a short text that explains the language in amazing depth

ocaml

Books
nlucaroni suggested the following:
OCaml for Scientists Introduction to ocaml
Using Understand and unraveling ocaml: practice to theory and vice versa
Developing Applications using Ocaml - O'Reilly
The Objective Caml System - Official Manua

Haskell

Online Tutorials
nlucaroni suggested the following:
Explore functional programming with Haskell
Books
Real World Haskell
Total Functional Programming

LISP/Scheme

Books
wfarr suggested the following:
The Little Schemer - Introduction to Scheme and functional programming in general
The Seasoned Schemer - Followup to Little Schemer.
Structure and Interpretation of Computer Programs - The definitive book on Lisp (also available online).
Practical Common Lisp - A good introduction to Lisp with several examples of practical use.
On Lisp - Advanced Topics in Lisp
How to Design Programs - An Introduction to Computing and Programming
Paradigms of Artificial Intelligence Programming: Case Studies in Common Lisp - an approach to high quality Lisp programming

What about you guys? Am I totally off on some of there? Did I leave out your favorite language? I will take the best comments and modify the question with the suggestions.

Java: SCJP for Java 6. I still use it as a reference.

Haskell:

O'Reilly Book:

  1. Real World Haskell, a great tutorial-oriented book on Haskell, available online and in print.

My favorite general, less academic online tutorials:

  1. The Haskell wikibook which contains all of the excellent Yet Another Haskell Tutorial. (This tutorial helps with specifics of setting up a Haskell distro and running example programs, for example.)
  2. Learn you a Haskell for Great Good, in the spirit of Why's Poignant Guide to Ruby but more to the point.
  3. Write yourself a Scheme in 48 hours. Get your hands dirty learning Haskell with a real project.

Books on Functional Programming with Haskell:

  1. Lambda calculus, combinators, more theoretical, but in a very down to earth manner: Davie's Introduction to Functional Programming Systems Using Haskell
  2. Laziness and program correctness, thinking functionally: Bird's Introduction to Functional Programming Using Haskell

Some books on Java I'd recommend:

For Beginners: Head First Java is an excellent introduction to the language. And I must also mention Head First Design Patterns which is a great resource for learners to grasp what can be quite challenging concepts. The easy-going fun style of these books are ideal for ppl new to programming.

A really thorough, comprehensive book on Java SE is Bruce Eckel's Thinking In Java v4. (At just under 1500 pages it's good for weight-training as well!) For those of us not on fat bank-bonuses there are older versions available for free download.

Of course, as many ppl have already mentioned, Josh Bloch's Effective Java v2 is an essential part of any Java developer's library.

Let's not forget Head First Java, which could be considered the essential first step in this language or maybe the step after the online tutorials by Sun. It's great for the purpose of grasping the language concisely, while adding a bit of fun, serving as a stepping stone for the more in-depth books already mentioned.

Sedgewick offers great series on Algorithms which are a must-have if you find Knuth's books to be too in-depth. Knuth aside, Sedgewick brings a solid approach to the field and he offers his books in C, C++ and Java. The C++ books could be used backwardly on C since he doesn't make a very large distinction between the two languages in his presentation.

Whenever I'm working on C, C:A Reference Manual, by Harbison and Steele, goes with me everywhere. It's concise and efficient while being extremely thorough making it priceless(to me anyways).

Languages aside, and if this thread is to become a go-to for references in which I think it's heading that way due to the number of solid contributions, please include Mastering Regular Expressions, for reasons I think most of us are aware of... some would also say that regex can be considered a language in its own right. Further, its usefulness in a wide array of languages makes it invaluable.

C: “Programming in C”, Stephen G. Kochan, Developer's Library.

Organized, clear, elaborate, beautiful.

C++

The first one is good for beginners and the second one requires more advanced level in C++.

I know this is a cross post from here... but, I think one of the best Java books is Java Concurrency in Practice by Brian Goetz. A rather advanced book - but, it will wear well on your concurrent code and Java development in general.

C#

C# to the Point by Hanspeter Mössenböck. On a mere 200 pages he explains C# in astonishing depth, focusing on underlying concepts and concise examples rather than hand waving and Visual Studio screenshots.

For additional information on specific language features, check the C# language specification ECMA-334.

Framework Design Guidelines, a book by Krzysztof Cwalina and Brad Abrams from Microsoft, provides further insight into the main design decisions behind the .NET library.

For Lisp and Scheme (hell, functional programming in general), there are few things that provide a more solid foundation than The Little Schemer and The Seasoned Schemer. Both provide a very simple and intuitive introduction to both Scheme and functional programming that proves far simpler for new students or hobbyists than any of the typical volumes that rub off like a nonfiction rendition of War & Peace.

Once they've moved beyond the Schemer series, SICP and On Lisp are both fantastic choices.

For C++ I am a big fan of C++ Common Knowledge: Essential Intermediate Programming, I like that it is organized into small sections (usually less than 5 pages per topic) So it is easy for me to grab it and read up on concepts that I need to review.

It is a must read for me the night before and on the plane to a job interview.

C Primer Plus, 5th Edition - The C book to get if you're learning C without any prior programming experience. It's a personal favorite of mine as I learned to program from this book. It has all the qualities a beginner friendly book should have:

  • Doesn't assume any prior exposure to programming
  • Enjoyable to read (without becoming annoying like For Dummies /
  • Doesn't oversimplify

For Javascript:

For PHP:

For OO design & programming, patterns:

For Refactoring:

For SQL/MySQL:

  • C - The C Programming Language - Obviously I had to reference K&R, one of the best programming books out there full stop.
  • C++ - Accelerated C++ - This clear, well written introduction to C++ goes straight to using the STL and gives nice, clear, practical examples. Lives up to its name.
  • C# - Pro C# 2008 and the .NET 3.5 Platform - Bit of a mouthful but wonderfully written and huge depth.
  • F# - Expert F# - Designed to take experienced programmers from zero to expert in F#. Very well written, one of the author's invented F# so you can't go far wrong!
  • Scheme - The Little Schemer - Really unique approach to teaching a programming language done really well.
  • Ruby - Programming Ruby - Affectionately known as the 'pick axe' book, this is THE defacto introduction to Ruby. Very well written, clear and detailed.

Could someone point me to an article, or write some tips right here about some c++ programming habits that are generally valid (no real drawbacks) and improves performance? I do not mean programming patterns and algorithm complexity - I need small things like how you define your functions, things to do/to avoid in loops, what to allocate on the stack, what on the heap, and so on.

It's not about making a particular software faster, also it's not about how to create a clean software design, but rather programming habits that - if you always apply them, you will make your code rather a little bit faster than a little bit slower.

Thanks :)

I took the habit to prefer writing ++i rather than i++ not that it brings any performance boost when i is an int but things are different when i is an iterator which might have a complex implementation.

Then let's say you come from the C programming language, lose your habit to declare all your variables at the beginning on the function: declare your variables when they are needed in the function flow since the function might contain early return statements before some variables that were initialized at the beginning are effectively used.

Apart from that, another resource is C++ Coding Standards: 101 Rules, Guidelines, and Best Practices by Herb Sutter (him again) and Alexei Alexandrescu.

There is also a more recent edition of Scott Meyers' Effective C++: Effective C++: 55 specific ways to improve your programs and designs.

Finally, I would like to mention Tony Albrecht's Pitfalls of Object Oriented Programming presentation: not that it contains rules of thumb you can follow blindly but it's a very interesting read.

A number of the tips in Effective C++, More Effective C++, Effective STL and C++ Coding Standards are along this line.

A simple example of such a tip: use preincrement (++i) rather than postincrement (i++) when possible. This is especially important with iterators, as postincrement involves copying the iterator. You optimizer may be able to undo this, but it isn't any extra work to write preincrement instead, so why take the risk?

What's the convention for naming functions in C++?

I come from the java environment so I usually name something like:

myFunction(...){
}

I've seen mixed code in C++,

myFunction(....)
MyFunction(....)
Myfunction(....)

what's the correct way?

Also, is it the same for a class function and for a function that's not a class function?

Unlike Java, C++ doesn't have a "standard style". Pretty much very company I've ever worked at has its own C++ coding style, and most open source projects have their own styles too. A few coding conventions you might want to look at:

It's interesting to note that C++ coding standards often specify which parts of the language not to use. For example, the Google C++ Style Guide says "We do not use C++ exceptions". Almost everywhere I've worked has prohibited certain parts of C++. (One place I worked basically said, "program in C, but new and delete are okay"!)

I'm in the process of changing part of my C++ app from using an older C type array to a templated C++ container class. See this question for details. While the solution is working very well, each minor change I make to the templated code causes a very large amount of recompilation to take place, and hence drastically slows build time. Is there any way of getting template code out of the header and back into a cpp file, so that minor implementation changes don't cause major rebuilds?

First of all, for completeness, I'll cover the straightforward solution: only use templated code when necessary, and base it on non-template code (with implementation in its own source file).

However, I suspect that the real issue is that you use generic programming as you would use typical OO-programming and end up with a bloated class.

Let's take an example:

// "bigArray/bigArray.hpp"

template <class T, class Allocator>
class BigArray
{
public:
  size_t size() const;

  T& operator[](size_t index);
  T const& operator[](size_t index) const;

  T& at(size_t index);
  T const& at(size_t index);

private:
  // impl
};

Does this shock you ? Probably not. It seems pretty minimalist after all. The thing is, it's not. The at methods can be factored out without any loss of generality:

// "bigArray/at.hpp"

template <class Container>
typename Container::reference_type at(Container& container,
                                      typename Container::size_type index)
{
  if (index >= container.size()) throw std::out_of_range();
  return container[index];
}

template <class Container>
typename Container::const_reference_type at(Container const& container,
                                            typename Container::size_type index)
{
  if (index >= container.size()) throw std::out_of_range();
  return container[index];
}

Okay, this changes the invocation slightly:

// From
myArray.at(i).method();

// To
at(myArray,i).method();

However, thanks to Koenig's lookup, you can call them unqualified as long as you put them in the same namespace, so it's just a matter of habit.

The example is contrived but the general point stands. Note that because of its genericity at.hpp never had to include bigArray.hpp and will still produce as tight code as if it were a member method, it's just that we can invoke it on other containers if we wish.

And now, a user of BigArray does not need to include at.hpp if she does not uses it... thus reducing her dependencies and not being impacted if you change the code in that file: for example alter std::out_of_range call to feature the file name and line number, the address of the container, its size and the index we tried to access.

The other (not so obvious) advantage, is that if ever integrity constraint of BigArray is violated, then at is obviously out of cause since it cannot mess with the internals of the class, thus reducing the number of suspects.

This is recommended by many authors, such as Herb Sutters in C++ Coding Standards:

Item 44: Prefer writing nonmember nonfriend functions

and has been extensively used in Boost... But you do have to change your coding habits!

Then of course you need to only include what you do depend on, there ought to be static C++ code analyzers that report included but unused header files which can help figuring this out.

I come from a the Objective-C and Cocoa world where there are lots of conventions and many people will say it makes your code beautiful! Now programming in C++ I cannot find a good document like this one for C++.

http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/CodingGuidelines/CodingGuidelines.html

Standard C++ probably does not have something like above but I hope I can stick to some other SDK or APIs (like Microsoft's(?),etc) conventions.

I hope you can provide me with some links.

We follow the guidelines listed on this page: C++ Programming Style Guidelines


I'd also recommend you read The Elements of C++ Style by Misfeldt et al, which is quite an excellent book on this topic.

not nearly as concise as the link you provided: but the following chapter 14 - 24 may help :) hehe

ref: http://www.amazon.com/Coding-Standards-Rules-Guidelines-Practices/dp/0321113586/ref=sr_1_1?ie=UTF8&s=books&qid=1284443869&sr=8-1-catcorr

If I have a C++ method declaration as follows:

class A
{
public:
   double getPrice() volatile;
};
  1. What does volatile represent here?
  2. What could it be used for?

You might be interested in this Dr Dobbs article by Andrei Alexandrescu. I was :)

Edit: That article was written a while back and now it seems that the community has moved on. Herb Sutter has this to say this. Thanks Iain (and Herb!)

mlimber points out that Andrei had a follow up article here where he continues to advocate the use of volatile correctness as a valuable tool for detecting race conditions on systems supporting POSIX-like mutexes.

You're probably familiar with const methods and const-correctness (cf. "Item 15 - Use const proactively" in C++ Coding Standards by Sutter and Alexandrescu), and volatile works in similar but slightly different ways to yield what might be called "volatile-correctness."

Like const, volatile is a type modifier. When attached to a member function as in your example, either modifier (or both!) mean that the object on which the method is called must have or be convertible to that type.

Consider:

struct A
{
  void f();
  void cf() const;
  void vf() volatile;
  void cvf() const volatile;
  // ...
};

void foo( A& a, const A& ca, volatile A& va, const volatile A& cva )
{
  a.f();    // Ok
  a.cf();   // Ok: Can convert non-const    obj to const    obj
  a.vf();   // Ok: Can convert non-volatile obj to volatile obj
  a.cvf();  // Ok: Can convert non-cv       obj to cv       obj

  ca.f();   // Error: can't call non-const method on const obj
  ca.cf();  // Ok
  ca.vf();  // Error: can't call non-const method on const obj
  ca.cvf(); // Ok: Can convert

  va.f();   // Error: can't call non-volatile method on volatile obj
  va.cf();  // Error: can't call non-volatile method on volatile obj
  va.vf();  // Ok
  va.cvf(); // Ok: Can convert

  cva.f();   // Error: can't call non-cv method on cv obj
  cva.cf();  // Error: can't call non-cv method on cv obj
  cva.vf();  // Error: can't call non-cv method on cv obj
  cva.cvf(); // Ok
}

Note these are compile-time errors, not run-time errors, and that is where it's potential usefulness comes in.

Const-correctness prevents unintentional errors at compile-time as well as making code "easier to understand, track, and reason about" (Sutter and Alexandrescu). Volatile-correctness can function similarly but is much less used (note that const_cast in C++ can cast away const, volatile, or const volatile, but rather than calling it cv_cast or similar, it's named after const alone because it is far more commonly used for casting away just const).

For instance, in "volatile - Multithreaded Programmer's Best Friend", Andrei Alexandrescu gives some examples of how this can be used to have the compiler automatically detect race conditions in multithreaded code. It has plenty of explanation about how type modifiers work, too, but see also his follow-up comments in his subsequent column.


Update:

Note that C++11 changes the meaning of const. Thus sayeth the Sutter: "const now really does mean 'read-only, or safe to read concurrently'—either truly physically/bitwise const, or internally synchronized so that any actual writes are synchronized with any possible concurrent const accesses so the callers can’t tell the difference."

Elsewhere, he notes that while C++11 has added concurrency primitives, volatile is still not one of them: "C++ volatile variables (which have no analog in languages like C# and Java) are always beyond the scope of this and any other article about the memory model and synchronization. That’s because C++ volatile variables aren’t about threads or communication at all and don’t interact with those things. Rather, a C++ volatile variable should be viewed as portal into a different universe beyond the language — a memory location that by definition does not obey the language’s memory model because that memory location is accessed by hardware (e.g., written to by a daughter card), have more than one address, or is otherwise 'strange' and beyond the language. So C++ volatile variables are universally an exception to every guideline about synchronization because are always inherently “racy” and unsynchronizable using the normal tools (mutexes, atomics, etc.) and more generally exist outside all normal of the language and compiler including that they generally cannot be optimized by the compiler.... For more discussion, see my article 'volatile vs. volatile.'"

I've got about 2/3 years C++ experience but I've spent most of my career doing Java. I'm about to go for an interview for a C++ programming role and I've been thinking about the best way to brush up my C++ to make sure I don't get caught out by any awkward questions. What would you recommend?

The following have been proposed for an upcoming C++ project.

  • C++ Coding Standards, by Sutter and Alexandrescu
  • JSF Air Vehicle C++ coding standards
  • The Elements of C++ Style
  • Effective C++ 3rd Edition, by Scott Meyers

Are there other choices? Or is the list above what be should used on a C++ project?

Some related links

I've written a coding standard for a major British company and was very conscious of putting reasons why I selected certain things rather than just make it a bunch of "Thou shalt" pronouncements. (-:

As a quick way out, I'd suggest mandating:

  • Scott Meyers's Effective C++ 3rd Edition (Amazon link) - if you can find a copy of the 1st edition of this book then buy it for the overview of OO design which was removed from later editions. )-:
  • Scott Meyer's book Effective STL (Amazon link) - you must use STL to use C++ efficiently.
  • Steve McConnell's book Code Complete 2 (Amazon link) - not C++ specific but full of great insights.

C++ Coding Standards: 101 Rules, Guidelines, and Best Practices (C++ In-Depth Series) by Herb Sutter and, Andrei Alexandrescu.

I recently forced myself to study C++ and I just finished reading the book C++: The Complete Reference, by Herbert Schildt. I liked the book and think I got more or less the big picture. I noticed though that when I try to check with other people the things I code using the material I learned, they are usually considered non-idiomatic and superseded by an STL way to do it that is safer and easier (well, the book doesn't cover STL and Boost libraries).

So I'd like to ask: what are good sources to learn the patterns of a good C++ program? Where can I learn basic patterns from the "C++ way" to do things and not just repeating C patterns in C++?

I'd be particularly interested in sources that included STL and Boost stuff.

I'd (also) recommend:

  • Effective C++, Effective STL by Steve Myers. They are easy to digest, yet very valuable - sometimes even illuminating.
  • Code Complete (The 1993 edition is available cheaply and not that much different). It's lengthy, but it walks across the entire field from what it means to be a programmer to how a for loop should look. (It would be better if it was shorter - the way it is it covers so much ground it's hard to place it). I hold it dear because it illustrate two points very well:
    • code is compromise
    • There are know facts, (but we still manage to get by by gut feel)
  • C++ FAQ Lite / C++ FAQ.
  • I'd throw in Facts and Fallacies by Robert Glass - it doesn't fit your request very well, but go read it.

It's natural that you are unhappy with other people's code. That's typical for programming - heck, even my own code of five years ago was written by a total n00b. That might be more articulated for C++, since it caters for different styles, and often puts freedom ("you can") over guildelines ("that's the way").

Still, mulling over existing code - yours or others - and considering how it can be improved. Also, figuring out why it is the way it is sometimes helps.


(I remember a few TheDailyWTF's where everyone would chime in how stupid and unreasonable this is - yet somewhere, buried among the me too's, was someone with domain experience explaining convincingly under what circumstances this was better than the obvious solution).

You might wnat to check out The Definitive C++ Book Guide and List

For your purposes I would especially recommend:

They are not in particular order, also you might want to read and code something in between them.

(Note: As noted by @John Dibling the Boost book might be a bit out of date, I do not have experience with that one myself)

One of the most common mantras in computer science and programming is to never optimize prematurely, meaning that you should not optimize anything until a problem has been identified, since code readability/maintainability is likely to suffer.

However, sometimes you might know that a particular way of doing things will perform poorly. When is it OK to optimize before identifying a problem? What sorts of optimizations are allowable right from the beginning?

For example, using as few DB connections as possible, and paying close attention to that while developing, rather than using a new connection as needed and worrying about the performance cost later

Item #9 from Sutter and Alexandrescu's C++ Coding Standards: 101 Rules, Guidelines, and Best Practices (amazon) is "Don’t pessimize prematurely".

This means you should do things like

void foo(const std::wstring& str) {...}

from the beginning, rather than write

void foo(std::wstring str) {...}

only to change it later during some "optimization phase".

template <class T>
void max (T &a ,T &b)
{}//generic template   #1

template<> void max(char &c, char &d)
{} //template specializtion    #2

void max (char &c, char &d)
{}//ordinary function      #3

what is difference between 1 ,2, and 3?

  1. is a template function
  2. is a total specialization of the previous template function (doesn't overload!)
  3. is an overload of the function

Here is an excerpt from C++ Coding Standards: 101 Rules, Guidelines, and Best Practices:

66) Don't specialize function templates

Function template specializations never participate in overloading: Therefore, any specializations you write will not affect which template gets used, and this runs counter to what most people would intuitively expect. After all, if you had written a nontemplate function with the identical signature instead of a function template specialization, the nontemplate function would always be selected because it's always considered to be a better match than a template.

The book advises you to add a level of indirection by implementing the function template in terms of a class template:

#include <algorithm>

template<typename T>
struct max_implementation
{
  T& operator() (T& a, T& b)
  {
    return std::max(a, b);
  }
};

template<typename T>
T& max(T& a, T& b)
{
  return max_implementation<T>()(a, b);
}

See also:

There are a couple of questions on Stackoverflow on whether there is any research or studies into what is the best coding convention/style. That's not what this question is about. This question is about whether there are any studies that research whether there are any advantages, productivity gains or other positive side effects to having an organization-wide coding convention and style.

I have my own opinions on this, which is basically that there is huge benefits to having such standards in place. Honestly, I couldn't care less what style I am required to use as long as it is consistent in all the code I might have to work with.

I just want to know if there are any studies that back my opinions or contradict them.

There have been several studies showing that a strict adherence to a consistent visual style helps experienced programmers keep more of the local problem in memory without having to memorize the individual elements of the problem.

Consistent Coding Style Aids Chunking

It has to do with how the human memory works. It is called chunking. For example, it is a well-studied phenomenon that chess masters are much better at memorizing chess positions than people who are not familiar with the game. But that is only if the pieces occur in "natural positions" that can occur in a normal game. If you place the chess pieces in random positions, chess masters are no better off than non-chess players at memorizing board positions.

The same concept applies to programmers. When coding styles are consistent, the coding constructs appear "natural" to the programmer and larger portions of the code are easier to assimilate. Our short term memory has a capacity of about "seven plus-or-minus two" chunks so, the larger those familiar chunks are, the more raw data our mind can actively hold in memory (George Miller).

When faced with randomly-formatted code, programmers have to expend addition mental energy to manually parse out the individual pieces of the problem they are working on. That takes away from the ability to hold larger pieces of the problem in memory to work on it. It also means that it takes longer to reach a point where the programmer is productively solving the problem at hand.

Flow Time

Have you ever found that a problem seems so clear while you continue to work on it but then you seem to "lose the information" when you come back to the problem later; i.e. break your flow time? Flow time is well-documented in Peopleware (a must read for all programmers). Flow time is when programmers get a large majority of work done and is only achieved when you are working on a problem for an extended, uninterupted period of time. That is because it takes a certain period of time for a programmer to assimilate enough of the problem into cognitive memory to effectively work on the problem. Well-formatted code helps our visual image processing which means programmers reach flow time much faster.

I have authored coding standards at several software companies. It is unfortunate how many programmers feel that coding standards are just a means of asserting unneeded control over how they do things; a form of creative censorship. Truth be told, it rarely matters what the actual standards are. The value is in getting everyone on a team to be consistent, even if it means making an often-arbitrary decision between doing it my way or doing it your way.

Here are a few reference I mentioned above:

The place I gained the most insight on the issue:

C++ Coding Standards: 101 Rules, Guidelines, and Best Practices (Sutter, Alexandrescu)

It's worth reading even if you aren't working in C++.

Background:

An art teacher once gave me a design problem to draw a tiger using only 3 lines. The idea being that I study a tiger and learn the 3 lines to draw for people to still be able to tell it is a tiger.

The solution for this problem is to start with a full drawing of a tiger and remove elements until you get to the three parts that are most recognizable as a tiger.

I love this problem as it can be applied in multiple disciplines like software development, especially in removing complexity.

At work I deal with maintaining a large software system that has been hacked to death and is to the point of becoming unmaintainable. It is my job to remove the burdensome complexity that was caused by past developers.

Question:

Is there a set process for removing complexity in software systems - a kind of reduction process template to be applied to the problem?

This is a loaded question :-)

First, how do we measure "complexity"? Without any metric decided apriori, it may be hard to justify any "reduction" project.

Second, is the choice entirely yours? If we may take an example, assume that, in some code base, the hammer of "inheritance" is used to solve every other problem. While using inheritance is perfectly right for some cases, it may not be right for all cases. What do you in such cases?

Third, can it be proved that behavior/functionality of the program did not change due to refactoring? (This gets more complex when the code is part of a shipping product.)

Fourth, you can start with start with simpler things like: (a) avoid global variables, (b) avoid macros, (c) use const pointers and const references as much as possible, (d) use const qualified methods wherever it is the logical thing to do. I know these are not refactoring techniques, but I think they might help you proceed towards your goal.

Finally, in my humble opinion, I think any such refactoring project is more of people issue than technology issue. All programmers want to write good code, but the perception of good vs. bad is very subjective and varies across members in the same team. I would suggest to establish a "design convention" for the project (Something like C++ Coding Standards). If you can achieve that, you are mostly done. The remaining part is modify the parts of code which does not follow the design convention. (I know, this is very easy to say, but much difficult to do. Good wishes to you.)

Checkout the book, Working Effectively with Legacy Code

The topics covered include

  • Understanding the mechanics of software change: adding features, fixing bugs, improving design, optimizing performance
  • Getting legacy code into a test harness
  • Writing tests that protect you against introducing new problems
  • Techniques that can be used with any language or platform—with examples in Java, C++, C, and C#
  • Accurately identifying where code changes need to be made
  • Coping with legacy systems that aren't object-oriented
  • Handling applications that don't seem to have any structure

This book also includes a catalog of twenty-four dependency-breaking techniques that help you work with program elements in isolation and make safer changes.

Check out the book Anti-Patterns for a well-written book on the whole subject of moving from bad (or maladaptive) design to better. It provides ways to recover from a whole host of problems typically found in software systems. I would then add support to Kristopher's recommendation of Refactoring as an important second step.

So, I have the following in a specification file

#include <string>
#include <fstream>
using namespace std:

class MyStuff
{
    private:

    string name;
    fstream file;
    // other stuff

    public:
    void setName(string);
}

I also have in the implementation file

#include "MyStuff.h"
using namespace std;

void MyStuff::setName(string name);
{
     name = name
}

and in the program file I have...

#include <iostream>
#include <string>
using namespace std;

void main()
{
     string name;
     MyStuff Stuff;

     cout << "Enter Your Name: ";
     getline(cin, name);

     Stuff.setName(name);
}

And I'm gathering that applying "using namespace std;" in a header file is a no-no, and that to fully qualify is the "better" practice; such as std::cout << stuff << endl;

It is my understanding that in order to use a string, it must have the std namespace. Is that true?

If so, in the header file, is more "pure/clean" to do it as...

#include <string>

class MyStuff
{
     std::string name;
}

And, as I understand it currently, using namespace std; across all three files, specification, implementation, and program, essentially layers the three namespaces on top of each other, so if I separately declare string name; within each of the files, the compiler will not know which goes to what. Is that true?

I generally understand that being clear is a "good" thing to do, I am however a little unclear on the specificity of how, and I'm most interested in the deeper "why" that underlies it all.

So my direct question is, in my example provided, what is the "clearest" way to describe the function both for the compiler and for industry "standard"? And, can you direct me to resources that more clearly delineate the reasoning and practical implementation of namespaces.

Namespace usings are for your convenience, not for you to inflict on others: Never write a using declaration or a using directive before an #include directive.

Corollary: In header files, don't write namespace-level using directives or using declarations; instead, explicitly namespace-qualify all names. (The second rule follows from the first, because headers can never know what other header #includes might appear after them.)

I generally understand that being clear is a "good" thing to do, I am however a little unclear on the specificity of how, and I'm most interested in the deeper "why" that underlies it all.

Below code snippets reflects why use using namespace in header file is bad:

// snippet 1
namespace A {
 int f(double);
}

// snippet 2
namespace B {  
    using A::f;
    void g();
}

// snippet 3
namespace A {
    int f(int);
}

// snippet 4
void B::g() {
    f(1);   // which overload is called?
}

So in your example, simply this one is better:

#include <string>

class MyStuff
{
    std::string name;
};

Recommend book: C++ Coding Standards: 101 Rules, Guidelines, and Best Practices

and link: Google C++ coding guide

I haven't touch C++ in more then 8 years. I recently had to do fix some C++ code, and although I still can code, I feel like I no more belongs to the camp of C++ programmers. I don't know any libraries, didn't pay attention to the new language features / improvements / best practices.

Qt Creator and Qt seems like a nice toolset for what I need now, since I'm interested mostly in cross platform development.

What would be good resources for someone like me to quickly re-learn C++ and best practices in shortest period of time?

I have been doing mostly java and common lisp in the meantime, with a short strides to C, flex, Scala and Haskell.

Read :

Those are references books on C++ that resume all the modern effective pratices, philosophies and knowledge on C++ (without going into Meta-Programmation stuff).

Then if you want to go farther, read :

About libraries: first learn about the STL and learn to use Boost as a "standard" STL extension.

I've just begun looking at the phobos source, and it's littered with several different styles and commented out code.

The style guide on the web side is very small, and I only found broken links from 2006 and another one from 2004...

Is there a newer, more comprehensive guide available?

PS: Originally asked at the D.learn newsgroup, but as I didn't get any answers, I thought I might try here even though it might be a shot in the dark

Whatever guide exists is out of date and shouldn't exist anymore. I don't believe that there is any sort of D style guide which is considered valid, and I don't think that Walter Bright, Andrei Alexandrescu, etc. want there to be one. Also, as I recall, in C++ Coding Standards: 101 Rules, Guidelines, and Best Practices, Herb Sutter and Andrei said that style guides were a bad idea (or at least that really specific ones were), but I'd have to pull out the book to be sure of exactly what they said. So I rather doubt that Phobos (which Andrei is in charge of) would have any kind of style guide; I'm certainly not aware of any. There may be some sort of guidelines for formatting code that goes into Phobos (like making your code look similar to the rest of the module or somesuch), but someone like Andrei or one of the other Phobos developers would have to answer that. Certainly, with about 15 different developers working on Phobos, you're bound to get several different styles in the code if there is no enforced style guide.

So, I don't believe that there really is any kind of recommended coding style for either D or Phobos. As I understand it, the main folks behind D aren't particularly in favor of style guides, and they certainly haven't pushed one. So, there isn't really one right now, and I don't expect there to be one in the future.

EDIT: Okay, I went and looked up exactly what Herb Sutter and Anderi Alexandrescu said in C++ Coding Standards: 101 Rules, Guidelines, and Best Practices. It's not exactly that they're against coding standards so much as they're against particularly restrictive ones which enforce personal tastes or obsolete practices. I'm not going to quote the whole thing here (it's a good book, and you should probably pick it up anyway), but here are some key points.

  • Don't specify how much to indent, but do indent to show structure.
  • Don't enforce a specific line length, but do keep line lengths readable.
  • Don't overlegislate naming, but do us a consistent naming convention.
  • Don't precsribe commenting styles (except where tools extract certain styles into documentation), but do write useful comments.

Some examples that they gave were that

  • Brace placement shouldn't matter but it should be consistent and readable.
  • On spaces vs tabs, they don't seem to care whether the coding standard says anything about it.
  • They're against Hungarian notation in C++ but think that it might be valuable in less type-safe languages.
  • They're completely against enforcing that there be a single return statement in a function.

Regardless, they do think that formatting should be consistent within a source file. Obviously Phobos doesn't necessarily stick to that at this point, but Andrei did just bring up on the newsgroup some of the conventions that have typically held to and was looking at possibly enforcing some of them (the actual post is archived here).

However, while Phobos is open source and anyone is free to submit patches, remember that it's the API that's meant for public consumption. Only the Phobos developers need to look at the code (at least if the docs are appropriately complete) - certainly they're the only ones who are going to be working on it directly - so there's no need for a publicly listed coding standard, even if they use one. It does look like they could use more consistency and that they may be working on that, but all that's going to do for 3rd parties is make it more readable. No one else really needs to know what the standard actually is (though if you looked at enough code following a standard, you could figure out at least more or less what the standard said).

As for D at large, there are certain conventions which are considered good practice (such as generally using auto instead of specifying a type, unless you actually have to specify the type), but just as with C++, you can code with whatever coding style you want, and the D devs aren't dictatorial enough to try enforce a style on the whole D community.

Recently we discussed a defect mentioned here and one of the parties said something like "yes, that's why books say that inheritance should be avoided.

I've been using inheritance for years and find it very useful and convenient in many design cases. Also I'm sure that the person arguing at the very least misunderstood what those "books say".

Is there really an idea that inheritance is kind of bad and should be avoided? Where does it originate and where can I learn more?

Good coding practice in C++ prefers composition through aggregation. cf. "C++ Coding Standards: 101 Rules, Guidelines, And Best Practices" by Sutter/Alexandrescu

We are migrating to Sun Studio 12.1 and with the new compiler [ CC: Sun C++ 5.10 SunOS_sparc 2009/06/03 ]. I am getting compilation error while compiling a code that compiled fine with earlier version of Sun Compiler [ CC: Sun WorkShop 6 update 2 C++ 5.3 2001/05/15 ].

This is the compilation error I get.

"Sample.cc": Error: Could not find a match for LoopThrough(int[2]) needed in main(). 1 Error(s) detected. * Error code 1.

CODE:

#include <iostream> 

#define PRINT_TRACE(STR) \
std::cout << __FILE__ << ":" << __LINE__ << ":" << STR << "\n";

template<size_t SZ>
void LoopThrough(const int(&Item)[SZ])
{
    PRINT_TRACE("Specialized version");
    for (size_t index = 0; index < SZ; ++index)
    {
        std::cout << Item[index] << "\n";
    }
}


/*     
    template<typename Type, size_t SZ>
    void LoopThrough(const Type(&Item)[SZ])
    {
        PRINT_TRACE("Generic version");        
    }
 */  



int main()
{
    {
       int arr[] = { 1, 2 };
       LoopThrough(arr);    
    }
}

If I uncomment the code with Generic version, the code compiles fine and the generic version is called. I don't see this problem with MSVC 2010 with extensions disabled and the same case with ideone here. The specialized version of the function is called. Now the question is, is this a bug in Sun Compiler ?

If yes, how could we file a bug report ?

Your compiler is buggy. Both overloads have their template arguments deduced, and overload resolution should select the most specialized one. So apart from getting a new compiler, what can you do?

First, it's helpful to realize that -even with conforming compilers- it is generally not a good a idea to have different function template overloads. See e.g. Item 66 of C++ Coding Standards: 101 Rules, Guidelines, and Best Practices by Herb Sutter and Andrei Alexandrescu.

Fortunately, that Item also suggests a possible fix. All you have to do is define a single function template and let that function template delegate the work to a class template function object. You can then partially specialize this class template for ints.

#include <iostream> 

#define PRINT_TRACE(STR) \
std::cout << __FILE__ << ":" << __LINE__ << ":" << STR << "\n";

namespace detail {    

// primary template
template<typename Type, size_t SZ>
class LoopThroughHelper
{
public:
    void operator()(const Type(&Item)[SZ]) 
    {
        PRINT_TRACE("Generic version");        
    }
}; 

// partial specialization for int arrays
template<size_t SZ>
class LoopThroughHelper<int, SZ>
{
public:
    void operator()(const int(&Item)[SZ]) 
    {
        PRINT_TRACE("Specialized version");
        for (size_t index = 0; index < SZ; ++index)
        {
            std::cout << Item[index] << "\n";
        }
    }
}; 

} // namespace detail

// one function template to rule them all
template<typename Type, size_t SZ>
void LoopThrough(const Type(&Item)[SZ])
{
     detail::LoopThroughHelper<Type, SZ>()(Item);        
}

int main()
{
    {
       int arr[] = { 1, 2 };
       LoopThrough(arr);    
    }
}

Most likely, the compiler will inline the call to the function object and completely optimize away the temporary. Hopefully your compiler will also have correctly implemented partial specialization of class templates.

Output on Ideone

Arrays can be passed as pointer to a function or even as reference. Passing it as reference gives an alias on which sizeof and count operators will also work. This makes pass by reference look superior.

However, pass by pointer seems to be the norm in books. Why? Is there something I particularly need to know about pass by reference for arrays?

I usually use std::vector and like to pass by const reference. That said, if my api may at some point be called by c code, using pass by const pointer may make sense, though you then have to also want to send down the size. If the function may be called with an std::array or a std::vector, you could decide to send down a pointer (and size), or a set of iterators (begin/end).

If we are talking about using std::array, the template argument requires the size of the array. This would mean in a normal function, you'd need a fixed size:

void myfunc( const std::array<int, 5>& mydata ){...}

However, if we do a templated function, templating on size, that is no longer a problem.

template<unsigned int SZ>
void myfunc(const std::array<int, SZ>& mydata) {...}

If we are talking about stack allocated c-style arrays... Good C++ style is to prefer std::array/std::vector to c-style arrays. I would recommend reading C++ Coding Standard by Herb Sutter chapter 77 on page 152 speaks about the subject. When using c-style arrays, sending down the pointer and size is the standard way to go.

Is this code ambiguous or is it perfectly fine (approved by standards/has consistent behavior for any compilers in existence)?

struct SCustomData {
    int nCode;
    int nSum;
    int nIndex;
    SCustomData(int nCode, int nSum, int nIndex)
        : nCode(nCode)
        , nSum(nSum)
        , nIndex(nIndex)
    {}
};

edit:
yes, I am referring to the fact that the member variables have the same name with formal parameters of the constructor.

No, in this case there are no ambiguity, but consider following:

struct SCustomData {
//...
    void SetCode(int nCode)
    {
            //OOPS!!! Here we do nothing!
            //nCode = nCode;

            //This works but still error prone
            this->nCode = nCode;
    }
};

You should draw attention to one of existing coding styles. For instance General Naming Rule in Google C++ Coding Styles or read excellent book "C++ Coding Standards: 101 Rules, Guidelines, and Best Practices" by Herb Sutter and Andrei Alexandrescu.

What books should you read to improve your code and get used to good programming practices after getting a taste of the language?

C++ Coding-Standards: 101 Rules, Guidelines, and Best Practices

---- Herb Sutter and Andrei Alexandrescu

alt text

Meyers' Effective C++, "More Effective C++" and "Effective STL".

Design Patterns by the 4 guys affectionately nicknamed "the gang of four".

Lakos' Large Scale C++ Software Design.

There are of course many others, including many truly good ones, but if I had to pick 3 on C++ (counting Meyers' three thin, information-packed volumes as one;-) these would be it...

What naming convention should I follow for class members? Right now, I’m prefixing all fields with an underscore, and using the regular name for the accessor method, e.g.: int _age and int age() { return _age; }

Any preferred approaches?

Personally I would recommend to start member variables with m_ and the accessor method with get and set prefixes, e.g.: m_age and int getAge() {}.

For a good rule set of naming conventions and best practices read these two books:

http://www.amazon.com/Code-Complete-Practical-Handbook-Construction/dp/0735619670/ref=sr_1_1/187-8545911-6271721?ie=UTF8&s=books&qid=1252936825&sr=8-1 (general programming style)

http://www.amazon.com/Coding-Standards-Rules-Guidelines-Practices/dp/0321113586/ref=sr_1_1/177-5450861-2480140?ie=UTF8&s=books&qid=1252936836&sr=8-1 (C++ specific)

I just don't get it. Tried on VC++ 2008 and G++ 4.3.2

#include <map>


class A : public std::multimap<int, bool>
{
public:
    size_type erase(int k, bool v)
    {
        return erase(k); // <- this fails; had to change to __super::erase(k)
    }
};

int main()
{
    A a;
    a.erase(0, false);
    a.erase(0); // <- fails. can't find base class' function?!

    return 0;
}

Others have answered how to resolve the syntax problem and why it can be dangerous to derive from standard classes, but it's also worth pointing out:

Prefer composition to inheritance.

I doubt you mean for 'A' to explicitly have the "is-a" relationship to multimap< int, bool >. C++ Coding Standards by Sutter/Alexandrescu has entire chapter on this (#34), and Google points to many good references on the subject.

It appears there is a SO thread on the topic as well.

For those that use Effective C++ as a C++ programming reference, this issue is covered in Item 33 (Avoid hiding inherited names.) in the book.

I'm new to Linux kernel development.

One thing that bothers me is a way a variables are declared and initialized.

I'm under impression that code uses variable declaration placement rules for C89/ANSI C (variables are declared at the beginning of block), while C99 relaxes the rule.

My background is C++ and there many advises from "very clever people" to declare variable as locally as possible - better declare and initialize in the same instruction:

What is the accepted way to initialize variables in Linux kernel?

I would like to know about books that talk about design issues like when to use namespaces and other coding standards to write good quality efficient C++ code. One that talks about Code testing will also be appreciated.

"Large-Scale C++ Software Design" by John Lakos worked great for me years ago on how to organise code in large projects.

On testing, this is not my area, and I cannot recommend a great book. What I can do is discourage you from getting "Testing Computer Software", 2nd edition by Cem Kaner, Jack Falk and Hung Q. Nguyen. I found it severely dated and extremely clumsy. But please take this with a grain of salt.

For big projects, it is essential to follow a common design and coding style. Consistently.

I found the following book useful to have a common ground in a big project.

C++ Coding Standards: 101 Rules, Guidelines, and Best Practices by Andrei Alexandrescu, Herb Sutter

I have been reading C++ and writing small programs in it for more than a year. Recently I came across Law of The Big Three. I never knew about this law.

Accidentally, I found it here: Rule of Three.

May I know any other such laws in C++?

You're probably looking for C++ "best practices", not "laws". This should help you searching on the net.

Moreover, there's a book called "C++ Coding Standards: 101 Rules, Guidelines, and Best Practices" by Herb Sutter and Andrei Alexandrescu which is supposed to be good, but I haven't read it myself. You can order it, e.g., over at amazon.com.

Well, it seems everyone agree on the value of Herb Sutter and Andrei Alexandrescu's amazing book.

C++ Coding Standards is a most interesting read. The items are grouped very logically, and each item is detailed just enough that you understand the risk for not heeding the advice. Also each item comes with possible exception to the rule and why they are exception.

All in all it is a very valuable asset to one trying to put in place a number of practices, especially when installing code reviews.

There is another 'book' though only available in PDF / HTML format as far as I know. It is a mash-up of several standards referenced

High Integrity C++ is also very interesting in that it qualifies the items (Rule / Guideline distinction) and sometimes offer alternatives (two mutually exclusive advices). It is much more detailed than C++ coding standards so you might want to read it in second position :)

You can obtain the PDF version here, they will send it to you by email.

At work we have the following construct to enable interpreting an IP address as either an array of 4 bytes, or as a 32-bit integer:

union IPv4
{
    std::uint32_t ip;
    std::uint8_t  data[4];
};

This works fine, but I'm a little worried after reading chapter 97 "Don't use unions to reinterpret representation" of the book C++ coding standards. The example in the book is more insidious though and I'm not sure if it applies to my code.

Are there any potential issues with my code?

According to the standard, reading a member of a union other than the last one written is undefined behavior. Unions were designed to save space, no for data type conversion. That said, what you are doing will probably work on all mainstream platforms and compilers.

I'm about to write a program in C++, but I'm unsure as to how to go about it. I want to create a program that can be used with a command line frontend but also a GUI frontend as I don't want to bind a user to a specific interface such as a widget toolkit for dependencies' sake.

How would be the best way to do this? I know some programs like RSync and SSH have frontends in GUIs, but I'm not sure how this is done. Wouldn't it be hacky to have a program that just uses system() to run it all while having a pretty GUI?

You could use QT for the GUI front end. But I'd actually just write your library first. Then do your GUI last.

Some helpful advice

  1. Be sure to write unit tests WHILE writing your code.

  2. Be sure to use a code coverage tool to evaluate your unit tests while writing your code.

  3. Be sure to avoid BOOL types since those are usually defined in the platform API (like win32). Use bool instead.

  4. Forward declare as many types as you can in your header files. Include as few as possible header files in each library header file.

  5. Expose as minimal an interface as possible.

  6. Be sure to follow good coding practices for c++. Herb Sutters Book C++ coding standards is excellent in this regard.

  7. Once you do write your gui, put as little business logic in your GUI event handlers as possible. Basically you want your library to be agnostic towards your GUI. Someone else mentioned the MVC pattern here. That is excellent advice.

I'm learning C++ at the moment and I think I understand most of what there is to know about including headers... coming from languages where this wasn't necessary at all, I often have the feeling that 'this is wrong' or there should be 'an easier way to do this':

  1. I find it very annoying to include (for example) "vector" in every class I want to use a vector. Is there a better way?

  2. I've got a good bit of core functionality (also in it's separate namespace) with quite a few classes that doesn't change often. While I don't need all the functionality in every class, it would be very nice to just have one single header file, include that and be done with it... What's the best way to do this?

  3. Is it bad practice to include headers in a precompiled header file? If yes, why?

1.I find it very annoying to include (for example) in every class I want to use a vector. Is there a better way?

Imagine how annoying it is for others who use your code (and that other could be your future self) and get a compilation error because there is a missing header for <vector>. Write it once, use it many times over.

2.I've got a good bit of core functionality (also in it's separate namespace) with quite a few classes that doesn't change often. While I don't need all the functionality in every class, it would be very nice to just have one single header file, include that and be done with it... What's the best way to do this?

You can do this for speedup, if you let your IDE include this automatically as a precompiled-header. But for correctness and portability alone you should not rely on it and always let every header be compilable as a standalone header. See e.g. Item 23 in Alexandrescu & Sutter's Coding Standard. Build systems like CMake even have macros to test for this.

3.Is it bad practice to include headers in a precompiled header file? If yes, why?

You can do it, but it's best to let the IDE do this in order to get better portability. And those headers better be stable (the Standard Library or Boost e.g., but never your own project headers).

I've got an argument with my colleague.

We have a class that is a member of a namespace (which is a member of the other namespace but that is not important here I think). In the header file, we nest the class block into the namespace block like this:

namespace NS {
    class A {
        void method();
        // ...
    };
}

And here is the .cpp file and the subject of our argument. I wrote:

using namespace NS;

void A::method() {
    // ...
}

The colleague told me that I use the 'using' directive improperly, and I should have used here the same NS { ... } as in the header. (He's modified the code and got some compiler errors that he only managed to get rid of by removing the using directive and surrounding the code with NS { ... }.)

My point is that 'using' just affects the name lookup so A is looked for in the NS namespace, so my approach is correct, and his compiler problems were caused by something else but not by that 'using' directive.

Who is right and why?

Added: guys, please don't answer like 'I did this (or that) way many times', that's not much useful. We need the theory here: why this or that approach is right or wrong.

Your colleague is correct, you should wrap cpp with namesapce which means you define your funcitons inside namesapce NS.

namespace NS
{    
  void A::method() 
  {
    // ...
  }
}

You may get conflict name lookup if you have multiple A available.

The dangerous thing happening here is that the using declaration takes a snapshot of whatever entities named A::method in namespace NS have been seen by the time the using declaration is encountered.

Have a read of Google cpp style guilde regarding namespace, also 101 c++ coding standards

So I read that inheritance from STL is a bad idea. But what about wrapping STL classes inside other classes in order to extend them. This with the main purpose of separating levels of abstraction, among other things.

Something like:

template<class T>
class MyVector{
public:
T& last(){
  return data[data.size() - 1]
}

bool include(T& element);

//etc.

private:
vector<T> data;
}

Is this a good idea? Is this something c++ programmers do often?

Thank you.

Yes, wrapping is better than inheritance, but only if you need to add state to an existing data structure. Otherwise, add non-member functions. This is explained in more detail in item 35 of C++ Coding Standards (Amazon)

To add state, prefer composition instead of inheritance. Admittedly, it's tedious to have to write passthrough functions for the member functions you want to keep, but such an implementation is vastly better and safer than using public or nonpublic inheritance.

template<typename T>
class MyExtendedVector
{
public:
    // pass-through functions for std::vector members
    void some_existing_fun() { return vec_.some_existing_fun(); }

    // new functionality that uses extra state
    void some_new_fun() { // your implementation here }   

private: 
    std::vector<T> vec_;
    // extra state e.g. to do logging, caching, or whatever
};

To add behavior, prefer to add nonmem-ber functions instead of member functions.

However make sure to make your algorithms as generic as possible:

// if you CAN: write algorithm that uses iterators only 
// (and delegates to iterator category that container supports)
template<typename Iterator, typename T>
bool generic_contains(Iterator first, Iterator last, T const& elem)
{
    // implement using iterators + STL algorithms only
    return std::find(first, last, elem) != last;
}

// if you MUST: write algorithm that uses specific interface of container
template<typename T>
void vector_contains(std::vector<T> const& v, T const& elem)
{
    // implement using public interface of Container + STL algorithms
    return generic_contains(v.begin(), v.end(), elem);
}

There is a base class A, which is virtual

class A
{
  ~virtual A() = 0;
};

and more derived classes B, C, D, E...

class B : public A
{
};

class C: public A
{
};

and analogously for other classed D, E... We have a list of A pointers

std::list <A*> a_list;

We remove any element which type is unknown, for example

A *a = a_list.front();

Base on the type of a pointed object we decide, what to do... There more possibilities how to do that:

A) dynamic_cast case

Recasting of a to derived types.

if (dynamic_cast <B*> (a))
{
   //do something (but nothing with a)
}

else if (dynamic_cast <C*> (a))
{
    //do other (but nothing with a)
}

But the dynamic_cast usage indicates a bad design.

B) Additional attribute

Some aditional attribute, for example an object ID is impelemented;

class A
{
  virtual ~A() = 0;
  virtual short getID() = 0;
};

class B : public A
{
  virtual short getID() {return 1;}
};

class C: public A
{
  virtual short getID() {return 2;}
};

So the modified condition

switch ( a->getID())
{
   case 1: // do something (but nothing with a)
   case 2: // do other (but nothing with a)
}

A note:

We do not perform any action directly with the object, but on the basis of its type we do some different computations.

Questions:

1) Is it the case, when we should avoid dynamic_cast?

2) is there any prefereable solution (may be different to presented)?

Thanks for your help.

According to Item 90 in C++ Coding Standards (Amazon): Avoid type-switching (regardless whether you do it with an if-else ladder and dynamic_cast, or a switch statement with getID() function). Prefer instead to rely on polymorphism via virtual functions

class A
{
public:
  ~virtual A() = 0;

  void fun()  // non-virtual
  { 
     // main algorithm here

     // post-processing step
     post_fun();
  }

  virtual void post_fun() = 0;
};

class B : public A
{
public:
   virtual void post_fun() { /* bla */ }
};

class C: public A
{
public:
   virtual void post_fun() { /* meow */ }
};

A* a = a_list.front();
a->fun(); // will be resolved at run-time to whatever type a points to

The reason is that having an explicit type-switch is hard to maintain and update. If you get a new derived class from A, you need to update every place where you loop over types. Instead, the compiler will do that automatically for you if you rely on virtual functions.

We are going to start a new project in our team which consists of less than 10 developers. We have access to modern IDEs such as VS2010.

The project is extremely dynamic (users' needs change very quick) and cross platform. Therefore, I need a highly readable and very detailed C++ coding standard so new developers can easily change the old codes in future. I also need a not to write list so the code will compile on different OSes (at least windows and linux).

  • Is there such a standard?
  • Are coding standards expired already?

Read C++ Coding Standards. It is not what most people would call a coding standards document, but you probably want to read it. One of the first guides is do not swell the small stuff (do not put too much emphasis on details: focus on rules that affect the semantic not the syntax, as in prefer RAII over raw pointers instead of add braces everywhere, in it's own line and indenting 3 spaces)

If I have a function (say messUp that does not need to access any private variables of a class (say room), should I write the function inside the class like room.messUp() or outside of it like messUp(room)? It seems the second version reads better to me.

i base myself on "C++ Coding Standards: 101 Rules, Guidelines, And Best Practices" by Sutter and Alexandrescu, and also Bob Martin's SOLID. I agree with them on this point of course ;-).

If the message/function doesnt interract so much with your class, you should make it a standard ordinary function taking your class object as argument.

You should not polute your class with behaviours that are not intimately related to it. This is to repect the Single Responsibility Principle: Your class should remain simple, aiming at the most precise goal.

However, if you think your message/function is intimately related to your object guts, then you should include it as a member function of your class.

I like quality software development, and this all might sound airy fairy, but I think it's important to strive towards and also project out to upper management what we are all about.

I am looking for suggestions for a vision goals to strive for in a software development department. What should you be doing and what characteristics should you have as a team?

Years ago, fresh out of school, a mentor listened to my desires to improve the local codebase, and offered an important insight. If you're trying to sell change to management, you need to communicate how it advances business goals.

Business goals might include, for example, greater productivity, reduced cost, reduced risk, reduced downtime, greater reliability, increased automation.

Let's say you've entered an environment not yet investing significantly in unit tests. (It still happens.) There is an up-front investment to write unit tests and unit-testable code. You need to communicate that the costs of this investment are exceeded by increased reliability, reduced schedule uncertainty, and improved productivity over the long term.

In terms of vision goals, here are a few resources.

  • "The Joel Test" by Joel Spolsky
  • XP practices - Even if you're not using XP, at least some of its practices may still be desirable, such as iterative development, continuous integration, unit testing, colocation, and a sustainable pace.
  • Industry-standard coding standards, like Sutter and Alexandrescu's "C++ coding standards" and Joshua Bloch's "Effective Java".

In my code I use a templated multi-dimensional container class array_dyn<T>, which has a property my_data that is a std::vector<T>.

To keep things separable I use my own class bisArray<T> that inherits from array_dyn:

typedef array_dyn<T>                   super_type;
typedef typename super_type::index_t   index_t;

template < typename Sizes >
bisArray( dirs a_dir, Sizes const& a_sizes={} ): 
        super_type ( a_dir, a_sizes ),   super_type::my_data( super_type::size()) {}
template < typename Sizes >
bisArray( Sizes const& a_sizes={} ): 
        super_type ( dir_fwd, a_sizes ), super_type::my_data( super_type::size()) {}

Here, dir_fwd (and dir_rev) represents c (and fortran) storage order. The array_dyn class is here [ https://svn.boost.org/svn/boost/sandbox/variadic_templates/sandbox/array_dyn ].

Happy to provide more code, but I think the problem that I get is caused here: when I use

std::vector<size_t> newsizes({2,3});
bisArray<int>       newarray(newsizes); // using constructor #2

Then there is an error message

no type named my_data in struct 'array_dyn<int>' 

Previous StackOverflow posts about this error mentioned circular definitions and forward declarations; but that is not what I am doing here. I just inherit from array_dyn, which has a property my_data, but when I create an object with the derived class bisArray, it says that its base class does not have this property.

Am I using the wrong inheritance mechanism? Or the wrong access method?

You probably shouldn't be (ab)using inheritance...

Question: why do you use inheritance for bisArray<T>?

Is it to add extra functionality to array_dyn<T> that can entirely be written in the public interface of array_dyn<T>? In that case, add non-member functions to provide that functionality instead of inheriting and adding member functions. So instead of

template<class T>
class bisArray: public array_dyn<T>
{
public:
     void doCoolStuffThatBoostDoesNotProvide() const;
};

write a non-member function

template<class T>
void doCoolStuffThatBoostDoesNotProvide(array_dyn<T> const& s);

If you need to add functionality that requires extra state to a array_dyn<T>, use composition

template<class T>
class bisArray
{
public: 
     void doCoolStuffThatBoostCannotImplement() const;
private:
     some_fancy_type s_;
     array_dyn<T> a_;
};

array_dyn<T> was never designed to be a base class. For one, it doesn't have a virtual destructor. Second, the designers of array_dyn<T> also composed a std::vector<T>, and did not inherit from it, for exactly those reasons.

Of course, when using composition, bisArray<T> will have to redefine the entire interface (members and constructors) that it wants to keep. However, in the words of Alexandrescu and Sutter:

Admittedly, it's tedious to have to write passthrough functions for the member functions you want to keep, but such an implementation is vastly better and safer than using public or nonpublic inheritance.

... but use the base constructors if you do...

OK, you absolutely-positively-definitely want to use inheritance. Well that's easy: just delegate all work to the array_dyn<T> base class constructor:

template
  < typename Sizes
  >
array_dyn( dirs a_dir, Sizes const& a_sizes={})
: super_t( a_dir, a_sizes)
, my_data( super_t::size())
{
}

Your two requested constructors can then be gotten from your current version minus the initialization of my_data because the array_dyn<T> constructor already does the exact same amount of work

// note use explicit keyword for single-argument constructors
template<typename Sizes>
explicit bisArray( dirs a_dir, Sizes const& a_sizes={} )
: super_type(a_dir, a_sizes) 
{}

template < typename Sizes >
bisArray( Sizes const& a_sizes={} )
: super_type(dir_fwd, a_sizes)
{}     

In case you want to set super_type::my_data to another value than what the super_type constructor does, just put such a statement in the body of the constructor. But from the Boost code and your code alone that doesn't seem to be required here.

... or use factory functions to get the best of both worlds

Still, if all that bisArray<T> does is create a default constructor that takes the C-array style parameter dir_fwd, why not drop the inheritance, and write two non-member factory functions that return a array_dyn<T> with the corresponding constructor arguments

template<typename T, typename Sizes>
make_fortran_array_dyn(Sizes const& a_sizes={} )
{
    return array_dyn<T>(dir_rev, a_sizes);
}

template <typename T, typename Sizes >
make_c_array_dyn( Sizes const& a_sizes={} )
{
     return array_dyn<T>(dir_fwd, a_sizes);
}     

which you can call like this:

auto c = make_c_array_dyn<double>(your_sizes);
auto f = make_fortran_array_dyn<double>(your_sizes);

I soon started a small C++ project and elaborated some naming convention rules for variables, according to scope.

I made class members _prefixed_with_underscore and methods parameters suffixed_with_underscore_. I soon got neurotic about inventing naming conventions for everything, like global variables (ok, those might be important), inline global functions, to try to improve code readability.

I've read this question and its answers that answered some of my doubts about naming convention, specially about methods parameters names. Maybe having a_rule_like_this_ for parameters names might not be a good idea.

So, my question is, what naming conventions do you use for different "entities" when programming, specially for parameter names? Thanks.

This is little more than a matter of opinion. So, here's mine.

  1. Don't sweat the small stuff
  2. Check out other people's opinions on the matter (which you're doing)
  3. It matters less which convention you choose, and much much more that you apply it consistantly
  4. Here's some of my convention:

    class MyGizmo
    {
    public:
      int DoIt();
    private:
      string myString_;
    };
    
    typedef vector<MyGizmo> MyGizmos;
    
    namespace somewhere
    {
      MyGizmos gizmos;
    };
    
    
    int MyGizmo::DoIt()
    {
      int retVal = 0;
      string strCopy = myString;
      retVal = strCopy.length();
      return retVal;
    }
    

Ok heres some code.

#include <iostream>
#include <deque>
using namespace std;
class A
{
public:
    virtual void Execute()
    {
        cout << "Hello from class A" << endl;
    }
};
class B: public A
{
public:
    void Execute()
    {
        cout << "Hello from class B" << endl;
    }
};
void Main()
{
    deque<A *> aclasses = deque<A*>(0);
    deque<A *> aclasses2 = deque<A*>(0);
    A a1 = A();
    B b1 = B();
    aclasses.push_back(&a1);
    aclasses.push_back(&b1);
    aclasses[0]->Execute();
    aclasses[1]->Execute();

    //Now say I want to copy a class from aclasses to aclasses2
    //while perserving it's identity and making it a seperate entity, without
    //knowing the exact type it is.

    aclasses2.push_back(new A(*aclasses[0]));
    aclasses2.push_back(new A(*aclasses[1]));
    //Now my problem show itself
    for each(A * a in aclasses2)
        a->Execute();
    //Execute is called from the original class A both times.

}

Now you might say, why don't you just put the pointers from the first deque into the second deque? While I could but I need the data to be independent. Basically I want to be able to clone items from the first deque while preserving there identity and giving them there own data.

Now the current modified version

#include <iostream>
#include <deque>
using namespace std;
class A
{
public:
    virtual void Execute()
    {
        cout << "Hello from class A" << endl;
    }
    virtual ~A() {}             // don't forget the virtual destructor
    virtual A* clone() const {
       return new A(*this);
    }
};
class B: public A
{
public:
    void Execute()
    {
        cout << "Hello from class B" << endl;
    }
    virtual B* clone() {     // return type is co-variant
       return new B( *this );
    }
};
void MainRUNNER()
{
    deque<A *> aclasses = deque<A*>(0);
    deque<A *> aclasses2 = deque<A*>(0);
    A a1 = A();
    B b1 = B();
    aclasses.push_back(&a1);
    aclasses.push_back(&b1);
    aclasses[0]->Execute();
    aclasses[1]->Execute();

    //Now say I want to copy a class from aclasses to aclasses2
    //while perserving it's identity and making it a seperate entity, without
    //knowing the exact type it is.

    aclasses2.push_back(aclasses[0]->clone());
    aclasses2.push_back(aclasses[1]->clone());
    //Now my problem show itself
    for each(A * a in aclasses2)
        a->Execute();
    //Execute is called from the original class A both times.
}

You have new A(...) way down there. What gets called is A's copy constructor (created implicitly by the compiler.

What you want is a clone method. See here. It recaps the appropriate item from the excellent C++ Coding Standards book. Below is a shameless copy of the final solution, which also shows a nice use of the NVI idiom to avoid the slicing problem.

class A {// …
public:
  A* Clone() const {                        // nonvirtual
    A* p = DoClone();
    assert( typeid(*p) == typeid(*this) && "DoClone incorrectly overridden" );
    return p;                                // check DoClone's returned type
  }

protected:
 A( const A& );
 virtual A* DoClone() const = 0;
};

class B : public A { // …
public:
  virtual B* Clone() const {return new B(*this); }

protected:
  B( const B& rhs ) : A( rhs ) {/* … */}
};

update A bit of an explanation. The basic idea of the clone is the same as the other excellent answers here.

Now, with cloning you have the danger of slicing objects. For example, if some object which derives from A forgets to implement its own clone method, then a call to A* a = d->clone() will not return a full D object (assuming D is a descendant of A)

The NVI idiom says to separate a public interface from a virtual interface. Thus, in this example, clone is public, but not virtual. It call a protected virtual method, doClone, which does the actual cloning, and which derived objects also implement. Because of the split, the clone method can verify that the type of the cloned object matches the type of the original object.

what is the use of using declaration type of namespacing over using directive type of namespacing??when to use each one of them?

Jonathan already resumed the differences between using namespace foo; and using foo::Bar; but I think his answer is unfortunately incomplete.

First: using namespace should never appear in a header file. By doing so you might render it impossible to use in combination with other header files because of a symbol clash...

Second: in general, you should try to limit the scope of the symbols as much as possible, you probably already do it while writing code:

for (size_t i = 0; i < 5; ++i)
{
  std::string myString = myVec.at(i);
  if (myString == "Foo") { std::cout << "Found"; break; }
}

Here it would be useless (and polluting) to have myString declared outside the for loop. In fact, that very advice can be found in a number of books:

From Scott Meyers' Effective C++, Item 26: Postpone variable definitions as long as possible.

From Herb Sutter and Andrei Alexandrescu's C++ Coding Standard, Item 18: Declare variables as locally as possible

There is no reason not to do the same with using declarations.

Third: consider alternatives to using: namespace aliasing and typedef.

// foo.h

class Foo
{
public:

  std::vector<std::string> getSynonyms(const std::string& s) const;

private:
  typedef std::map< std::string, std::vector<std::string> > synonyms_type;
  synonyms_type mSynonyms;
};

// foo.cpp (never in header, at general scope)

namespace fu = boost::fusion;

std::vector<std::string> Foo::getSynonyms(const std::string& s) const
{
  synonyms_type::const_iterator it =
    std::find(mSynonyms.begin(), mSynonyms.end(), s);

  std::vector<std::string> result;
  if (it != mSynonyms.end()) { result = it->second; }

  return result;
}

What are the advantages ?

  • namespace aliasing > reduce typing almost as much without injecting the types right in the current scope so without risk
  • typedef > reduce typing more than using and allow easy change of underlying type too.

Possible Duplicate:
What makes more sense - char* string or char *string?

Sorry if this is a silly question, I am new to these things :-)

I am working on a C++ code base which uses the following reference conventions:

  • const Name &var
  • const Name& var

As far as I'm aware, they mean the same thing.

Which of these is either of these preferred, or mandated?

I don't like the ambiguity of having to choose one or the other.

The closest I have found to this answer is on http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Reference_Arguments , which uses the &var layout.

From the language or compiler perspective both are exactly same. For a group project, you have to use a group style. For personal project, you are free to make any choice.

Though it is hard, but on topics like these, I always try to remember Rule# 0 from C++ Coding Standards: 101 Rules, Guidelines, Best Practices:

Don't sweat the small stuff. (Or: Know what not to standardize.)

If I have flexibility to choose, then personally, I always having prefer having spaces on either side of '*', '&', '=' etc. and so I write it as

const Name & var;

(Also, I never declare two variables in one line.)

According to Herb Sutter's C++ Coding Standards: 101 Rules, Guidelines, and Best Practices programmer should avoid c-style casting:

C-style casts have different (and often dangerous) semantics depending on context, all disguised behind a single syntax. Replacing C-style casts with C++-style casts helps guard against unexpected errors

I am trying to pass pointer p_ctrl to WinAPI callback function, for which I want to use DWORD_PTR parameter of callback function (below example is working, but contains C-style casts where commented):

WndCtrls* WndCtrls::Button ( WndCtrls* const p_ctrl, HWND hwnd, RECT const &rc )
{
    p_ctrl->ctrl = CreateWindowEx (
        0,
        L"BUTTON",
        p_ctrl->w_classNameButton.c_str (),
        WS_VISIBLE | WS_CHILD | BS_OWNERDRAW,
        rc.left,
        rc.top,
        rc.right,
        rc.bottom,
        hwnd,
        0,
        (HINSTANCE)GetWindowLongPtr ( hwnd, GWL_HINSTANCE ), // Problematic C-style cast for which I already know workaround
        p_ctrl
    );
    SetWindowSubclass ( p_ctrl->ctrl, WndCtrls::CtrlProc, 0, (DWORD_PTR)p_ctrl ) ) // C-style cast

    return p_ctrl;
}

LRESULT CALLBACK WndCtrls::CtrlProc ( HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam, UINT_PTR uIdSubclass, DWORD_PTR dwRefData )
{
    WndCtrls* const p_ctrl = (WndCtrls*)dwRefData; // Problematic C-style cast
    switch ( message )
    {
        ...
    }
    return DefSubclassProc ( hwnd, message, wParam, lParam );
}

I already tried dynamic cast, but that gives me errors. reinterpret_cast should not be used at all (according to Sutter).

Please is there a way to do those casts using c++ provided functions?

Sutter's advice is just that: advice. They aren't hard and fast rules; they're just suggestions that encourage you to write safer, more robust code.

This is one of those cases where the advice doesn't work.

In many places, the Windows API needs to be able to pass data that may or may not be a pointer. As such, it uses a pointer-sized integer, using a C-style cast (remember that the Windows API is primarily C-based) to turn the integer into a pointer. This is safe because the documentation requires it to be: if you give Windows a garbage pointer value, you're breaking that function's rules!

The standard C/C++ names for the pointer-sized integers are intptr_t (signed) and uintptr_t (unsigned). However, Windows predates C99 and C++11 (when these were introduced), so it uses its own names: LONG_PTR (signed) and DWORD_PTR and ULONG_PTR (unsigned). In addition, WPARAM, LPARAM, and LRESULT are also pointer-sized, since window messages often need to deal with pointers.

So go ahead and use that C-style cast or that reinterpret_cast<>, whichever one you prefer. The other casts won't work because you need to interpret an integer as a pointer, which the other casts won't let you do.

You may need these anyway because there are other places that, because the Windows API needs to not only be in C but also be usable from other languages, subclassing is replaced by having an object of the struct to derive from as the first element of the dervied struct. This is most apparent in the WM_NOTIFY message, where all possible notification structs do this with NMHDR. Just keep this in mind.

Sutter and Alexandrescu have discribed in a quite simple and self contained way the ecosystem of C++ classes, providing 6 main categories

  1. Value classes (e.g., std::pair, std::vector)
  2. Base classes (building blocks of class hierarchies)
  3. Traits classes (templates that carry information about types)
  4. Policy classes (fragments of pluggable behavior)
  5. Exception classes
  6. Ancillary classes that typically support specific idioms (e.g. RAII)

It is a very handy shortcut when taking decisions on class design and I' ve used it before, but there are two things that come into play: 2004 (the year that book was puplished) is a long time ago in software engineering and there is a new language standard since then. I can't but wonder:

  • Is this this categorization still relevant?
  • Are there any new items ammending the above list?
  • Is there an alternative categorization, by authors having matching authoritative power?
  • Is there a standard taxonomy for c++ classes? (for all I know this could also be it)

NOTE:

I hope the 4 questions above have a clear setting. To avoid opinion based answers, a valid answer should link/mention examples, code usage or standard excerpts that verify its statings.

Given:

Object of class A contains an array of objects.

Each of these objects must implement some interface IB, because A use methods of IB.

These objects are passed to object of class A by client, and they are of type C or its children. A must return these objects back to clients.

Problem: A must not know anything about C, only about IB, but A must return C.

Is there any standard solution in C++ without unsafe casts<>?

I don't think this is possible with A not knowing anything about C. However, having A know enough to use the right interface is not that hard in C++. Have all classes with IB derive from a single abstract base class with the interface defined there as pure virtual functions. This actually corresponds to proper C++ design--separating interface from implementation--as described in e.g. Sutter & Alexandrescu.

Otherwise, if the above really is impossible, you could make A a template class, and store the array elements as void*, resolving the class type (at compile time) using static_cast.

i am trying to find any user entered value in a array which the user has previously entered the values of. I made the following for finding which values were entered in array but cant seem to know where to insert the loop for finding user entered value for searching

ok update

i am looking for a way to find user entered value in array which the user entered before something like this if its logical

Ok 2nd Update

This is what i have been working on i am struck The entered searching value is not been found

#include<iostream>
#include<conio.h>

using namespace std;

void main ()
{
    int a[10], found;

    for(int i=0;i<10;i++)
{
    cout<<"enter value : ";
    cin>>a[i];
}

    cout<<"Enter Searching Value :";
    cin>>found;

    for(int i=0;i<10;i++)
{
    if(found == a[10])
{
    cout<<"Value Found";
    _getch();
}
        else if (found != a[10])
            cout<<"Value Not Found";

}

    _getch();

}

Working solution

You are solving a finding problem here. You have no any suggestions where the entered value may
probably be, so you should try each one step by step. This is a common problem.

The first way to solve it is to use a loop. It isn't a good way for modern C++. But you should probably
try it for a practice.

bool has(int val, int const* arr, size_t size) {
    size_t idx = 0;
    // Iterates each element of array and checks
    // whether the one is equal to the `val`. In
    // case of meeting of `val`, the loop stops.
    while (idx < size && arr[idx] != val) ++idx;
    return idx != size;
}

The way below is more convinient. Actually, the more general form of has function is already has in C++ standart library in <algorithm> header. It is called find. It do exactly the same, but much better. Actually, there are a lot of functions solving a common problems in <algorithm> header. You have to use it anywhere you can.

bool has_(int val, int const* arr, size_t size) {
    int const* end = arr + size;
    // Now `has_` don't iterate each element and
    // checks it. It finds the `val` in range
    // between the first element of array and
    // the last.
    return std::find(arr, end, val) != end;
}

I suggest you to read the subsection "Prefer algorithm calls to handwritten loops." in section "STL: Containers" in the book "C++ Coding Standarts" by Herb Sutter and Andrei Alexandrescu to gain an intuition about why to use the <algorithm> header.

Also, you may find the reference to the <algorithm> header here.

Mistakes in your solution

Lets consider your code and discuss why you end up with error. Actually, you just made a typo.
It is the one of the reasons to use the <algorithm> header instead of handwritten loops like yours.

#include<iostream>
#include<conio.h>

using namespace std;

void main()
{
    int a[10], found;

    for (int i = 0; i<10; i++)
    {
        cout << "enter value : ";
        cin >> a[i];
    }

    cout << "Enter Searching Value :";
    cin >> found;

    for (int i = 0; i<10; i++)
    {
        // Look at here: you compare entered value ten times
        // with the value after the last element of array.
        if (found == a[10])
        {
            // In case that you found an entered value in array
            // you just continue the loop. You should probably
            // break it at this point. This may be achieved by
            // using the `brake` operator or the `while` loop.
            cout << "Value Found";
            _getch();
        }
        else if (found != a[10])
            cout << "Value Not Found";

    }

    _getch();

}

I am trying to make a farey seq program with C++ list library

My program works fine when I use the first level, however, it crashes after that with all other levels for some reason.

I am using visual studio as a compiler. I tried the debugger mode as well as the resource. The program doesn't crash in the resource mode, however, it doesn't give me the even numbers levels output. In addition, it gives me half of the odds levels output for some reason.

I want to fix this problem and I want it to work in the dubgger mode as well.

Any suggestions?

Here is what I've done so far

  class RULLZ: public list<Fraction>
  {
    private:
    list<Fraction>::iterator head,tail,buf,buf1;
    public :
      Farey2()
    {
      this->push_front( Fraction(1,1));
      this->push_front( Fraction(0,1));

}

  void Add(int level)

  {
    Fraction *tmp,*tmp2;
    buf=this->first();
    for(int i=0;i<level-1;i++)  
    {


      head=this->first();
      tail=this->last();
      while(head!=tail)
      {

        tmp=new Fraction(head->num,head->den);
        head++;
        if(tmp->den+head->den<=level)
        {
          tmp2=new Fraction(tmp->num+head->num,tmp->den+head->den);
          this->insert(head,*tmp2); 
          head--;
        }


      }
      this->pop_back();
    }





  }

  friend ostream& operator<<(ostream& out,  RULLZ& f)
  {
    for(list<Fraction>::iterator it=f.first();it !=f.last();it++)
      out <<*it;
    return out;
  }

  };
class RULLZ: public list<Fraction>

Before even looking at your question, the above code is a problem. The C++ standard containers are deliberately not designed to be base classes (none of them have a virtual destructor), so this will cause problems. For reasons why you should not publicly derive from a standard container, see the following:

  1. When is it "okay"?
  2. The risks
  3. Why it is a bad design decision
  4. Coding Guidelines (Page ~60)
  5. Why inheritance is usually not the right approach

It appears you want the Add function to add the next X number of fractions together (if I understand your intent correctly). A better way to do that is to use a std::stack:

std::stack<Fraction, std::list<Fraction>> expression;
// add fractions to your stack here
Fraction Add(unsigned int count)
{
    // assume count is greater than 1 (as adding 0 fractions makes no sense, and adding 1 is trivial)
    Fraction result(0, 1);
    for (int i = 0; i < count; ++i)
    {
        Fraction a = expression.top();
        expression.pop();
        Fraction b = expression.top();
        expression.pop();
        result += a + b; // assume operators + and += have been implemented for Fraction
    }
    expression.push(result);
    return result;
}

Another problem you appear to have is a logic problem (again, assuming I understand your intent correctly):

for(int i=0;i<level-1;i++)

If level is the number of fractions you want to add, and you pass in 2, this loop will only include the first one. That is, it will not add fractions 0 and 1, but rather just grab fraction 0 and return it. I think you meant for this to be

for(int i=0; i < level; i++)

Which will grab both fractions 0 and 1 to add together.

I'm not sure where, but your logic for generating the series appears to be off. A more simple approach can be found here:

#include <algorithm>
#include <cstdint>
#include <iterator>
#include <iostream>
#include <vector>

struct Fraction
{
    std::uint32_t Numerator;
    std::uint32_t Denominator;
    Fraction(std::uint32_t n, std::uint32_t d) : Numerator(n), Denominator(d) { }
};

std::ostream& operator<<(std::ostream& os, const Fraction& f)
{
    os << "(" << f.Numerator << " / " << f.Denominator << ")";
    return os;
}

typedef std::vector<Fraction> FareySeries;

FareySeries generate_series(std::uint32_t depth)
{
    std::uint32_t a = 0;
    std::uint32_t b = 1;
    std::uint32_t c = 1;
    std::uint32_t d = depth;
    FareySeries results;
    results.emplace_back(a, b);
    while (c <= depth)
    {
        std::uint32_t k = (depth + b) / d;
        std::uint32_t nc = (k * c) - a;
        std::uint32_t nd = (k * d) - b;
        a = c;
        b = d;
        c = nc;
        d = nd;
        results.emplace_back(a, b);
    }
    return results;
}

int main()
{
    const std::uint32_t DEPTH = 4;
    FareySeries series = generate_series(DEPTH);
    std::copy(series.begin(), series.end(), std::ostream_iterator<Fraction>(std::cout, "\n"));
    return 0;
}

I have a question about writing loops. I always begin with

(int i=0; i<10; i++)

But I see many experts begin with

(int i=0; i<10; ++i)

Is there there any real difference, or they are same?

Of course, I know the difference between pre-increment and post-increment. I mean which one I should use when writing the loop? or it depends.

Thanks!

Preincrement is generally preferred because while it makes no difference for primitive types it may be faster for iterators as preincrement doesn't have to return a copy of its old value.

Since preincrement is sometimes faster (with non primitive types like iterators) it is a good habit to get into even where it makes no performance difference which is why many people recommend it. This is item 28 in C++ Coding Standards for example.

In C++ a while statement like this...

while (currGame.playGame(currPlayer) == true);

is perfectly legal as long as the playGame function returns true or false but is this considered ugly code?

Ugly or pretty depend on you! But keep in mind

  • Programs should be written for people to read, and only incidentally for machines to execute.
  • Make it clearer to both humans and compilers that the code does what you intended.

As Other answers I would shorten your code to while (currGame.playGame(currPlayer));. But anyway this is not a big deal.

For further this small book would be a good reference to read http://www.amazon.com/Coding-Standards-Rules-Guidelines-Practices/dp/0321113586

Say I have an interface class A (class with only pure virtual functions). Also, I have a concrete class B, which holds a weak pointer to A, and calls methods on it.

There is strong coupling between classes A and B. Basically I expect only class B will call methods on class A.

Does it make sense to declare all methods on A, private (pure) virtual and make class B its friend. The classes implementing A, will be free to change the access of the functions they implement as part of inheriting A. It seems appropriate for the use case but I haven't seen it used before.

It makes sense, and it addresses one design issue, but it raises another one (which you might either consider minor or not).

In Sutter and Alexandrescu's C++ Coding Standards there's a guideline 39. Consider making virtual functions nonpublic, and public functions nonvirtual. This makes sense. Say you have

class interface {
public:
    virtual void bar();
};

then you realize that all bars have something in common: maybe you want to validate arguments passed to them (if they take arguments), or log calls to all of them. Because of this, the guideline is to split it into

class interface {
public:
    void bar() { bar_(); }

protected:
    virtual void bar_();
};

I.e., a public non-virtual method calling a non-public virtual one. The public one is the only gateway to the virtual one.

The problem is that this is the only gateway until you introduce friend. Then, you have no control, and the external class can call bar_ directly, circumventing it.


In your case, you could consider the following, therefore:

Say the class to which you want to grant access is foo, and the interface class is interface. Write another class interface_accessor, which will be the gateway:

class foo;

class interface;

class interface_accessor {
private:
     static void bar(interface &i);

     friend class foo;                                                  
};

Note that interface_accessor is a friend of foo.

Now, make interface a friend of interface_accessor, but not of foo:

class interface {
private:
    virtual void bar_() {}

    friend class interface_accessor;
};

Finally, implement interface_accessor:

void interface_accessor::bar(interface &i) {
    i.bar_();
}