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


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 (, 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]


  • 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]


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

  • (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.

If you could go back in time and tell yourself to read a specific book at the beginning of your career as a developer, which book would it be?

I expect this list to be varied and to cover a wide range of things.

To search: Use the search box in the upper-right corner. To search the answers of the current question, use inquestion:this. For example:

inquestion:this "Code Complete"

Applying UML and Patterns by Craig Larman.

The title of the book is slightly misleading; it does deal with UML and patterns, but it covers so much more. The subtitle of the book tells you a bit more: An Introduction to Object-Oriented Analysis and Design and Iterative Development.

Masters of doom. As far as motivation and love for your profession go: it won't get any better than what's been described in this book, truthfully inspiring story!

Beginning C# 3.0: An Introduction to Object Oriented Programming

This is the book for those who want to understand the whys and hows of OOP using C# 3.0. You don't want to miss it.

alt text

Mastery: The Keys to Success and Long-Term Fulfillment, by George Leonard

It's about about what mindsets are required to reach mastery in any skill, and why. It's just awesome, and an easy read too.

Pro Spring is a superb introduction to the world of Inversion of Control and Dependency Injection. If you're not aware of these practices and their implications - the balance of topics and technical detail in Pro Spring is excellent. It builds a great case and consequent personal foundation.

Another book I'd suggest would be Robert Martin's Agile Software Development (ASD). Code smells, agile techniques, test driven dev, principles ... a well-written balance of many different programming facets.

More traditional classics would include the infamous GoF Design Patterns, Bertrand Meyer's Object Oriented Software Construction, Booch's Object Oriented Analysis and Design, Scott Meyer's "Effective C++'" series and a lesser known book I enjoyed by Gunderloy, Coder to Developer.

And while books are nice ... don't forget radio!

... let me add one more thing. If you haven't already discovered safari - take a look. It is more addictive than stack overflow :-) I've found that with my google type habits - I need the more expensive subscription so I can look at any book at any time - but I'd recommend the trial to anyone even remotely interested.

(ah yes, a little obj-C today, cocoa tomorrow, patterns? soa? what was that example in that cookbook? What did Steve say in the second edition? Should I buy this book? ... a subscription like this is great if you'd like some continuity and context to what you're googling ...)

Database System Concepts is one of the best books you can read on understanding good database design principles.

alt text

Algorithms in C++ was invaluable to me in learning Big O notation and the ins and outs of the various sort algorithms. This was published before Sedgewick decided he could make more money by dividing it into 5 different books.

C++ FAQs is an amazing book that really shows you what you should and shouldn't be doing in C++. The backward compatibility of C++ leaves a lot of landmines about and this book helps one carefully avoid them while at the same time being a good introduction into OO design and intent.

Here are two I haven't seen mentioned:
I wish I had read "Ruminations on C++" by Koenig and Moo much sooner. That was the book that made OO concepts really click for me.
And I recommend Michael Abrash's "Zen of Code Optimization" for anyone else planning on starting a programming career in the mid 90s.

Perfect Software: And Other Illusions about Testing


Perfect Software: And Other Illusions about Testing by Gerald M. Weinberg

ISBN-10: 0932633692

ISBN-13: 978-0932633699

Rapid Development by McConnell

The most influential programming book for me was Enough Rope to Shoot Yourself in the Foot by Allen Holub.

Cover of the book

O, well, how long ago it was.

I have a few good books that strongly influenced me that I've not seen on this list so far:

The Psychology of Everyday Things by Donald Norman. The general principles of design for other people. This may seem to be mostly good for UI but if you think about it, it has applications almost anywhere there is an interface that someone besides the original developer has to work with; e. g. an API and designing the interface in such a way that other developers form the correct mental model and get appropriate feedback from the API itself.

The Art of Software Testing by Glen Myers. A good, general introduction to testing software; good for programmers to read to help them think like a tester i. e. think of what may go wrong and prepare for it.

By the way, I realize the question was the "Single Most Influential Book" but the discussion seems to have changed to listing good books for developers to read so I hope I can be forgiven for listing two good books rather than just one.

alt text

C++ How to Program It is good for beginner.This is excellent book that full complete with 1500 pages.

Effective C++ and More Effective C++ by Scott Myers.

Inside the C++ object model by Stanley Lippman

I bough this when I was a complete newbie and took me from only knowing that Java existed to a reliable team member in a short time

Not a programming book, but still a very important book every programmer should read:

Orbiting the Giant Hairball by Gordon MacKenzie

The Pragmatic programmer was pretty good. However one that really made an impact when I was starting out was :

Windows 95 System Programming Secrets"

I know - it sounds and looks a bit cheesy on the outside and has probably dated a bit - but this was an awesome explanation of the internals of Win95 based on the Authors (Matt Pietrek) investigations using his own own tools - the code for which came with the book. Bear in mind this was before the whole open source thing and Microsoft was still pretty cagey about releasing documentation of internals - let alone source. There was some quote in there like "If you are working through some problem and hit some sticking point then you need to stop and really look deeply into that piece and really understand how it works". I've found this to be pretty good advice - particularly these days when you often have the source for a library and can go take a look. Its also inspired me to enjoy diving into the internals of how systems work, something that has proven invaluable over the course of my career.

Oh and I'd also throw in effective .net - great internals explanation of .Net from Don Box.

I recently read Dreaming in Code and found it to be an interesting read. Perhaps more so since the day I started reading it Chandler 1.0 was released. Reading about the growing pains and mistakes of a project team of talented people trying to "change the world" gives you a lot to learn from. Also Scott brings up a lot of programmer lore and wisdom in between that's just an entertaining read.

Beautiful Code had one or two things that made me think differently, particularly the chapter on top down operator precedence.


@Juan: I know Juan, I know - but there are some things that can only be learned by actually getting down to the task at hand. Speaking in abstract ideals all day simply makes you into an academic. It's in the application of the abstract that we truly grok the reason for their existence. :P

@Keith: Great mention of "The Inmates are Running the Asylum" by Alan Cooper - an eye opener for certain, any developer that has worked with me since I read that book has heard me mention the ideas it espouses. +1

I found the The Algorithm Design Manual to be a very beneficial read. I also highly recommend Programming Pearls.

This one isnt really a book for the beginning programmer, but if you're looking for SOA design books, then SOA in Practice: The Art of Distributed System Design is for you.

For me it was Design Patterns Explained it provided an 'Oh that's how it works' moment for me in regards to design patterns and has been very useful when teaching design patterns to others.

Code Craft by Pete Goodliffe is a good read!

Code Craft

The first book that made a real impact on me was Mastering Turbo Assembler by Tom Swan.

Other books that have had an impact was Just For Fun by Linus Torvalds and David Diamond and of course The Pragmatic Programmer by Andrew Hunt and David Thomas.

In addition to other people's suggestions, I'd recommend either acquiring a copy of SICP, or reading it online. It's one of the few books that I've read that I feel greatly increased my skill in designing software, particularly in creating good abstraction layers.

A book that is not directly related to programming, but is also a good read for programmers (IMO) is Concrete Mathematics. Most, if not all of the topics in it are useful for programmers to know about, and it does a better job of explaining things than any other math book I've read to date.

For me "Memory as a programming concept in C and C++" really opened my eyes to how memory management really works. If you're a C or C++ developer I consider it a must read. You will defiantly learn something or remember things you might have forgotten along the way.

Agile Software Development with Scrum by Ken Schwaber and Mike Beedle.

I used this book as the starting point to understanding Agile development.

Systemantics: How Systems Work and Especially How They Fail. Get it used cheap. But you might not get the humor until you've worked on a few failed projects.

The beauty of the book is the copyright year.

Probably the most profound takeaway "law" presented in the book:

The Fundamental Failure-Mode Theorem (F.F.T.): Complex systems usually operate in failure mode.

The idea being that there are failing parts in any given piece of software that are masked by failures in other parts or by validations in other parts. See a real-world example at the Therac-25 radiation machine, whose software flaws were masked by hardware failsafes. When the hardware failsafes were removed, the software race condition that had gone undetected all those years resulted in the machine killing 3 people.

It seems most people have already touched on the some very good books. One which really helped me out was Effective C#: 50 Ways to Improve your C#. I'd be remiss if I didn't mention The Tao of Pooh. Philosophy books can be good for the soul, and the code.

Discrete Mathematics For Computer Scientists

Discrete Mathematics For Computer Scientists by J.K. Truss.

While this doesn't teach you programming, it teaches you fundamental mathematics that every programmer should know. You may remember this stuff from university, but really, doing predicate logic will improve you programming skills, you need to learn Set Theory if you want to program using collections.

There really is a lot of interesting information in here that can get you thinking about problems in different ways. It's handy to have, just to pick up once in a while to learn something new.

I saw a review of Software Factories: Assembling Applications with Patterns, Models, Frameworks, and Tools on a blog talking also about XI-Factory, I read it and I must say this book is a must read. Altough not specifically targetted to programmers, it explains very clearly what is happening in the programming world right now with Model-Driven Architecture and so on..

Solid Code Optimizing the Software Development Life Cycle

Although the book is only 300 pages and favors Microsoft technologies it still offers some good language agnostic tidbits.

Managing Gigabytes is an instant classic for thinking about the heavy lifting of information.

My vote is "How to Think Like a Computer Scientist: Learning With Python" It's available both as a book and as a free e-book.

It really helped me to understand the basics of not just Python but programming in general. Although it uses Python to demonstrate concepts, they apply to most, if not all, programming languages. Also: IT'S FREE!

Object-Oriented Programming in Turbo C++. Not super popular, but it was the one that got me started, and was the first book that really helped me grok what an object was. Read this one waaaay back in high school. It sort of brings a tear to my eye...

My high school math teacher lent me a copy of Are Your Lights Figure Problem that I have re-read many times. It has been invaluable, as a developer, and in life generally.

I'm reading now Agile Software Development, Principles, Patterns and Practices. For those interested in XP and Object-Oriented Design, this is a classic reading.

alt text

Kernighan & Plauger's Elements of Programming Style. It illustrates the difference between gimmicky-clever and elegant-clever.

to get advanced in prolog i like these two books:

The Art of Prolog

The Craft of Prolog

really opens the mind for logic programming and recursion schemes.

Here's an excellent book that is not as widely applauded, but is full of deep insight: Agile Software Development: The Cooperative Game, by Alistair Cockburn.

What's so special about it? Well, clearly everyone has heard the term "Agile", and it seems most are believers these days. Whether you believe or not, though, there are some deep principles behind why the Agile movement exists. This book uncovers and articulates these principles in a precise, scientific way. Some of the principles are (btw, these are my words, not Alistair's):

  1. The hardest thing about team software development is getting everyone's brains to have the same understanding. We are building huge, elaborate, complex systems which are invisible in the tangible world. The better you are at getting more peoples' brains to share deeper understanding, the more effective your team will be at software development. This is the underlying reason that pair programming makes sense. Most people dismiss it (and I did too initially), but with this principle in mind I highly recommend that you give it another shot. You wind up with TWO people who deeply understand the subsystem you just built ... there aren't many other ways to get such a deep information transfer so quickly. It is like a Vulcan mind meld.
  2. You don't always need words to communicate deep understanding quickly. And a corollary: too many words, and you exceed the listener/reader's capacity, meaning the understanding transfer you're attempting does not happen. Consider that children learn how to speak language by being "immersed" and "absorbing". Not just language either ... he gives the example of some kids playing with trains on the floor. Along comes another kid who has never even SEEN a train before ... but by watching the other kids, he picks up the gist of the game and plays right along. This happens all the time between humans. This along with the corollary about too many words helps you see how misguided it was in the old "waterfall" days to try to write 700 page detailed requirements specifications.

There is so much more in there too. I'll shut up now, but I HIGHLY recommend this book!

alt text

The Back of the Napkin, by Dan Roam.

The Back of the Napkin

A great book about visual thinking techniques. There is also an expanded edition now. I can't speak to that version, as I do not own it; yet.

Agile Software Development by Alistair Cockburn

Do users ever touch your code? If you're not doing solely back-end work, I recommend About Face: The Essentials of User Interface Design — now in its third edition (linked). I used to think my users were stupid because they didn't "get" my interfaces. I was, of course, wrong. About Face turned me around.

"Writing Solid Code: Microsoft's Techniques for Developing Bug-Free C Programs (Microsoft Programming Series)" by Steve MacGuire.

Interesting what a large proportion the books mentioned here are C/C++ books.

While not strictly a software development book, I would highly recommend that Don't Make me Think! be considered in this list.

As so many people have listed Head First Design Patterns, which I agree is a very good book, I would like to see if so many people aware of a title called Design Patterns Explained: A New Perspective on Object-Oriented Design.

This title deals with design patterns excellently. The first half of the book is very accessible and the remaining chapters require only a firm grasp of the content already covered The reason I feel the second half of the book is less accessible is that it covers patterns that I, as a young developer admittedly lacking in experience, have not used much.

This title also introduces the concept behind design patterns, covering Christopher Alexander's initial work in architecture to the GoF first implementing documenting patterns in SmallTalk.

I think that anyone who enjoyed Head First Design Patterns but still finds the GoF very dry, should look into Design Patterns Explained as a much more readable (although not quite as comprehensive) alternative.

Even though i've never programmed a game this book helped me understand a lot of things in a fun way.

How influential a book is often depends on the reader and where they were in their career when they read the book. I have to give a shout-out to Head First Design Patterns. Great book and the very creative way it's written should be used as an example for other tech book writers. I.e. it's written in order to facilitate learning and internalizing the concepts.

Head First Design Patterns

97 Things Every Programmer Should Know

alt text

This book pools together the collective experiences of some of the world's best programmers. It is a must read.

Extreme Programming Explained: Embrace Change by Kent Beck. While I don't advocate a hardcore XP-or-the-highway take on software development, I wish I had been introduced to the principles in this book much earlier in my career. Unit testing, refactoring, simplicity, continuous integration, cost/time/quality/scope - these changed the way I looked at development. Before Agile, it was all about the debugger and fear of change requests. After Agile, those demons did not loom as large.

One of my personal favorites is Hacker's Delight, because it was as much fun to read as it was educational.

I hope the second edition will be released soon!

You.Next(): Move Your Software Development Career to the Leadership Track ~ Michael C. Finley (Author), Honza Fedák (Author) link text

I've been arounda while, so most books that I have found influential don't necessarily apply today. I do believe it is universally important to understand the platform that you are developing for (both hardware and OS). I also think it's important to learn from other peoples mistakes. So two books I would recommend are:

Computing Calamities and In Search of Stupidity: Over Twenty Years of High Tech Marketing Disasters

Working Effectively with Legacy Code is a really amazing book that goes into great detail about how to properly unit test your code and what the true benefit of it is. It really opened my eyes.

I've heard that, in C++, the static_cast function should be preferred to C-style or simple function-style casting. Is this true? Why?

  1. Allows casts to be found easily in your code using grep or similar tools.
  2. Makes it explicit what kind of cast you are doing, and engaging the compiler's help in enforcing it. If you only want to cast away const-ness, then you can use const_cast, which will not allow you to do other types of conversions.
  3. Casts are inherently ugly -- you as a programmer are overruling how the compiler would ordinarily treat your code. You are saying to the compiler, "I know better than you." That being the case, it makes sense that performing a cast should be a moderately painful thing to do, and that they should stick out in your code, since they are a likely source of problems.

See Effective C++ Introduction

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.

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.


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


Online Tutorials
The tutorial on 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/.

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


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?
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


Online Tutorials - 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.


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


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


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.


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.

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


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#
C# to the point - suggested by tamberg as a short text that explains the language in amazing depth


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


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


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.


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.


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# 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:


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

From what I saw in this post I decided to start reading the book Effective C++.

But now that there are many new features because of C++11 and that a few of the good practices changed, I'm not sure whether or not it is actually a good idea. Has the advent of C++11 deprecated any of the advice contained in Effective C++? If so, which topics should I avoid?

This what Scott Meyers himself had to say about it on his own blog

Which may lead you to wonder whether the information and advice in this pre-C++0x edition of Effective C++ remains relevant. I'm pleased to report that it does. Surprisingly so, in fact. Having spent nearly two years steeped in the details of C++0x, I expected to groan a bit as I reviewed this book's table of contents with C++0x in mind. Surely some Items would be inappropriate. But the advice I found proved sound. Should C++0x developers prefer consts, enums, and inlines to #defines (Item 2)? They should. Should they prevent exceptions from leaving destructors (Item 8)? Certainly. Should they use objects to manage resources? Declare data members private? Consider alternatives to virtual functions? Factor parameter-independent code out of templates? (Items 13, 22, 35, and 44.) Yes, yes, yes, yes! My goal has always been for Effective C++'s table of contents to summarize the advice in the book, and that summary remains just as applicable to C++0x development as to “traditional” C++ development. C++0x is a bigger language, and in some ways it's a different one, but the core techniques for making effective use of “old” C++ are core for the effective use of C++0x, too.

This doesn't mean that this Effective C++ is a perfect match for C++0x. The book doesn't discuss features new to C++0x, so Items about making effective use of those features are missing. A C++0xified Effective C++ would certainly have Items devoted to move operations, to uniform initialization, and to lambda expressions, and it'd probably have an entire chapter on making effective use of the concurrency API. Such a book would also contain different examples, e.g., ones making use of auto variables, range-based for loops, in-class default initializers, as well as the occasional variadic template. To the extent that this book falls short in its support for C++0x, the errors are those of omission, not commission.

UPDATE: the new title Effective Modern C++ has been for sale since November 2014 from O'Reilly and Amazon (and many others that you can google for).

int main( const int argc , const char[] const argv)

As Effective C++ Item#3 states "Use const whenever possible", I start thinking "why not make these 'constant' parameters const"?.

Is there any scenario in which the value of argc is modified in a program?

In this case, history is a factor. C defined these inputs as "not constant", and compatibility with (a good portion of) existing C code was an early goal of C++.

Some UNIX APIs, such as getopt, actually do manipulate argv[], so it can't be made const for that reason also.

(Aside: Interestingly, although getopt's prototype suggests it won't modify argv[] but may modify the strings pointed to, the Linux man page indicates that getopt permutes its arguments, and it appears they know they're being naughty. The man page at the Open Group does not mention this permutation.)

Putting const on argc and argv wouldn't buy much, and it would invalidate some old-school programming practices, such as:

// print out all the arguments:
while (--argc)
    std::cout << *++argv << std::endl;

I've written such programs in C, and I know I'm not alone. I copied the example from somewhere.

I remember first learning about vectors in the STL and after some time, I wanted to use a vector of bools for one of my projects. After seeing some strange behavior and doing some research, I learned that a vector of bools is not really a vector of bools.

Are there any other common pitfalls to avoid in C++?

Some must have C++ books that will help you avoid common C++ pitfalls:

Effective C++
More Effective C++
Effective STL

The Effective STL book explains the vector of bools issue :)

I've already mentioned it a few times, but Scott Meyers' books Effective C++ and Effective STL are really worth their weight in gold for helping with C++.

Come to think of it, Steven Dewhurst's C++ Gotchas is also an excellent "from the trenches" resource. His item on rolling your own exceptions and how they should be constructed really helped me in one project.

I wanted to ask about a specific point made in Effective C++.

It says:

A destructor should be made virtual if a class needs to act like a polymorphic class. It further adds that since std::string does not have a virtual destructor, one should never derive from it. Also std::string is not even designed to be a base class, forget polymorphic base class.

I do not understand what specifically is required in a class to be eligible for being a base class (not a polymorphic one)?

Is the only reason that I should not derive from std::string class is it does not have a virtual destructor? For reusability purpose a base class can be defined and multiple derived class can inherit from it. So what makes std::string not even eligible as a base class?

Also, if there is a base class purely defined for reusability purpose and there are many derived types, is there any way to prevent client from doing Base* p = new Derived() because the classes are not meant to be used polymorphically?

I think this statement reflects the confusion here (emphasis mine):

I do not understand what specifically is required in a class to be eligible for being a base clas (not a polymorphic one)?

In idiomatic C++, there are two uses for deriving from a class:

  • private inheritance, used for mixins and aspect oriented programming using templates.
  • public inheritance, used for polymorphic situations only. EDIT: Okay, I guess this could be used in a few mixin scenarios too -- such as boost::iterator_facade -- which show up when the CRTP is in use.

There is absolutely no reason to publicly derive a class in C++ if you're not trying to do something polymorphic. The language comes with free functions as a standard feature of the language, and free functions are what you should be using here.

Think of it this way -- do you really want to force clients of your code to convert to using some proprietary string class simply because you want to tack on a few methods? Because unlike in Java or C# (or most similar object oriented languages), when you derive a class in C++ most users of the base class need to know about that kind of a change. In Java/C#, classes are usually accessed through references, which are similar to C++'s pointers. Therefore, there's a level of indirection involved which decouples the clients of your class, allowing you to substitute a derived class without other clients knowing.

However, in C++, classes are value types -- unlike in most other OO languages. The easiest way to see this is what's known as the slicing problem. Basically, consider:

int StringToNumber(std::string copyMeByValue)
    std::istringstream converter(copyMeByValue);
    int result;
    if (converter >> result)
        return result;
    throw std::logic_error("That is not a number.");

If you pass your own string to this method, the copy constructor for std::string will be called to make a copy, not the copy constructor for your derived object -- no matter what child class of std::string is passed. This can lead to inconsistency between your methods and anything attached to the string. The function StringToNumber cannot simply take whatever your derived object is and copy that, simply because your derived object probably has a different size than a std::string -- but this function was compiled to reserve only the space for a std::string in automatic storage. In Java and C# this is not a problem because the only thing like automatic storage involved are reference types, and the references are always the same size. Not so in C++.

Long story short -- don't use inheritance to tack on methods in C++. That's not idiomatic and results in problems with the language. Use non-friend, non-member functions where possible, followed by composition. Don't use inheritance unless you're template metaprogramming or want polymorphic behavior. For more information, see Scott Meyers' Effective C++ Item 23: Prefer non-member non-friend functions to member functions.

EDIT: Here's a more complete example showing the slicing problem. You can see it's output on

#include <ostream>
#include <iomanip>

struct Base
    int aMemberForASize;
    Base() { std::cout << "Constructing a base." << std::endl; }
    Base(const Base&) { std::cout << "Copying a base." << std::endl; }
    ~Base() { std::cout << "Destroying a base." << std::endl; }

struct Derived : public Base
    int aMemberThatMakesMeBiggerThanBase;
    Derived() { std::cout << "Constructing a derived." << std::endl; }
    Derived(const Derived&) : Base() { std::cout << "Copying a derived." << std::endl; }
    ~Derived() { std::cout << "Destroying a derived." << std::endl; }

int SomeThirdPartyMethod(Base /* SomeBase */)
    return 42;

int main()
    Derived derivedObject;
        //Scope to show the copy behavior of copying a derived.
        Derived aCopy(derivedObject);

When I compiled my C++ code with GCC 4.3 for the first time, (after having compiled it successfully with no warnings on 4.1, 4.0, 3.4 with the -Wall -Wextra options) I suddenly got a bunch of errors of the form warning: type qualifiers ignored on function return type.

Consider temp.cpp:

class Something
    const int getConstThing() const {
        return _cMyInt;
    const int getNonconstThing() const {
        return _myInt;

    const int& getConstReference() const {
        return _myInt;
    int& getNonconstReference() {
        return _myInt;

    void setInt(const int newValue) {
        _myInt = newValue;

    Something() : _cMyInt( 3 ) {
        _myInt = 2;
    const int _cMyInt;
    int _myInt;

Running g++ temp.cpp -Wextra -c -o blah.o:

temp.cpp:4: warning: type qualifiers ignored on function return type
temp.cpp:7: warning: type qualifiers ignored on function return type

Can someone tell me what I am doing wrong that violates the C++ standard? I suppose that when returning by value, the leading const is superfluous, but I'm having trouble understanding why it's necessary to generate a warning with it. Are there other places where I should leave off the const?

Scott Meyers pointed out that there's pretty good reason why someone would want to return const values. Here's an example:

int some_calculation(int a, int b) { int res = 0; /* ... */ return res; }

/* Test if the result of the calculation equals 40.*/
if (some_calculation(3,20) = 40)


Do you see what I did wrong? This code is absolutely correct and should compile. The problem is that the compiler didn't understand that you intended tocompare instead of assign the value 40.

With a const return value the above example won't compile. Well, at least if the compiler doesn't discard the const keyword.

I'm reading Scott Meyers' Effective C++. He is talking about traits classes, I understood that I need them to determine the type of the object during compilation time, but I can't understand his explanation about what these classes actually do? (from technical point of view)

Perhaps you’re expecting some kind of magic that makes type traits work. In that case, be disappointed – there is no magic. Type traits are manually defined for each type. For example, consider iterator_traits, which provides typedefs (e.g. value_type) for iterators.

Using them, you can write

iterator_traits<vector<int>::iterator>::value_type x;
iterator_traits<int*>::value_type y;
// `x` and `y` have type int.

But to make this work, there is actually an explicit definition somewhere in the <iterator> header, which reads something like this:

template <typename T>
struct iterator_traits<T*> {
    typedef T value_type;
    // …

This is a partial specialization of the iterator_traits type for types of the form T*, i.e. pointers of some generic type.

In the same vein, iterator_traits are specialized for other iterators, e.g. typename vector<T>::iterator.

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?

Every so often, I'll have to switch between languages for the majority of the code I write (whether for work or for play). I find that C++ is one of those languages that requires a lot of mental cache space, so if I take a long break from it, then I forget a lot of the details. Even things like adding items to an STL container or using the static storage keyword in various contexts get all jumbled up ("is it add, append, push...oh, it's push_back").

So what essential tidbits do you like to have loaded into your brain when you're writing C++?

Edit: I should say, I'd like to be able to bookmark this page and use it as my cheatsheet :)

Since I work in C++ all the time I keep most of the syntax in my head. For library reference I use sgi and Josuttis' book. When I haven't done C++ for a while and really want a refresher I go back to Effective C++.

When I need to ansewer a deeper question I'll refer to the standard or Stroustrup's book.

When all else fails, google and stackoverflow are great tools.

I have a Phone interview coming up next with with a company which works in financial software industry. The interview is mainly going to be in C++ and problem solving and logic. Please tell me the method of preparation for this interview. I have started skimming through Thinking in C++ and brushing up the concepts. Is there any other way I can prepare?? Please help.


Thank you all everyone for the advice. I just want to add that I am currently fresh out of grad school and have no previous experience. So Can you suggest some type of questions that will be asked to new grads??

Read (or skim, depending on how much time you have to prepare) "Large-Scale C++ Software Design" by John Lakos. Chances are, you will need it.

Make sure you know your basic data structures and algorithms. You're more likely to be asked about that stuff than something higher up the food chain. Those are usually saved for the in-person interview.

Put another way: be solid with the fundamentals and solid with your C++ syntax. Also, knowledge of common libraries like STL and Boost couldn't hurt...but be sure you know what those libraries give you! In the end phone screens are there to cull out people who can't do the basics. Prove you can and you should move on to the next step. Good luck!

Here's some links of interview questions to check out:

Now, for completion's sake, some books:

Are there some drawbacks of such implementation of copy-constructor?

Foo::Foo(const Foo& i_foo)
   *this = i_foo;

As I remember, it was recommend in some book to call copy constructor from assignment operator and use well-known swap trick, but I don't remember, why...

You're looking for Scott Meyers' Effective C++ Item 12: Copy all parts of an object.

I'd like to learn how to use RAII in c++. I think I know what it is, but have no idea how to implement it in my programs. A quick google search did not show any nice tutorials.

Does any one have any nice links to teach me RAII?

The reference that I personally have found most helpful on the topic of RAII is the book Exceptional C++ by Herb Sutter.

Many of the topics covered in that book are touched on in the Guru of the Week articles by Sutter. Those articles are available at

Item 13 of "Effective C+" is also pretty useful

Just would like some thoughts of what you think about my strategy to learn C++. While I understand that it takes years to master a programming language, I simply want to get to the point where I can be considered competent as quickly as possible. Why quickly? Well when I say quickly I'm really saying I'm committed, and that I don't want it to take forever where forever is never. If it takes five years to become competent, it takes five years. I'm not expecting 24 hours or 30 days.

About me: I don't have a CS degree, I have an anthropology degree and a Masters in library science. Learning the CS fundamentals such as Big O notation, and basics such as binary trees and linked lists, sort algorithms has been a challenge. Probably nothing substitutes a good CS degree. :( I do have many years programming experience, starting with PHP in 2001, ActionScript, 2003, JavaScript soon after. I have been writing programs in Python for about two years now and I have learned C (by reading the K&R book and writing some programs), but I'm probably not going to get hired for a C job. Also recently learned Objective C. I work as a JavaScript & Python, & CSS developer at a website at the moment.

Anyhow, this is my strategy: Read the Stroustrup book (I just started on Part I) and at the same time start a simple C++ project, while also doing many of the Stroustrup exercises.


Also be sure to check out How Not to Program in C++

Bjarne's book is fantastic, especially for C++ syntax, but the one book that will really make you a competent C++ programmer is Meyers' Effective C++. Get it. Read it.

I as well do not have a CS degree, but I work for a silicon valley startup. It is possible, you just have to be aware of what's out there and never stop learning. Many students who graduate with a computer science degree end up working in a language they didn't study, so be sure to hit the fundamentals. If you hear something that's unfamiliar to you, be sure to find a good book and a coffee shop and get to it. The C++ will come in time - with Stroustrup and Meyers, you've got 90% of what it takes to be good at C++

If you have a strong handle on C, then C++ is not a huge leap once you have a good handle on the OOP concepts....which hopefully you have from becoming proficient in Python. Coming from C, the biggest thing to learn in C++ is really getting familiar with the Standard Template Library (STL) and all the subtle things come along with using it.

Personally, I think the Stroustrup book is not all that great for learning the language, it's more of a reference. I would recommend C++ Primer Plus as a better book and the Effective C++ books by Meyers for really learning to use the language coherently.

I don't htink the Stroustrop book is a good place to start. It's more of an advanced/reference book. I would start with Thinking in C++ (Volume 1) (and Volume 2. And write lots of code. Once you've got a basic handle on the code I would get the Scott Meyer Effective C++ books and definitely the Stroustrop book.

I'm trying to find a least-resistance path from C# to C++, and while I feel I handle C# pretty well after two solid years, I'm still not sure I've gotten the "groove" of C++, despite numerous attempts.

Are there any particular books or websites that might be suitable for this transition?

About two years ago, I made the switch from C# to C++ (after 10 years of writing java). The most useful book for me was Bruce Eckel's Thinking in C++ [AMZN]. You can also read the book online at Eckel's website. It's a well-written book--the kind you can read in bed--that's also useful as a keyboard-side reference. It assumes a significant level of comfort with OO and general programming concepts.

Stroustrup [AMZN] is invaluable as a reference, but basically impenetrable unless you're trying to answer a very specific question--and even then, it's a struggle. I haven't cracked my K&R [AMZN] in a few years. I don't think it's got much value as a C++ reference. Myers' Effective C++ [AMZN] (and, once you get there, Effective STL [AMZN]) are fantastic books. They're very specific, though (e.g., "36. Design functor classes for pass-by-value"), and hence not as useful as Eckel for making the transition.

My experience writing C++ after many years writing managed languages has been great. C++ is a hundred times more expressive than C#, and extremely satisfying to write--where it's warranted. On the other hand, on the rare occasions when I still get to write C#, I'm always amazed by how quickly and succinctly I can get things done.

Anyway, Eckel's Effective C++ can help you make the transition. There's a second volume that's good, but not as good. Stick with the original.

Good luck!

You should read one of the other books posted, but then also The Design & Evolution of C++. It helps you to get inside the head of what the language is trying to do.

recently I've been reading through Scott Meyers's excellent Effective C++ book. In one of the last tips he covered some of the features from TR1 - I knew many of them via Boost.

However, there was one that I definitely did NOT recognize: tr1::reference_wrapper.

How and when would I use tr1::reference_wrapper?

It's like boost::ref, as far as I know. Basically, a reference which can be copied. Very useful when binding to functions where you need to pass parameters by reference.

For example (using boost syntax):

void Increment( int& iValue )

int iVariable = 0;
boost::function< void () > fIncrementMyVariable = boost::bind( &Increment, boost::ref( iVariable ));


This Dr. Dobbs article has some info.

Hope this is right, and helpful. :)

What is the difference between these two terms, and why do I need mutable?

Scott Meyers, Effective C++, Item 3:

Use const whenever possible

has an excellent discussion (with examples) on this topic. Its hard to write better than Scott!

Note also that physical-constness is also known as bitwise-constness.

In several introductory texts on Object-oriented programming, I've come across the above statement.

From wikipedia, "In OOP, each object is capable of receiving messages, processing data, and sending messages to other objects and can be viewed as an independent 'machine' with a distinct role or responsibility."

What exactly does the statement mean in code?

    class A


    class B


class C{
 A a=new A();
 B b=new B();
 a.methodA(); // does this mean msgs passing??
 b.methodB(); // or does this?? I may be completely off-track here..

If we are talking about OOP than the term "message passing" comes from Smalltalk. In a few words the Smalltalk basic principles are:

  1. Object is the basic unit of object-oriented system.
  2. Objects have their own state.
  3. Objects communicate by sending and receiving messages.

If you are interested in Smalltalk take a look at Pharo or Squeak.

Java/C#/C++ and many other languages use slightly different approach probably derived from Simula. You invoke a method instead of pass a message.

I think this terms are more or less equivalent. May be the only interesting difference is that message passing (at least in Smalltalk) always rely on dynamic dispatch and late binding while in the case of method invocation one can use static dispatch and early binding too. For example, C++ (AFAIK) does early binding by default until "virtual" keyword appears somewhere...

Anyway, regardless of which formalism do your programming language use for communication between two objects (message passing or method invocation) it's always considered a good OOP style to forbid direct access to instance variables in Smalltalk terminology or data members in C++ terminology or whatever term is used in your programming language.

Smalltalk directly prohibits access to instance variables at the syntax level. As I mentioned above objects in Smalltalk program can interact only by passing/receiving messages. Many other languages allow access to instance variables at the syntax level but it's considered a bad practice. For example, the famous Effective C++ book contains the corresponding recommendation: Item 22: Declare data members private.

The reasons are:

  • syntactic consistency (the only way for clients to access an object is via member functions or message passing);
  • more precise control over the accessibility of data members (you can implement no access, read-only access, read-write access, and even write-only access);
  • you can later replace the data member without breaking your public interface.

The last one is the most important. It's the essence of encapsulation - information hiding on the class level.

The point about encapsulation is more important than it might initially appear. If you hide your data members from your clients (i.e., encapsulate them), you can ensure that class invariants are always maintained, because only member functions can affect them. Furthermore, you reserve the right to change your implementation decisions later. If you don't hide such decisions, you'll soon find that even if you own the source code to a class, your ability to change anything public is extremely restricted, because too much client code will be broken. Public means unencapsulated, and practically speaking, unencapsulated means unchangeable, especially for classes that are widely used. Yet widely used classes are most in need of encapsulation, because they are the ones that can most benefit from the ability to replace one implementation with a better one.

(с) Scott Meyers, Effective C++: 55 Specific Ways to Improve Your Programs and Designs (3rd Edition)

I occasionally have classes with private static data members. I'm currently debating if I should replace these with static variables in an unnamed namespace in the implementation file. Other that not being able to use these variables in inline methods, are there any other drawbacks? The advantage that I see is that is hides them completely from the users of the class.

I disagree with the other answers. Keep as much out of the class definition as possible.

In Scott Meyers' Effective C++ 3rd edition he recommends preferring non-friend functions to class methods. In this way the class definition is as small as possible, the private data is accessed in as few places as possible (encapsulated).

Following this principle further leads to the pimpl idiom. However, balance is needed. Make sure your code is maintainable. Blindly, following this rule would lead you to make all your private methods file local and just pass in the needed members as parameters. This would improve encapsulation, but destroy maintainability.

All that said, file local objects are very hard to unit test. With some clever hacking you can access private members during unit tests. Accessing file local objects is a bit more involved.

I've been extensively using smart pointers (boost::shared_ptr to be exact) in my projects for the last two years. I understand and appreciate their benefits and I generally like them a lot. But the more I use them, the more I miss the deterministic behavior of C++ with regarding to memory management and RAII that I seem to like in a programming language. Smart pointers simplify the process of memory management and provide automatic garbage collection among other things, but the problem is that using automatic garbage collection in general and smart pointer specifically introduces some degree of indeterminisim in the order of (de)initializations. This indeterminism takes the control away from the programmers and, as I've come to realize lately, makes the job of designing and developing APIs, the usage of which is not completely known in advance at the time of development, annoyingly time-consuming because all usage patterns and corner cases must be well thought of.

To elaborate more, I'm currently developing an API. Parts of this API requires certain objects to be initialized before or destroyed after other objects. Put another way, the order of (de)initialization is important at times. To give you a simple example, let's say we have a class called System. A System provides some basic functionality (logging in our example) and holds a number of Subsystems via smart pointers.

class System {
    boost::shared_ptr< Subsystem > GetSubsystem( unsigned int index ) {
        assert( index < mSubsystems.size() );
        return mSubsystems[ index ];

    void LogMessage( const std::string& message ) {
        std::cout << message << std::endl;

    typedef std::vector< boost::shared_ptr< Subsystem > > SubsystemList;
    SubsystemList mSubsystems;    

class Subsystem {
    Subsystem( System* pParentSystem )
         : mpParentSystem( pParentSystem ) {

    ~Subsystem() {
         pParentSubsystem->LogMessage( "Destroying..." );
         // Destroy this subsystem: deallocate memory, release resource, etc.             

     Other stuff here

    System * pParentSystem; // raw pointer to avoid cycles - can also use weak_ptrs

As you can already tell, a Subsystem is only meaningful in the context of a System. But a Subsystem in such a design can easily outlive its parent System.

int main() {
        boost::shared_ptr< Subsystem > pSomeSubsystem;
            boost::shared_ptr< System > pSystem( new System );
            pSomeSubsystem = pSystem->GetSubsystem( /* some index */ );

        } // Our System would go out of scope and be destroyed here, but the Subsystem that pSomeSubsystem points to will not be destroyed.

     } // pSomeSubsystem would go out of scope here but wait a second, how are we going to log messages in Subsystem's destructor?! Its parent System is destroyed after all. BOOM!

    return 0;

If we had used raw pointers to hold subsystems, we would have destroyed subsystems when our system had gone down, of course then, pSomeSubsystem would be a dangling pointer.

Although, it's not the job of an API designer to protect the client programmers from themselves, it's a good idea to make the API easy to use correctly and hard to use incorrectly. So I'm asking you guys. What do you think? How should I alleviate this problem? How would you design such a system?

Thanks in advance, Josh

Problem Summary

There are two competing concerns in this question.

  1. Life-cycle management of Subsystems, allowing their removal at the right time.
  2. Clients of Subsystems need to know that the Subsystem they are using is valid.

Handling #1

System owns the Subsystems and should manage their life-cycle with it's own scope. Using shared_ptrs for this is particularly useful as it simplifies destruction, but you should not be handing them out because then you loose the determinism you are seeking with regard to their deallocation.

Handling #2

This is the more intersting concern to address. Describing the problem in more detail, you need clients to receive an object which behaves like a Subsystem while that Subsystem (and it's parent System) exists, but behaves appropriately after a Subsystem is destroyed.

This is easily solved by a combination of the Proxy Pattern, the State Pattern and the Null Object Pattern. While this may seem to be a bit complex of a solution, 'There is a simplicity only to be had on the other side of complexity.' As Library/API developers, we must go the extra mile to make our systems robust. Further, we want our systems to behave intuitively as a user expects, and to decay gracefully when they attempt to misuse them. There are many solutions to this problem, however, this one should get you to that all important point where, as you and Scott Meyers say, it is "easy to use correctly and hard to use incorrectly.'

Now, I am assuming that in reality, System deals in some base class of Subsystems, from which you derive various different Subsystems. I've introduced it below as SubsystemBase. You need to introduce a Proxy object, SubsystemProxy below, which implements the interface of SubsystemBase by forwarding requests to the object it is proxying. (In this sense, it is very much like a special purpose application of the Decorator Pattern.) Each Subsystem creates one of these objects, which it holds via a shared_ptr, and returns when requested via GetProxy(), which is called by the parent System object when GetSubsystem() is called.

When a System goes out of scope, each of it's Subsystem objects gets destructed. In their destructor, they call mProxy->Nullify(), which causes their Proxy objects to change their State. They do this by changing to point to a Null Object, which implements the SubsystemBase interface, but does so by doing nothing.

Using the State Pattern here has allowed the client application to be completely oblivious to whether or not a particular Subsystem exists. Moreover, it does not need to check pointers or keep around instances that should have been destroyed.

The Proxy Pattern allows the client to be dependent on a light weight object that completely wraps up the details of the API's inner workings, and maintains a constant, uniform interface.

The Null Object Pattern allows the Proxy to function after the original Subsystem has been removed.

Sample Code

I had placed a rough pseudo-code quality example here, but I wasn't satisfied with it. I've rewritten it to be a precise, compiling (I used g++) example of what I have described above. To get it to work, I had to introduce a few other classes, but their uses should be clear from their names. I employed the Singleton Pattern for the NullSubsystem class, as it makes sense that you wouldn't need more than one. ProxyableSubsystemBase completely abstracts the Proxying behavior away from the Subsystem, allowing it to be ignorant of this behavior. Here is the UML Diagram of the classes:

UML Diagram of Subsystem and System Hierarchy

Example Code:

#include <iostream>
#include <string>
#include <vector>

#include <boost/shared_ptr.hpp>

// Forward Declarations to allow friending
class System;
class ProxyableSubsystemBase;

// Base defining the interface for Subsystems
class SubsystemBase
    // pure virtual functions
    virtual void DoSomething(void) = 0;
    virtual int GetSize(void) = 0;

    virtual ~SubsystemBase() {} // virtual destructor for base class

// Null Object Pattern: an object which implements the interface to do nothing.
class NullSubsystem : public SubsystemBase
    // implements pure virtual functions from SubsystemBase to do nothing.
    void DoSomething(void) { }
    int GetSize(void) { return -1; }

    // Singleton Pattern: We only ever need one NullSubsystem, so we'll enforce that
    static NullSubsystem *instance()
      static NullSubsystem singletonInstance;
      return &singletonInstance;

    NullSubsystem() {}  // private constructor to inforce Singleton Pattern

// Proxy Pattern: An object that takes the place of another to provide better
//   control over the uses of that object
class SubsystemProxy : public SubsystemBase
  friend class ProxyableSubsystemBase;

    SubsystemProxy(SubsystemBase *ProxiedSubsystem)
      : mProxied(ProxiedSubsystem)

    // implements pure virtual functions from SubsystemBase to forward to mProxied
    void DoSomething(void) { mProxied->DoSomething(); }
    int  GetSize(void) { return mProxied->GetSize(); }

    // State Pattern: the initial state of the SubsystemProxy is to point to a
    //  valid SubsytemBase, which is passed into the constructor.  Calling Nullify()
    //  causes a change in the internal state to point to a NullSubsystem, which allows
    //  the proxy to still perform correctly, despite the Subsystem going out of scope.
    void Nullify()

      SubsystemBase *mProxied;

// A Base for real Subsystems to add the Proxying behavior
class ProxyableSubsystemBase : public SubsystemBase
  friend class System;  // Allow system to call our GetProxy() method.

      : mProxy(new SubsystemProxy(this)) // create our proxy object
      mProxy->Nullify(); // inform our proxy object we are going away

    boost::shared_ptr<SubsystemProxy> GetProxy() { return mProxy; }

    boost::shared_ptr<SubsystemProxy> mProxy;

// the managing system
class System
    typedef boost::shared_ptr< SubsystemProxy > SubsystemHandle;
    typedef boost::shared_ptr< ProxyableSubsystemBase > SubsystemPtr;

    SubsystemHandle GetSubsystem( unsigned int index )
        assert( index < mSubsystems.size() );
        return mSubsystems[ index ]->GetProxy();

    void LogMessage( const std::string& message )
        std::cout << "  <System>: " << message << std::endl;

    int AddSubsystem( ProxyableSubsystemBase *pSubsystem )
      LogMessage("Adding Subsystem:");
      return mSubsystems.size()-1;

      LogMessage("System is constructing.");

      LogMessage("System is going out of scope.");

    // have to hold base pointers
    typedef std::vector< boost::shared_ptr<ProxyableSubsystemBase> > SubsystemList;
    SubsystemList mSubsystems;

// the actual Subsystem
class Subsystem : public ProxyableSubsystemBase
    Subsystem( System* pParentSystem, const std::string ID )
      : mParentSystem( pParentSystem )
      , mID(ID)
         mParentSystem->LogMessage( "Creating... "+mID );

         mParentSystem->LogMessage( "Destroying... "+mID );

    // implements pure virtual functions from SubsystemBase
    void DoSomething(void) { mParentSystem->LogMessage( mID + " is DoingSomething (tm)."); }
    int GetSize(void) { return sizeof(Subsystem); }

    System * mParentSystem; // raw pointer to avoid cycles - can also use weak_ptrs
    std::string mID;

// Actual Use Example
int main(int argc, char* argv[])

  std::cout << "main(): Creating Handles H1 and H2 for Subsystems. " << std::endl;
  System::SubsystemHandle H1;
  System::SubsystemHandle H2;

  std::cout << "-------------------------------------------" << std::endl;
    std::cout << "  main(): Begin scope for System." << std::endl;
    System mySystem;
    int FrankIndex = mySystem.AddSubsystem(new Subsystem(&mySystem, "Frank"));
    int ErnestIndex = mySystem.AddSubsystem(new Subsystem(&mySystem, "Ernest"));

    std::cout << "  main(): Assigning Subsystems to H1 and H2." << std::endl;

    std::cout << "  main(): Doing something on H1 and H2." << std::endl;
    std::cout << "  main(): Leaving scope for System." << std::endl;
  std::cout << "-------------------------------------------" << std::endl;
  std::cout << "main(): Doing something on H1 and H2. (outside System Scope.) " << std::endl;
  std::cout << "main(): No errors from using handles to out of scope Subsystems because of Proxy to Null Object." << std::endl;

  return 0;

Output from the code:

main(): Creating Handles H1 and H2 for Subsystems.
  main(): Begin scope for System.
  <System>: System is constructing.
  <System>: Creating... Frank
  <System>: Adding Subsystem:
  <System>: Creating... Ernest
  <System>: Adding Subsystem:
  main(): Assigning Subsystems to H1 and H2.
  main(): Doing something on H1 and H2.
  <System>: Frank is DoingSomething (tm).
  <System>: Ernest is DoingSomething (tm).
  main(): Leaving scope for System.
  <System>: System is going out of scope.
  <System>: Destroying... Frank
  <System>: Destroying... Ernest
main(): Doing something on H1 and H2. (outside System Scope.)
main(): No errors from using handles to out of scope Subsystems because of Proxy to Null Object.

Other Thoughts:

  • An interesting article I read in one of the Game Programming Gems books talks about using Null Objects for debugging and development. They were specifically talking about using Null Graphics Models and Textures, such as a checkerboard texture to make missing models really stand out. The same could be applied here by changing out the NullSubsystem for a ReportingSubsystem which would log the call and possibly the callstack whenever it is accessed. This would allow you or your library's clients to track down where they are depending on something that has gone out of scope, but without the need to cause a crash.

  • I mentioned in a comment @Arkadiy that the circular dependency he brought up between System and Subsystem is a bit unpleasant. It can easily be remedied by having System derive from an interface on which Subsystem depends, an application of Robert C Martin's Dependency Inversion Principle. Better still would be to isolate the functionality that Subsystems need from their parent, write an interface for that, then hold onto an implementor of that interface in System and pass it to the Subsystems, which would hold it via a shared_ptr. For example, you might have LoggerInterface, which your Subsystem uses to write to the log, then you could derive CoutLogger or FileLogger from it, and keep an instance of such in System.
    Eliminating the Circular Dependency

Can anyone recommend any good resources for learning C++ Templates?

Many thanks.

I've found to be helpful on numerous occasions. Looks like they've got a pretty good intro to templates.

If its an actual book you're looking for, Effective C++ is a classic with a great section on templates.

Bruce Eckel's Thinking in C++ is how I learned about templates. The first volume has an introductory chapter and the second volume has an in-depth chapter on templates.

There's Bjarne Stroustrop's The C++ Programming Language which has a good chapter on them. And The C++ Standard Library: A Tutorial and Reference which is about the standard library, but would definitely help you get a better understanding of how templates could be used in the real world. .

This is a more advanced, but very useful, book on templates and template use.

Modern C++ Design

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?

I'm in high school and taking a class where basically we design our own course and choose what we learn. I've chosen to learn about C++ and game programming.

I'd like to learn as much about using C++ with OpenGL or DirectX or some other API as I can.

After I finish learning C++ where should I go? Can you recommend a book on game programming?

I too have once thought I knew most of C++... Then I read "Effective C++","Effective STL" , "C++ Gotchas" and "Modern C++ Design", and I realized just how wrong I was.

If you are looking to continue with gaming, C++ is a darn good place to start. You could also check out C# as it is used by Microsoft in XNA (XBox), Second Life, and by Unity on smart phones.

While I would not disagree with anybody about the math and reading you need to do, I think it is better to just roll up your sleeves and program. Read other people's code and then read so that you can understand why they are doing what they are doing.

If you think you know C++ well, the next step is to learn how to use it to make better software. For that, I would start with reading Effective C++.

If you really have a handle on C++ then perhaps this StackOverflow thread will answer your question about game books.

Personally, even if your goal is game programming, I would branch out from that to get a solid grounding as a developer.

Perhaps you should do a little web programming to get a feel for what that is all about. Maybe something like Ruby on Rails.

Alternatively, you could try to write a simple compiler or even an operating system to get a feel for what goes on under the hood and to learn that these too are just programs written by mortals.

Instead of writing your own, you could also get involved in an Open Source project. If I had the time, I would be all over spending time reading the code of Haiku and finding somewhere to contribute. Here is a list of open source game projects that you could consider joining as well.

Your chances of getting a decent job probably go up quite a bit if you know Java or .NET so those are also options. If you decide on .NET, I recommend checking out Mono.

I was wondering whether a design pattern or idiom exists to automatically register a class type. Or simpler, can I force a method to get called on a class by simply extending a base class?

For example, say I have a base class Animal and extending classes Tiger and Dog, and I have a helper function that prints out all classes that extend Animal.

So I could have something like:

struct AnimalManager
   static std::vector<std::string> names;
   static void registerAnimal(std::string name) { 
            //if not already registered
            names.push_back(name); }

struct Animal
   virtual std::string name() = 0;
   void registerAnimal() { AnimalManager::registerAnimal(name()); }
struct Tiger : Animal
   virtual std::string name() { return "Tiger"; }

So basically I would do:

Tiger t;

This could be worked into a static function as well. Is there any pattern (like a curiously recursive template) or something like that that can help me achieve this without explicitly having to call the registerAnimal method.

I want my class Animal to be extendible in the future and others might forget to call register, I'm looking for ways to prevent that besides documenting this (which I will anyway).

PS This is just an example, I'm not actually implementing animals.

This is a typical example where you want to do some sort of bookkeeping when an object is constructed. Item 9 in Scott Meyers "Effective C++" gives an example of this.

Basically you move all the bookkeeping stuff to base class. Derived class explicitly constructs base class and passes the information that is required for Base class construction. For example:

struct Animal
  Animal(std::string animal_type)

struct Dog : public Animal
  Dog() : Animal(animal_type()) {};

    static std::string animal_type()
      return "Dog";

As I've understand, when overloading operator=, the return value should should be a non-const reference.

A& A::operator=( const A& )
    // check for self-assignment, do assignment

    return *this;

It is non-const to allow non-const member functions to be called in cases like:

( a = b ).f();

But why should it return a reference? In what instance will it give a problem if the return value is not declared a reference, let's say return by value?

It's assumed that copy constructor is implemented correctly.

This is Item 10 of Scott Meyers' excellent book, Effective C++. Returning a reference from operator= is only a convention, but it's a good one.

This is only a convention; code that doesn't follow it will compile. However, the convention is followed by all the built-in types as well as by all the types in the standard library. Unless you have a good reason for doing things differently, don't.

I often hear people praise the compilation speed of C#. So far I have only made a few tiny applications, and indeed I noticed that compilation was very fast. However, I was wondering if this still holds for large applications. Do big C# projects compile faster than C++ projects of a similar size?

C++ is so slow to compile as the header files have to be reread and reparse every time they are included. Due to the way “#defines” work, it is very hard for a compiler to automatically pre-compile all header files. (Modula-2 made a much better job of this) Having 100s of headers read for each C++ file that is compiled is normal on a lot of C++ projects.

Sometimes incremental c++ compiles can be a lot faster than C#. If you have all your C++ header files (and design) in a very good state (see books like Large-Scale C++ Software Design, Effective C++) You can make a change to the implementation of a class that is used by most of the system and only have one dll recompile.

As C# does not have separate header files whenever you change the implantation of a class, all uses of the class get recompiled even if the public interface of the class has not changed. This can be reduced in C# by using “interface based programming” and “dependency injection” etc. But it is still a pain.

However on the whole I find that C# compiles fast enough, but large C++ projects are so slow to compile that I find myself not wanting to add a methods to a “base class” due to the time of the rebuild.

Having lots of Visual Studio projects with a handful of classes in each can slow down C# builds a lot. Combining related projects together and then “trusting” the developers not to use class that are private to a namespace can at times have a great benefit. (nDepends can be used to check for people breaking the rules)

(When trying to speed up C++ compiles I have found FileMon very useful. One project I worked on, the STL was added to a header file and the build got a lot slower. Just adding STL to the precompiled header file made a big difference! Therefore track your build time and investigate when it gets slower)

This is a very general question. I'm a self taught 'programmer' who programs in C#. A project I would like to work on would be made a whole lot easier (in the grand scheme of things) if I knew C++. How easy is it to move from C# to C++? Any pitfalls I should watch out for? And if I am using VS2010, can I program (not in the same class, but same project) something in both C# and C++?

I came the other way from c++ to c#. In many ways that was a relief. C++ has a lot more rules than c# particularly around memory allocation. The syntax can also be challenging and it is easy to wander off into out of bounds memory. C++ is however much more suitable for system level programming but with great power comes great responsibility.

I recommend first grabbing a copy of Scott Meyer's Effective C++ and read it cover to cover. This is the best resource I know of for getting the basics correct and without question improved the quality of the code I was producing, even as an "experienced" c++ developer. Then grab a unit test framework and take a look at a c++ kata (in this case an xcode project but should still be useful). And get familiar with the Standard Template Library which contains a lot of useful/efficient code/classes for containers, algorithms, etc.

Lastly, best of luck. Learning a new language is always a challenge and can be daunting but the payoff is generally worth it. If nothing else you will see your c# code with new eyes.

For illustrative purposes, let's say I want to implement a generic integer comparing function. I can think of a few approaches for the definition/invocation of the function.

(A) Function Template + functors

template <class Compare> void compare_int (int a, int b, const std::string& msg, Compare cmp_func) 
    if (cmp_func(a, b)) std::cout << "a is " << msg << " b" << std::endl;
    else std::cout << "a is not " << msg << " b" << std::endl;

struct MyFunctor_LT {
    bool operator() (int a, int b) {
        return a<b;

And this would be a couple of calls to this function:

MyFunctor_LT mflt;
MyFunctor_GT mfgt; //not necessary to show the implementation
compare_int (3, 5, "less than", mflt);
compare_int (3, 5, "greater than", mflt);

(B) Function template + lambdas

We would call compare_int like this:

compare_int (3, 5, "less than", [](int a, int b) {return a<b;});
compare_int (3, 5, "greater than", [](int a, int b) {return a>b;});

(C) Function template + std::function

Same template implementation, invocation:

std::function<bool(int,int)> func_lt = [](int a, int b) {return a<b;}; //or a functor/function
std::function<bool(int,int)> func_gt = [](int a, int b) {return a>b;}; 

compare_int (3, 5, "less than", func_lt);
compare_int (3, 5, "greater than", func_gt);

(D) Raw "C-style" pointers


void compare_int (int a, int b, const std::string& msg, bool (*cmp_func) (int a, int b)) 

bool lt_func (int a, int b) 
    return a<b;


compare_int (10, 5, "less than", lt_func); 
compare_int (10, 5, "greater than", gt_func);

With those scenarios laid out, we have in each case:

(A) Two template instances (two different parameters) will be compiled and allocated in memory.

(B) I would say also two template instances would be compiled. Each lambda is a different class. Correct me if I'm wrong, please.

(C) Only one template instance would be compiled, since template parameter is always te same: std::function<bool(int,int)>.

(D) Obviously we only have one instance.

Needless to day, it doesn't make a difference for such a naive example. But when working with dozens (or hundreds) of templates, and numerous functors, the compilation times and memory usage difference can be substantial.

Can we say that in many circumstances (i.e., when using too many functors with the same signature) std::function (or even function pointers) must be preferred over templates+raw functors/lambdas? Wrapping your functor or lambda with std::function may be very convenient.

I am aware that std::function (function pointer too) introduces an overhead. Is it worth it?

EDIT. I did a very simple benchmark using the following macros and a very common standard library function template (std::sort):

#define TEST(X) std::function<bool(int,int)>  f##X = [] (int a, int b) {return (a^X)<(b+X);}; \
std::sort (v.begin(), v.end(), f##X);

#define TEST2(X) auto f##X = [] (int a, int b) {return (a^X)<(b^X);}; \
std::sort (v.begin(), v.end(), f##X);

#define TEST3(X) bool(*f##X)(int, int) = [] (int a, int b) {return (a^X)<(b^X);}; \ 
std::sort (v.begin(), v.end(), f##X);

Results are the following regarding size of the generated binaries (GCC at -O3):

  • Binary with 1 TEST macro instance: 17009
  • 1 TEST2 macro instance: 9932
  • 1 TEST3 macro instance: 9820
  • 50 TEST macro instances: 59918
  • 50 TEST2 macro instances: 94682
  • 50 TEST3 macro instances: 16857

Even if I showed the numbers, it is a more qualitative than quantitative benchmark. As we were expecting, function templates based on the std::function parameter or function pointer scale better (in terms of size), as not so many instances are created. I did not measure runtime memory usage though.

As for the performance results (vector size is 1000000 of elements):

  • 50 TEST macro instances: 5.75s
  • 50 TEST2 macro instances: 1.54s
  • 50 TEST3 macro instances: 3.20s

It is a notable difference, and we must not neglect the overhead introduced by std::function (at least if our algorithms consist of millions of iterations).

As others have already pointed out, lambdas and function objects are likely to be inlined, especially if the body of the function is not too long. As a consequence, they are likely to be better in terms of speed and memory usage than the std::function approach. The compiler can optimize your code more aggressively if the function can be inlined. Shockingly better. std::function would be my last resort for this reason, among other things.

But when working with dozens (or hundreds) of templates, and numerous functors, the compilation times and memory usage difference can be substantial.

As for the compilation times, I wouldn't worry too much about it as long as you are using simple templates like the one shown. (If you are doing template metaprogramming, yeah, then you can start worrying.)

Now, the memory usage: By the compiler during compilation or by the generated executable at run time? For the former, same holds as for the compilation time. For the latter: Inlined lamdas and function objects are the winners.

Can we say that in many circumstances std::function (or even function pointers) must be preferred over templates+raw functors/lambdas? I.e. wrapping your functor or lambda with std::function may be very convenient.

I am not quite sure how to answer to that one. I cannot define "many circumstances".

However, one thing I can say for sure is that type erasure is a way to avoid / reduce code bloat due to templates, see Item 44: Factor parameter-independent code out of templates in Effective C++. By the way, std::function uses type erasure internally. So yes, code bloat is an issue.

I am aware that std::function (function pointer too) introduces an overhead. Is it worth it?

"Want speed? Measure." (Howard Hinnant)

One more thing: function calls through function pointers can be inlined (even across compilation units!). Here is a proof:

#include <cstdio>

bool lt_func(int a, int b) 
    return a<b;

void compare_int(int a, int b, const char* msg, bool (*cmp_func) (int a, int b)) {
    if (cmp_func(a, b)) printf("a is %s b\n", msg);
    else printf("a is not %s b\n", msg);

void f() {
  compare_int (10, 5, "less than", lt_func); 

This is a slightly modified version of your code. I removed all the iostream stuff because it makes the generated assembly cluttered. Here is the assembly of f():

    .string "a is not %s b\n"
    .string "less than"
    movl    $.LC2, %edx
    movl    $.LC1, %esi
    movl    $1, %edi
    xorl    %eax, %eax
    jmp __printf_chk

Which means, that gcc 4.7.2 inlined lt_func at -O3. In fact, the generated assembly code is optimal.

I have also checked: I moved the implementation of lt_func into a separate source file and enabled link time optimization (-flto). GCC still happily inlined the call through the function pointer! It is nontrivial and you need a quality compiler to do that.

Just for the record, and that you can actually feel the overhead of the std::function approach:

This code:

#include <cstdio>
#include <functional>

template <class Compare> void compare_int(int a, int b, const char* msg, Compare cmp_func) 
    if (cmp_func(a, b)) printf("a is %s b\n", msg);
    else printf("a is not %s b\n", msg);

void f() {
  std::function<bool(int,int)> func_lt = [](int a, int b) {return a<b;};
  compare_int (10, 5, "less than", func_lt); 

yields this assembly at -O3 (approx. 140 lines):

    .cfi_personality 0x3,__gxx_personality_v0
    .cfi_lsda 0x3,.LLSDA498
    pushq   %rbx
    .cfi_def_cfa_offset 16
    .cfi_offset 3, -16
    movl    $1, %edi
    subq    $80, %rsp
    .cfi_def_cfa_offset 96
    movq    %fs:40, %rax
    movq    %rax, 72(%rsp)
    xorl    %eax, %eax
    movq    std::_Function_handler<bool (int, int), f()::{lambda(int, int)#1}>::_M_invoke(std::_Any_data const&, int, int), 24(%rsp)
    movq    std::_Function_base::_Base_manager<f()::{lambda(int, int)#1}>::_M_manager(std::_Any_data&, std::_Function_base::_Base_manager<f()::{lambda(int, int)#1}> const&, std::_Manager_operation), 16(%rsp)
    call    operator new(unsigned long)
    movq    %rax, (%rsp)
    movq    16(%rsp), %rax
    movq    $0, 48(%rsp)
    testq   %rax, %rax
    je  .L14
    movq    24(%rsp), %rdx
    movq    %rax, 48(%rsp)
    movq    %rsp, %rsi
    leaq    32(%rsp), %rdi
    movq    %rdx, 56(%rsp)
    movl    $2, %edx
    call    *%rax
    cmpq    $0, 48(%rsp)
    je  .L14
    movl    $5, %edx
    movl    $10, %esi
    leaq    32(%rsp), %rdi
    call    *56(%rsp)
    testb   %al, %al
    movl    $.LC0, %edx
    jne .L49
    movl    $.LC2, %esi
    movl    $1, %edi
    xorl    %eax, %eax
    call    __printf_chk
    movq    48(%rsp), %rax
    testq   %rax, %rax
    je  .L23
    leaq    32(%rsp), %rsi
    movl    $3, %edx
    movq    %rsi, %rdi
    call    *%rax
    movq    16(%rsp), %rax
    testq   %rax, %rax
    je  .L12
    movl    $3, %edx
    movq    %rsp, %rsi
    movq    %rsp, %rdi
    call    *%rax
    movq    72(%rsp), %rax
    xorq    %fs:40, %rax
    jne .L50
    addq    $80, %rsp
    .cfi_def_cfa_offset 16
    popq    %rbx
    .cfi_def_cfa_offset 8
    .p2align 4,,10
    .p2align 3
    movl    $.LC1, %esi
    movl    $1, %edi
    xorl    %eax, %eax
    call    __printf_chk
    jmp .L24
    call    std::__throw_bad_function_call()
    movq    48(%rsp), %rcx
    movq    %rax, %rbx
    testq   %rcx, %rcx
    je  .L20
    leaq    32(%rsp), %rsi
    movl    $3, %edx
    movq    %rsi, %rdi
    call    *%rcx
    movq    16(%rsp), %rax
    testq   %rax, %rax
    je  .L29
    movl    $3, %edx
    movq    %rsp, %rsi
    movq    %rsp, %rdi
    call    *%rax
    movq    %rbx, %rdi
    call    _Unwind_Resume
    call    __stack_chk_fail
    movq    48(%rsp), %rcx
    movq    %rax, %rbx
    testq   %rcx, %rcx
    je  .L20
    leaq    32(%rsp), %rsi
    movl    $3, %edx
    movq    %rsi, %rdi
    call    *%rcx
    jmp .L20
    movq    %rax, %rbx
    jmp .L20
    movq    16(%rsp), %rcx
    movq    %rax, %rbx
    testq   %rcx, %rcx
    je  .L29
    movl    $3, %edx
    movq    %rsp, %rsi
    movq    %rsp, %rdi
    call    *%rcx
    jmp .L29

Which approach would you like to choose when it comes to performance?

Herb Sutter has said that the most object oriented way to write methods in C++ is using non-member non-friend functions. Should that mean that I should take private methods and turn them into non-member non-friend functions? Any member variables that these methods may need can be passed in as parameters.

Example (before):

class Number {
  Number( int nNumber ) : m_nNumber( nNumber ) {}
  int CalculateDifference( int nNumber ) { return minus( nNumber ); }
  int minus( int nNumber ) { return m_nNumber - nNumber; }
  int m_nNumber;

Example (after):

int minus( int nLhsNumber, int nRhsNumber ) { return nLhsNumber - nRhsNumber; }
class Number {
  Number( int nNumber ) : m_nNumber( nNumber ) {}
  int CalculateDifference( int nNumber ) { return minus( m_nNumber, nNumber ); }
  int m_nNumber;

Am I on the right track? Should all private methods be moved to non-member non-friend functions? What should be rules that would tell you otherwise?

Not all private methods should be moved to non-member non-friend function, but those that do not need access to your private data members should be. You should give access to as little function as you can, to encapsulate your classes as mush a possible.

I strongly recommend reading Effective C++ from Scott Meyers which explain why you should do this and when it is appropriate.

Edit : I would like to add that this is less true for private method then for public ones, although still valid. As encapsulation is proportionnal to the amount of code you would break by modifying your method, having a private member-function , even though it does not requires access to data members. That is because modifying that code would break little code and only code that you have control over.

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)

I wrote a Stack and Queue implementation (Linked List based). There is one stack (bigStack). For example, I separate bigStack (example: stackA and stackB). I pop() a node from bigStack, I push() in stackA. In the same way, I push() in stackB. I want bigStack to not change. Therefore I want to clone the bigStack object. How do I clone objects in C++? Or is there another solution to my problem?

class Stack : public List {
   Stack() {}
   Stack(const Stack& rhs) {}
   Stack& operator=(const Stack& rhs) {};
    ~Stack() {}

    int Top() {
        if (head == NULL) {
            cout << "Error: The stack is empty." << endl;
            return -1;
        } else {
            return head->nosu;

    void Push(int nosu, string adi, string soyadi, string bolumu) {
        InsertNode(0, nosu, adi, soyadi, bolumu);

    int Pop() {
        if (head == NULL) {
            cout << "Error: The stack is empty." << endl;
            return -1;
        } else {
            int val = head->nosu;
            return val;

    void DisplayStack(void);



Stack copyStack = veriYapilariDersi;

If your object is not polymorphic (and a stack implementation likely isn't), then as per other answers here, what you want is the copy constructor. Please note that there are differences between copy construction and assignment in C++; if you want both behaviors (and the default versions don't fit your needs), you'll have to implement both functions.

If your object is polymorphic, then slicing can be an issue and you might need to jump through some extra hoops to do proper copying. Sometimes people use as virtual method called clone() as a helper for polymorphic copying.

Finally, note that getting copying and assignment right, if you need to replace the default versions, is actually quite difficult. It is usually better to set up your objects (via RAII) in such a way that the default versions of copy/assign do what you want them to do. I highly recommend you look at Meyer's Effective C++, especially at items 10,11,12.

I'm implementing a CORBA like server. Each class has remotely callable methods and a dispatch method with two possible input, a string identifying the method or an integer which would be the index of the method in a table. A mapping of the string to the corresponding integer would be implemented by a map.

The caller would send the string on the first call and get back the integer with the response so that it simply has to send the integer on subsequent calls. It is just a small optimization. The integer may be assigned dynamically on demand by the server object. The server class may be derived from another class with overridden virtual methods.

What could be a simple and general way to define the method binding and the dispatch method ?

Edit: The methods have all the same signature (no overloading). The methods have no parameters and return a boolean. They may be static, virtual or not, overriding a base class method or not. The binding must correctly handle method overriding.

The string is class hierarchy bound. If we have A::foo() identified by the string "", and a class B inherits A and override the method A::foo(), it will still be identified as "", but the dispatcher will call A::foo if the server is an A object and B::foo if it is a B object.

Edit (6 apr): In other words, I need to implement my own virtual method table (vftable) with a dynamic dispatch method using a string key to identify the method to call. The vftable should be shared among objects of the same class and behave as expected for polymorphism (inherited method override).

Edit (28 apr): See my own answer below and the edit at the end.

You might like to rephrase the question slightly as static and dynamic binding actually have a specific meaning in C++.

For example, default values for parameters are determined at compile time so if I have a virtual method in a base class that declares default values for its parameters then those values are set at compile time.

Any new default values for these parameters that are declared in a derived class will be ignored at run time with the result being that the default parameter values in the base class will be used, even though you called the member function in the derived class.

The default parameter values are said to be statically bound.

Scott Meyers discusses this in an item in his excellent book "Effective C++".


It took me a long time to realize how important and subtle having variables that:

1) exist on the stack

2) have their destructors called when they fall out of scope


These two things allow things like:


B) refcounted GC

Interesting enough, (1) & (2) are not available in "lower" languages like C/Assembly; nor in "higher" languages like Ruby/Python/Java (since GC prevents predictable destruction of objects).

I'm curious -- what other techniques do you know of that are very C++ specific, due to language design choices.


Edit: If your answer is "this works in C++ & this other langauge", that's okay too. The things I want to learn about are similar to:

By choosing to not have certain features (like GC), we gain other features (like RAII + predicable destructing of objects). In what areas of C++, by choosing to NOT have features that other "higher level" langauges have, C++ manages to get patterns that those higher level langauges can't express.

There's the pImpl idiom. It work similar to the Bridge pattern.

And the Expression Template, which delays C++'s expression evaluations.

These two works also explore this question: More C++ Idioms and Effective C++ (Scott Meyers, 2005)

As we have so many design patterns in java, like wise do we have any in c++.Or can we use the same sort of patterns in c++.

Design patterns are language agnostic. Language specific patterns are called idioms - these are solutions to recurring problems in a certain language.

For C++ there are good books like Effective C++, that introduce you to the basic ones. The wikibook More C++ idioms is also worth a look.

I am a new to professional development. I mean I have only 5 months of professional development experience. Before that I have studied it by myself or at university. So I was looking over questions and found here a question about code quality. And I got a question related to it myself. How do I increase my code understanding/reading skills? Also will it improve the code quality I will write? Is there better code notation than Hungarian one? And is there any really good books for C++ design patterns(or the language doesn't matter?)? Thank you in advance answering these questions and helping me improving :)

P.S. - Also I have forgot to tell you that I am developing with C++ and C# languages.

How do I increase my code understanding/reading skills?

Read read read. Learn from your mistakes. Review answers on SO and elsewhere. When you can think back on a piece of code you wrote and go "aha! I should've done xyz instead!" then you're learning. Read a good book for your language of choice, get beyond the basics and understand more advanced concepts.

Then, apart from reading: write write write! Coding is like math: you won't fully grock it without actually solving problems. Glancing at a math problem's solution is different than getting out a blank piece of paper and solving it yourself.

If you can, do some pair programming too to see how others code and bounce ideas around.

Also will it improve the code quality I will write?

See above. As you progress you should get more efficient. It won't happen by reading a book on design patterns. It will happen by solving real world problems and understanding why what you read works.

Is there better code notation than Hungarian one?

It depends. Generally I avoid them and use descriptive names. The one exception where I might use Hungarian type of notations is for UI elements such as Windows Forms or ASP.NET controls, for example: using btn as a prefix for a Submit button (btnSubmit), txt for a TextBox (txtFirstName), and so on but it differs from project to project depending on approach and patterns utilized.

With regards to UI elements, some people like to keep things alphabetical and may append the control type at the end, so the previous examples become submitButton and firstNameTextBox, respectively. In Windows Forms many people name forms as frmMain, which is Hungarian, while others prefer naming it based on the application name or form purpose, such as MainForm, ReportForm, etc.

EDIT: be sure to check out the difference between Apps Hungarian and Systems Hungarian as mentioned by @Tobias Langner in a comment to an earlier response.

Pascal Case is generally used for method names, classes, and properties, where the first letter of each word is capitalized. For local variables Camel Case is typically used, where the first letter of the first word is lowercase and subsequent words have their first letters capitalized.

You can check out the naming conventions and more from the .NET Framework Design Guidelines. There is a book and some of it is on MSDN.

And is there any really good books for C++ design patterns(or the language doesn't matter?)?

Design patterns should be applicable to any language. Once you understand the concept and the reasoning behind that pattern's usefulness you should be able to apply it in your language of choice. Of course, don't approach everything with a "written in stone" attitude; the pattern is the goal, the implementation might differ slightly between languages depending on language features available to you. Take the Decorator pattern for example, and see how C# extension methods allow it to be implemented differently than without it.

Design Pattern books:

Head First Design Patterns - good beginner intro using Java but code is available for C++ and C# as a download (see "book code and downloads" section on the book's site)

Design Patterns: Elements of Reusable Object-Oriented Software - classic gang of four (GOF)

Patterns of Enterprise Application Architecture - Martin Fowler

If you're looking for best practices for quality coding in C++ and C# then look for the "Effective C++" and "More Effective C++" books (by Scott Meyers) and "Effective C#" and "More Effective C#" books (by Bill Wagner). They won't hold your hand along the way though, so you should have an understanding of the language in general. There are other books in the "Effective" series so make sure you see what's available for your languages.

I'm sure you can do a search here for other recommended reading so I'll stop here.

EDIT: added more details under the Hungarian Notation question.

I have a good understanding of OO from java and C# and I'm lucky in my engineering courses to have been exposed to the evils of both assembler and C (pointers are my playground :D ).

However, I've tried looking into C++ and the thing that gets me is the library code. There are so many nice examples of how to perform the bread and butter tasks in java and C#, but I've not been able to find a good explanation of how to do these things in C++.

I'd love to expand my knowledge into C++ to add to my skillset but I've not had a chance to be exposed to people and communities that are keen on these things.

Could anyone here recommend some good open source projects or tutorials which are useful. Bonus marks if they involve coming from java or C# into this environment.

Assuming you already have some knowledge of the C++ syntax, and have good Object Oriented experience I'd go for Effective c++ series.

It's a collection of "tips and tricks" explaining how c++ works under the hood. Which are the common misunderstandings from people coming from other languages and why c++ works this way.

I read that destructors need to be defined when we have pointer members and when we define a base class, but I am not sure if I completely understand. One of the things I am not sure about is whether or not defining a default constructor is useless or not, since we are always given a default constructor by default. Also, I am not sure if we need to define default constructor to implement the RAII principle (do we just need to put resource allocation in a constructor and not define any destructor?).

class A

        delete [] brandname;
        delete b;

        //do we need to define it?


    something(){} =0; //virtual function (reason #1: base class)

    char *brandname; //c-style string, which is a pointer member (reason #2: has a pointer member)
    B* b; //instance of class B, which is a pointer member (reason #2)
    vector<B*> vec; //what about this?


class B: public A
    public something()
    cout << "nothing" << endl;

    //in all other cases we don't need to define the destructor, nor declare it?

As @nonsensickle points out, the questions is too broad... so I'm gonna try to tackle it with everything I know...

The first reason to re define the destructor would be in The Rule of Three which is on part the item 6 in Scott Meyers Effective C++ but not entirely. The rule of three says that if you re defined the destructor, copy constructor, or copy assignment operations then that means you should rewrite all three of them. The reason is that if you had to rewrite your own version for one, then the compiler defaults will no longer be valid for the rest.

Another example would be the one pointed out by Scott Meyers in Effective C++

When you try to delete a derived class object through a base class pointer and the base class has a non virtual destructor, the results are undefined.

And then he continues

If a class does not contain any virtual functions, that is often an indication that it is not meant to be used as a base class. When a class is not intended to be used as a base class, making the destructor virtual is usually a bad idea.

His conclusion on destructors for virtual is

The bottom line is that gratuitously declaring all destructors virtual is just as wrong as never declaring them virtual. In fact, many people summarize the situation this way: declare a virtual destructor in a class if and only if that class contains at least one virtual function.

And if it is not a Rule Of three case, then maybe you have a pointer member inside your object, and maybe you allocated memory to it inside your object, then, you need to manage that memory in the destructor, this is item 6 on his book

Be sure to check out @Jefffrey's answer on the Rule of Zero

what is the most advanced c or c++ book you ever read? i am asking this because i already read lots and lots of books on c and c++ on a lot of topics including (object oriented programming-data structures and algorithms-network programming-parallel programming (MPI-PThreads-OpenMP-Cilk-Cuda)-boost library....). So whats next. I still want to advance.. especially in c.

Hey nobody mentioned about Bruce Eckel's Thinking in C++ Volume 1 And Volume 2. When I read it as the first book it went straight way above my head. However as now I have good experience and have read books like Effective/Exceptional C++ so Eckel's book is now an ordinary stuff. However no doubt its a very popular book (4.5 stars on Amazon - 84 customer reviews).

Large Scale C++ Design by John Lakos.

Practical advice on managing the complexity of compiling/linking and executing large C++ programs. Talks a lot about decoupling and how to avoid the many kinds of dependencies that arise in C++.

(This is something most C#/Java developers, and sadly some C++-devs too, rarely understand. IMO, it's a pain they need to. I wish we had modules in C++ already.)

My favourite "difficult" C++ book is this Template Metaprogramming one: C++ Template Metaprogramming: Concepts, Tools, and Techniques from Boost and Beyond.

You really want to test your mental limits? Then try these:

Alexandrescu: Modern C++ Design

Abrahams&Gurtovoy: C++ Template Metaprogramming

These books look deceiptively thin, but they stretch the limits of template programming, your C++ compiler, and your brain.

It seems to me there aren't half as many books about C programming as there are about C++. The language just isn't that complex.

One interesting read might be P. J. Plauger The Standard C Library. It is supposed to contain some masterful code. It's on my to-read list.

I am not sure if you would consider these advanced, but I would surely put them in the category of must have references:

The C++ Programming Language Special Edition (3rd) by Bjarne Stroustrup

The C++ Standard Library: A Tutorial and Reference by Nicolai M. Josuttis

The other books I would recommend have already been listed by others.

A developer in a team I'm supervising prefers declaring variables as constants in his tests, e.g. const int someValue = 1; (rather than just int someValue = 1;).

When I saw this I found it a bit odd and questioned what he'd done. His argument is that this is sensible for the purposes of this test - because the value he's assigned never changes.

I've always thought of constants as something that should be declared at a class level. However I do see this developer's point of view.

What's your opinion? And, tests aside, would you declare constants in normal methods? If 'yes', why?

From Effective C++ by Scott Meyers (chapter 3):

Use const whenever possible.

The wonderful thing about const is that it allows you to specify a semantic constraint - a particular object should not be modified - and compilers will enforce that constraint. It allows you to communicate to both compilers and other programmers that a value should remain invariant. Whenever that is true, you should be sure to say so, because that way you enlist your compilers' aid in making sure the constraint isn't violated.

How would you call the constructor of the following class in these three situations: Global objects, arrays of objects, and objects contained in another class/struct?

The class with the constructor (used in all three examples):

class Foo {
        Foo(int a) { b = a; }

        int b;

And here are my attempts at calling this constructor:

Global objects

Foo global_foo(3); // works, but I can't control when the constructor is called.

int main() {
    // ...

Arrays of objects

int main() {
    // Array on stack
    Foo array_of_foos[30](3); // doesn't work

    // Array on heap
    Foo *pointer_to_another_array = new Foo(3) [30]; // doesn't work

There I'm attempting to call the constructor for all elements of the arrays, but I'd also like to know how to call it on individual elements.

Objects contained in classes/structs

class Bar {
    Foo foo(3); // doesn't work

int main() {
    Bar bar;

The Konrad reply is OK, just a puntualization about the arrays.... There is a way to create an array of items(not pointers) and here it follows:

//allocate raw memory for our array
void *rawMemory = operator new[](30 * sizeof(Foo))

// point array_of_foos to this memory so we can use it as an array of Foo
Foo *array_of_foos = static_cast<Foo *>(rawMemory);

// and now we can create the array of objects(NOT pointers to the objects)
//  using the buffered new operator
for (int i = 0; i < 30; i++)

This approach is described here:

What is the difference between the index overloaded operator and the insert method call for std::map?


some_map["x"] = 500;


some_map.insert(pair<std::string, int>("x", 500));

In addition to the fact that map::operator[] will replace an existing value is that operator[] map::will create and add to the map a default existing value to replace before the replacement occurs (the map::operator[]() call has to return a reference to something). For items that are expensive to create this could be a performance issue.

See "Item 24: Choose carefully between map::operator[] and map::insert when efficiency is important" in Scott Meyers' Effective STL.

In an attempt to write a wrapper type for another type T, I encountered a rather obnoxious problem: I would like to define some binary operators (such as +) that forward any operation on wrapper to the underlying type, but I need these operators accept any of the potential combinations that involve wrapper:

wrapper() + wrapper()
wrapper() + T()
T()       + wrapper()

The naive approach involves writing all the potential overloads directly.

But I don't like writing duplicated code and wanted a bit more challenge, so I chose to implement it using a very generic template and restrict the potential types with an enable_if.

My attempt is shown at the bottom of the question (sorry, this is as minimal as I can think of). The problem is that it will run into an infinite recursion error:

  1. To evaluate test() + test(), the compile looks at all potential overloads.
  2. The operator defined here is in fact a potential overload, so it tries to construct the return type.
  3. The return type has an enable_if clause, which is supposed to prevent it from being a valid overload, but the compiler just ignores that and tries to compute the decltype first, which requires ...
  4. ... an instantiation of operator+(test, test).

And we're back where we started. GCC is nice enough to spit an error; Clang just segfaults.

What would be a good, clean solution for this? (Keep in mind that there are also other operators that need to follow the same pattern.)

template<class T>
struct wrapper { T t; };

// Checks if the type is instantiated from the wrapper
template<class>   struct is_wrapper              : false_type {};
template<class T> struct is_wrapper<wrapper<T> > : true_type  {};

// Returns the underlying object
template<class T> const T& base(const T& t)          { return   t; }
template<class T> const T& base(const wrapper<T>& w) { return w.t; }

// Operator
template<class W, class X>
typename enable_if<
    is_wrapper<W>::value || is_wrapper<X>::value,
    decltype(base(declval<W>()) + base(declval<X>()))
>::type operator+(const W& i, const X& j);

// Test case
struct test {};
int main() {
    test() + test();
    return 0;

Here's rather clunky solution that I would rather not use unless I have to:

// Force the evaluation to occur as a 2-step process
template<class W, class X, class = void>
struct plus_ret;
template<class W, class X>
struct plus_ret<W, X, typename enable_if<
    is_wrapper<W>::value || is_wrapper<X>::value>::type> {
    typedef decltype(base(declval<W>()) + base(declval<X>())) type;

// Operator
template<class W, class X>
typename plus_ret<W, X>::type operator+(const W& i, const X& j);

The most straightforward way to write mixed-mode arithmetic is to follow Scott Meyers's Item 24 in Effective C++

template<class T>
class wrapper1 
    wrapper1(T const& t): t_(t) {} // yes, no explicit here

    friend wrapper1 operator+(wrapper1 const& lhs, wrapper1 const& rhs)
        return wrapper1{ lhs.t_ + rhs.t_ };        

    std::ostream& print(std::ostream& os) const
        return os << t_;

    T t_; 

template<class T>
std::ostream& operator<<(std::ostream& os, wrapper1<T> const& rhs)
    return rhs.print(os);

Note that you would still need to write operator+= in order to provide a consistent interface ("do as the ints do"). If you also want to avoid that boilerplate, take a look at Boost.Operators

template<class T>
class wrapper2
    boost::addable< wrapper2<T> >
    wrapper2(T const& t): t_(t) {}

    // operator+ provided by boost::addable
    wrapper2& operator+=(wrapper2 const& rhs)
        t_ += rhs.t_;
        return *this;

    std::ostream& print(std::ostream& os) const
        return os << t_;

    T t_; 

template<class T>
std::ostream& operator<<(std::ostream& os, wrapper2<T> const& rhs)
    return rhs.print(os);

In either case, you can then write

int main()
    wrapper1<int> v{1};
    wrapper1<int> w{2};

    std::cout << (v + w) << "\n";
    std::cout << (1 + w) << "\n";
    std::cout << (v + 2) << "\n";

    wrapper2<int> x{1};
    wrapper2<int> y{2};

    std::cout << (x + y) << "\n";
    std::cout << (1 + y) << "\n";
    std::cout << (x + 2) << "\n";


which will print 3 in all cases. Live example. The Boost approach is very general, e.g. you can derive from boost::arithmetic to also provide operator* from your definition of operator*=.

NOTE: this code relies on implicit conversions of T to wrapper<T>. But to quote Scott Meyers:

Classes supporting implicit type conversions are generally a bad idea. Of course, there are exceptions to this rule, and one of the most common is when creating numerical types.

What is good book for industry level C++ programming? I am not looking for a beginners C++ book that talks about datatypes and control structures. I am looking for a more advanced book. For example, how to build system applications using C++. Any kind of guidance will be very helpful.

If you're looking for books on refining your craft in C++ as a language, you don't get much better than Scott Meyers' Effective C++ and More Effective C++ and Herb Sutter's Exceptional C++, More Exceptional C++ and Exceptional C++ Style. All are packed with invaluable information on bringing your facility with the language from the intermediate to the advanced level.

System-level programming is specific to operating system, so the books diverge based on your platform. Ones I've found very helpful (albeit not C++ specific) are: Windows System Programming, by Johnson M. Hart, Advanced Windows Debugging, by Mario Hewardt and Daniel Pravat, and Linux System Programming, by Robert Love.

All of these books (as well as Peter Alexander's excellent suggestion of Modern C++ Design) are available on O'Reilly's Safari service, which is a pretty cost-effective way of doing a lot of technical reading on the cheap and well worth checking out if you're considering going on a studying binge.

Lakos' Large Scale C++ Software Design is quite a good intermediate-advanced level book about C++ software architecture. It's a little out of date - predating widespread use of templates for example - but it is quite a good book on the subject.

Lakos worked for Mentor Graphics in the 1980s when first generation workstations were the technology du jour. This was an era when the difference in performance and memory footprint between C and C++ apps was regarded as significant. This 'old school' approach discusses efficient C++ systems architecture in some depth, which is a bit of a unique selling point for this book.

These are the best two books I have seen and read

Advanced C++ Programing Styles and Idioms

C++ Common Knowledge

Modern C++ Design by Andrei Alexandrescu is probably the most advanced C++ book out there. It's more about very advanced design patterns rather than building software.

I am trying to learn C++ via some web tutorials. I don't have a compiler available to me, otherwise I would try this out. I'm not sure what is meant by a const pointer. Does that just mean it always points to the same memory address? Why would you ever want to do that? Would the following code be legal?

int * const aPointer = new int;
... //do something with aPointer
delete aPointer;
... //do something else, including possibly more 'new' statements
aPointer = new int;


To remember this easily you can use the trick that Scott Meyers describes in his excellent book "Effective C++" (sanitised Amazon link)

You draw a line through the declaration where the asterisk is located.

  • If the keyword const appears to the left of the line, then you can't change the value of the item that you're pointing to.
  • If the keyword const appears to the right of the line, then you can't change the pointer to point to another location.
  • If const appears on both sides, then you can't change the pointer and you can't change the value of what you're pointing to.

BTW That book is excellent, and while not for a beginner, is definitely a way of taking your C++ knowledge to the next level! Highly recommended.



I am very interested in c++ and want to master this language. I have read a lot of books about c++. I want to read some library source code to improve my skill, but when I read the boost library source code, I find it is very difficulty.
Can anyone give me some advice about how to read boost source code and before I can understand it what kind of books about c++ should I read?

If you're starting out in C++, the boost source code is probably not the best place. It's where the wizards hang out and they deal in template magic. I think a better starting point are Scott Myers and Herb Sutters books (in that order).

Some versions of Scott's book can be a bit out dated but they are still strong in the fundamentals. Herb's books are worth reading many many times and are an invaluable tool. Once you've gotten through both of those authors, then would be a good time to tackle the boost source code.

I have this snippet of code here. The intention is to make a copy of initialData. Since I am not modifying initialData in any way, I figure that I should pass it as a const reference. However, I keep getting this message when compiling.

.\src\Scene\SceneAnimationData.cpp(23) : error C2662: 'SceneTrackerData::getRect' : cannot convert 'this' pointer from 'const SceneTrackerData' to 'SceneTrackerData &'

#include "SceneTrackerData.h"

void SceneAnimationData::SetupData(const SceneTrackerData &initialData)
    // getRect(), points() and links() all return const pointers

void SceneAnimationData::CloneRect(const QGraphicsRectItem * initialRect) 
    if (initialRect != NULL)
        QPointF position = initialRect->scenePos();
        QRectF rect = initialRect->rect();

        initialRect = new QGraphicsRectItem(rect);

void SceneAnimationData::CloneLinks(const QList<QGraphicsLineItem*> links) 
    links_ = new QList<QGraphicsLineItem*>(*links);

void SceneAnimationData::ClonePoints(const QList<QGraphicsEllipseItem*> points) 
    points_ = new QList<QGraphicsEllipseItem*>(*points);

I'm not sure as I am no expert C++ programmer, but are your functions getRect() and so on declared const? If not but you know the way you use them is const, you can still use a const_cast to remove the const from your initialData reference.

See for example here:

Or Scott Meyers excellent C++-Books Effective C++ and More Effective C++. At least one of them has an item about constness.

I port a middle-sized application from C to C++. It doesn't deal anywhere with exceptions, and that shouldn't change.

My (wrong!) understanding of C++ was (until I learned it the hard way yesterday) that the (default) new operator returns a NULL pointer in case of an allocation problem. However, that was only true until 1993 (or so). Nowadays, it throws a std::bad_alloc exception.

Is it possible to return to the old behavior without rewriting everything to using std::nothrow on every single call?

Sorry, but as for my opinion you should NOT do this and return to old new behavior. This is because you simply can't avoid exceptions anyway.


Consider about new call which should allocate class with constructor calling some initialization code which needs to construct anything temporary which is dynamic. Alas, you are going to have exception. No matter if you use std::nothrow. This is only one scenario among number of them.

In Scott Meyers book Effective C++ it was discussed in details as far as I remember. But I'm not sure if all the cases are reviewed (but I suggest enough of them).

I saw what looks like an inconsistency in the std::lower_bound() and std::upper_bound() syntaxes (well, type-conversion, really) and was wondering if anyone could elucidate please? Per the comments, line 2 will not compile despite its obvious similarity to line 1; you need to use the form shown on line 3 (on gcc 4.7.3 / ubuntu 64-bit at least - that's all I've got to play with)

#include <set>
#include <algorithm>

using namespace std;

class MyInt {
    int val;
    MyInt(int _val): val(_val) {}
    bool operator<(const MyInt& other) const {return val < other.val;}

int main() {
    set<MyInt> s;
    s.insert(1);  // demonstrate implicit conversion works
    s.insert(3); // one last one for the road
    set<MyInt>::iterator itL = lower_bound(s.begin(), s.end(), 2); //LINE 1
    // the line below will NOT compile
    set<MyInt>::iterator itU = upper_bound(s.begin(), s.end(), 2); //LINE 2
    // the line below WILL compile
    set<MyInt>::iterator itU2 = upper_bound(s.begin(), s.end(), MyInt(2)); // LINE 3
    return 0;

I don't think it's a bug. If you look at the (possible) implementation of std::upper_bound, the comparison is done like

if (!(value < *it)) { ... } // upper_bound, implicit conversion `MyInt`->`int` doesn't work

And because operator< is a member function of MyInt (and not of int, which is not a class type), the code doesn't compile, since there is no conversion from MyInt to int. On the other hand, in std::lower_bound, *it appears on the lhs of the comparison, and value (of type int) can be implicitly converted to MyInt when passed to MyInt::operator<.

if (*it < value) { ... } // lower_bound, implicit conversion `int`->`MyInt` works

This is the reason why it's better to implement comparison operators as non-members, so you don't have this asymmetry. This is also mentioned in Scott Meyers' Effective C++ book: Item 24: Declare non-member functions when type conversions should apply to all parameters.

Quick and dirty fix: define an MyInt::operator int(){return val;} for implicit conversion MyInt to int. (EDIT: doesn't really work, ambiguity). What works is removing the need for implicit conversion

set<MyInt>::iterator itU = upper_bound(s.begin(), s.end(), MyInt(2));


I spent over 2 hours finding this memory leak:

class Parent{

class Child:public Parent{
  std::string str;

int main(){
  Parent *ptr=new Child();
  delete ptr;

I fixed it by moving the string into the parent class. Why did this memory leak happen? Shouldn't the child's members be deleted as well?

This can happen because Parent may not have a virtual destructor. Since you are creating a Parent* (the base class) to a dynamically allocated derived class Child, deleting the Parent* which has no virtual destructor will cause undefined behaviour, but typically will result in the derived class not being destroyed.

From Scott Myers - Effective C++ Third Edition:

... if we delete Base class pointer with a non-virtual destructor, results are undefined. What typically happens at runtime is that the derived part of the object is never destroyed. This is an excellent way to leak resources, corrupt data structures, and spend a lot of time with a debugger. So any class with virtual functions should almost certainly have a virtual destructor.

class Parent{

class Child:public Parent{
    Child() : str("Child") {}
    ~Child() { std::cout << str << std::endl;};
    std::string str;

int main(){
    Parent *ptr=new Child();
    delete ptr; // undefined behaviour: deleting a Base* to a Derived object where the Base has no virtual destructor

You can fix this by making Parent's destructor virtual:

class Parent{
    virtual ~Parent() {} // Will call derived classes destructors now as well

class Child:public Parent{
    Child() : str("Child") {}
    ~Child() { std::cout << str << std::endl;};
    std::string str;

int main(){
    Parent *ptr=new Child();
    delete ptr;
    // Child::~Child() has now been called.

See When to use virtual destructors? which probably explains it better than I did

Edit: Thank you to the @aschepler (in the question's comments), commenters below, and the answer to the linked question, I have updated the answer to better reflect that this is undefined behaviour. In my haste I didn't mention it, and only mentioned the typical behaviour

Is there any website where people share and discuss good examples of object-oriented design?

Ideally such website should be populated with posts of the following structure:

  • Concise description of the problem, including definitions, links, etc.
  • Several attempts of OO design, diagrams, pseudocode listings (voted up/down by users)
    • Comments (also voted by users)

Currently I'm looking for a source of inspiration.

Object Oriented Software Construction - Betrand Mayer

He's the man that originated the Eiffel language, the most complete analysis of OO software construction I've read.

Well I can't point you to web sites, but I can refer you to some great books :

Of course, those are C++ books, but a lot of concepts in them applies to much more than just C++

Our project uses a macro to make logging easy and simple in one-line statements, like so:

DEBUG_LOG(TRACE_LOG_LEVEL, "The X value = " << x << ", pointer = " << *x);

The macro translates the 2nd parameter into stringstream arguments, and sends it off to a regular C++ logger. This works great in practice, as it makes multi-parameter logging statements very concise. However, Scott Meyers has said, in Effective C++ 3rd Edition, "You can get all the efficiency of a macro plus all the predictable behavior and type safety of a regular function by using a template for an inline function" (Item 2). I know there are many issues with macro usage in C++ related to predictable behavior, so I'm trying to eliminate as many macros as possible in our code base.

My logging macro is defined similar to:

#define DEBUG_LOG(aLogLevel, aWhat) {  \
if (isEnabled(aLogLevel)) {            \
  std::stringstream outStr;            \
  outStr<< __FILE__ << "(" << __LINE__ << ") [" << getpid() << "] : " << aWhat;    \
  logger::log(aLogLevel, outStr.str());    \

I've tried several times to rewrite this into something that doesn't use macros, including:

inline void DEBUG_LOG(LogLevel aLogLevel, const std::stringstream& aWhat) {


template<typename WhatT> inline void DEBUG_LOG(LogLevel aLogLevel, WhatT aWhat) {
    ...  }

To no avail (neither of the above 2 rewrites will compile against our logging code in the 1st example). Any other ideas? Can this be done? Or is it best to just leave it as a macro?

Logging remains one of the few places were you can't completely do away with macros, as you need call-site information (__LINE__, __FILE__, ...) that isn't available otherwise. See also this question.

You can, however, move the logging logic into a seperate function (or object) and provide just the call-site information through a macro. You don't even need a template function for this.

#define DEBUG_LOG(Level, What) \
  isEnabled(Level) && scoped_logger(Level, __FILE__, __LINE__).stream() << What

With this, the usage remains the same, which might be a good idea so you don't have to change a load of code. With the &&, you get the same short-curcuit behaviour as you do with your if clause.

Now, the scoped_logger will be a RAII object that will actually log what it gets when it's destroyed, aka in the destructor.

struct scoped_logger
  scoped_logger(LogLevel level, char const* file, unsigned line)
    : _level(level)
  { _ss << file << "(" << line << ") [" << getpid() << "] : "; }

  std::stringstream& stream(){ return _ss; }
  ~scoped_logger(){ logger::log(_level, _ss.str()); }
  std::stringstream _ss;
  LogLevel _level;

Exposing the underlying std::stringstream object saves us the trouble of having to write our own operator<< overloads (which would be silly). The need to actually expose it through a function is important; if the scoped_logger object is a temporary (an rvalue), so is the std::stringstream member and only member overloads of operator<< will be found if we don't somehow transform it to an lvalue (reference). You can read more about this problem here (note that this problem has been fixed in C++11 with rvalue stream inserters). This "transformation" is done by calling a member function that simply returns a normal reference to the stream.

Small live example on Ideone.

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

I am trying to implement factory pattern by registering the function pointers of the derived class to the factory in a static map(member of the factory)and creating objects by looking up the map. But I am getting a segmentation fault in doing this.

Code Snippet:


typedef Shape* (*Funcptr)();

std::map<int,Funcptr> Factory::funcmap;

int Factory::registerCreator(int ShapeID, Shape *(*CFuncptr)()) {
    Factory::funcmap[ShapeID] = CFuncptr;
return 1;

Shape* Factory::CreateObject(int ShapeID) {
    std::map<int,Funcptr>::iterator iter;
    iter = funcmap.find(ShapeID);
    if(iter != funcmap.end()){
        return iter->second();
    return NULL;


class Factory {
    virtual ~Factory();
    static int registerCreator(int, Shape *(*CFuncptr)());
    Shape* CreateObject(int);
    static  std::map<int,Funcptr> funcmap;


static Shape *SquareCreator() { 
    return new Square; 
static int SquareAutoRegHook = Factory::registerCreator(1,SquareCreator);

On creating the object for Factory in the main file a segmentation fault occurs. Can you please suggest if I am doing something wrong. I am using CppUTest for TDD and not sure how to debug this.

There is no guarantee about the order of creation of static objects that are defined in different translations uints* so you have a 50/50 shot as to which would happen first, the initializtion of Factory::funcmap or Factory::registerCreator(1,SquareCreator) and Undefined Behavior Russian Roulette is not a good game to play.

A common approach to deal with this, and one that described in Item 4 of the third edition of Scott Meyer's Effective C++ is to use local static objects instead of global static objects. In this case it means changing Factory to look like this:

class Factory { 
    virtual ~Factory(); 
    static int registerCreator(int, Shape *(*CFuncptr)()); 
    Shape* CreateObject(int); 
    static std::map<int,Funcptr> & GetFactoryMap() {
        static std::map<int,Funcptr> funcmap;
        return funcmap;

and changing Factory::registerCreator to this:

int Factory::registerCreator(int ShapeID, Shape *(*CFuncptr)()) {   
    GetFactoryMap()[ShapeID] = CFuncptr;   
    return 1;   

This way funcmap will be initialized the first time registerCreator is called and will never be used uninitialized.

*Or, roughly speaking, different .cpp files if you are not familar with the term translation unit

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

#include <map>

class A : public std::multimap<int, bool>
    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.

Possible Duplicate:
The Definitive C++ Book Guide and List

I was developing for quite long time already on C/C++ (mostly C, which makes style poorer). So, I know how to use it. However, quite often I stuck with style decisions like: - should I return error code here, throw exceptions, return error through a parameter - should I have all this stuff in constructor or should I create separate init function for that. and so on.

Any solutions WILL work. However, each of them has cons and pros, which I know and most importantly which I don't know.

It would be very nice to read something regarding overall C++ development style, coding practices and so forth. What do you recommend?

I've been recommended this by many people and I have a copy. Effective C++: 55 Specific Ways to Improve Your Programs and Designs (3rd Edition)

I am a student, and new to c++. I am searching for a standard c++ api that is as comprehensive as the java api. I have been using, and Please any help would be greatly appreciated.

C++ has a standard library.

You can try The C++ Standard Library: Tutorial and Reference. While I don't own it myself, it's on our book list (which I recommend you check out), so it shouldn't be bad.

Note C++ isn't Java, so the libraries don't necessarily have the same functionality. Another resource you'll want to look at is Boost, which serves as a source for well-written C++ libraries for things the standard library lacks.

If you mean the c++ standard library I'd look at It covers the current standards. After familiarizing yourself with that, you could try looking at boost.
There are a number of changes in the upcoming c++0x standard. Wikipedia has info on a number of these as does SO.

The number one book, IMO, for c++ is Effective C++ by Scott Meyers.

I am trying to develop abstract design pattern code for one of my project as below.. But, I am not able to compile the code some compile errors(like "unresolved external symbol "public: virtual void __thiscall Xsecs::draw_lines(double,double)" (?draw_lines@Xsecs@@UAEXNN@Z)" ).. Can any one please help me out in this...

#include "stdafx.h"
#include <iostream>
#include <vector>
#include "Xsecs.h"
using namespace std;
//Product class

class Xsecs
    virtual void draw_lines(double pt1, double pt2);
    virtual void draw_curves(double pt1, double rad);

class polyline: public Xsecs
    virtual void draw_lines(double pt1,double pt2)
        cout<<"draw_line in polygon"<<endl;
     virtual void draw_curves(double pt1, double rad)
        cout<<"Draw_curve in circle"<<endl;
    /*void create_polygons()

class circle: public Xsecs
     virtual void draw_lines(double pt1,double pt2)
        cout<<"draw_line in polygon"<<endl;
     virtual void draw_curves(double pt1, double rad)
        cout<<"Draw_curve in circle"<<endl;
    /*void create_circles()
        cout<<"Create circle"<<endl;

//Factory class
class Factory
 virtual polyline* create_polyline()=0;
 virtual circle* create_circle()=0;

class Factory1: public Factory
      polyline* create_polyline()
    return new polyline();
      circle* create_circle()
    return new circle();

class Factory2: public Factory
      circle* create_circle()
    return new circle();
     polyline* create_polyline()
    return new polyline();

int _tmain(int argc, _TCHAR* argv[])
    Factory1 f1;
    Factory * fp=&f1;
    return 0;

You should inherit publicly from A, like

class ProductA1 : public ProductA {

Without the public keyword, this relationship is private inheritance, which is not an is-a relationship, therefore you can't simply cast from ProductA1 to ProductA.

Scott Meyers explains this in Effective C++, Third Ed., Item 39:

[...] compilers, when given a hierarchy in which a class Student publicly inherits from a class Person, implicitly convert Students to Persons when that is necessary for a function call to succeed.

[...] the first rule governing private inheritance you've just seen in action: in contrast to public inheritance, compilers will generally not convert a derived class object (such as Student) into a base class object (such as Person) if the inheritance relationship between the classes is private. [...] The second rule is that members inherited from a private base class become private members of the derived class, even if they were protected or public in the base class.

Private inheritance means is-implemented-in-terms-of. If you make a class D privately inherit from a class B, you do so because you are interested in taking advantage of some of the features available in class B, not because there is any conceptual relationship between objects of types B and D. As such, private inheritance is purely an implementation technique.

Update for the 2nd version of the post: if you want pure virtual functions, you should declare them so:

virtual void draw_lines(double pt1, double pt2) = 0;
virtual void draw_curves(double pt1, double rad) = 0;

Otherwise the linker will miss their definition.

I'm wondering if you can overload an operator and use it without changing the object's original values.

Edited code example:

class Rational{
   Rational(double n, double d):numerator_(n), denominator_(d){};
   Rational(){}; // default constructor
   double numerator() const { return numerator_; } // accessor
   double denominator() const { return denominator_; } // accessor
    double numerator_;
    double denominator_;

const Rational operator+(const Rational& a, const Rational& b)
      Rational tmp;
      tmp.denominator_ = (a.denominator() * b.denominator());
      tmp.numerator_ = (a.numerator() * b.denominator());
      tmp.numerator_ += (b.numerator() * a.denominator());
      return tmp;

I made the accessors const methods, but I'm still getting a privacy error for every tmp.denominator_ / numerator_.

Since your class already provides accessors to the numerator and denominator, and it has a public constructor, there is no need to use any friends. You can overload operator+ as follows:

const Rational operator+(const Rational& rhs, const Rational& lhs)
    double newNumerator = rhs.numerator() * lhs.denominator() +
                          rhs.denominator() * lhs.numerator();
    return Rational(newNumerator, rhs.denominator() * lhs.denominator());

In response to some of the other answers:

Everything about this question is exactly answered by Item 24 of Effective C++ (Third Edition). In this item, Scott Meyers shows that, in cases dealing with numerical types where you want to support implicit conversion in an intuitive manner, it is best to use a non-member non-friend function.

Say your Rational class had the following constructor:

Rational::Rational(double numerator = 0, double denominator = 1);

In this case, if operator+ were a member function, trying to do mixed mode arithmetic would work only half the time:

Rational oneHalf(1, 2);
oneHalf + 2;   // works
2 + oneHalf;   // error!

In the second example, operator+ for integers is called. The way to fix this is to make operator+ for Rationals a non-member function as shown above.

If you have access to Effective C++, you should also check out Item 23: Prefer non-member non-friend functions to member functions.

I'm writing this question with reference to this one which I wrote yesterday. After a little documentation, it seems clear to me that what I wanted to do (and what I believed to be possible) is nearly impossible if not impossible at all. There are several ways to implement it, and since I'm not an experienced programmer, I ask you which choice would you take. I explain again my problem, but now I have some solutions to explore.

What I need

I have a Matrix class, and I want to implement multiplication between matrices so that the class usage is very intuitive:

Matrix a(5,2);
a(4,1) = 6 ;
a(3,1) = 9.4 ;           
...                   // And so on ...

Matrix b(2,9);
b(0,2) = 3;
...                   // And so on ...

// After a while
Matrix i = a * b;

What I had yesterday

At the moment I overloaded the two operators operator* and operator= and until yesterday night the were defined in this way:

Matrix& operator*(Matrix& m);
Matrix& operator=(Matrix& m);

The operator* instantiates a new Matrix object (Matrix return = new Matrix(...)) on the heap, set the values and then just:

return *result;

What I have today

After the discussion I decided to implement it in a "different way" to avoid the user to be bothered bother by pointers of any type and to keep the usage unchanged. The "different way" is to pass the returning value of operator* by value:

Matrix operator*(Matrix& m);
Matrix& operator=(Matrix& m);

The operator* instantiates return on the stack, set the values and then return the object.

There is a problem with this approach: it doesn't work. The operator= expects a Matrix& and operator* returns a Matrix. Moreover this approach doesn't look so good to me for another reason: I'm dealing with matrices, that can be very large and the aims of this library were to be 1) good enough for my project 2) fast, so probably passing by value should not be an option.

Which solutions I have explored

Well, following the suggestions in the previous discussion I read some stuff about smart pointers, they look great but I can't still figure out how to solve my problem with them. They deal with memory freeing and pointer copying, but I'm basicly using references, so they don't look the right choice for me. But I may be wrong.

Maybe the only solution is to pass by value, maybe I can't get both efficiency and a good interface. But again, you're the expert, and I would like to know your opinion.

You should really read Effective C++ by Scott Meyers, it has great topics on that. As already said, the best signatures for operator= and operator* are

Matrix& operator=(Matrix const& m);
Matrix operator*(Matrix const& m) const;

but I have to say you should implement multiplication code in

Matrix& operator*=(Matrix const& m);

and just reuse it in operator*

Matrix operator*(Matrix const &m) const {
    return Matrix(*this) *= m;

that way user could multiply without creating new matrices when she wants to. Of course for this code to work you also should have copy constructor :)

I saw Scott Meyers' "Effective C++" third edition book having a small section on "Template Programming".

Any other book/links containing information on "effective" usage of templates ?

Scott Meyers deals with the Standard Template Library in Effective STL. That may be relevant for you.

I like Modern C++ Design: Generic Programming and Design Patterns Applied. I found it very well written and clear. Contains a few advanced topics.

alt text

A rarely mentioned but solid book is C++ Common Knowledge by Stephen C. Dewhurst. "Among the first users of C++ at Bell Labs", Dewhurst gives the book a somewhat deceptive title because he actually covers quite a bit of advanced material in particular in regards to templates.

Dewhurst's book is organized similarly to Meyers's with 63 "Items" that you can usefully read on their own. On templates you should look over items 45-59 (about 70 pages of reading).

alt text

right now i am learning C++, and now I know the basic concept of template, which act just like a generic type, and i found almost every c++ program used template, So i really want to know when are we supposed to use template ? Can someone conclude your experience for me about c++ template ? When will you consider to use template ?

Supplement: if we defined such function

template <class myType>
myType GetMax (myType a, myType b) {
 return (a>b?a:b);

but we want to pass a object(self-defined class) for comparison, how can we implement ?

Supplement2: in the answer below, someone have wrote this sample code

template <class myType>
const myType& GetMax (const myType& a, const myType& b) {
    return (a<b?b:a);

template <class myType, class Compare>
const myType& GetMax (const myType& a, const myType& b, Compare compare) {
    return (compare(a,b)?b:a);

is this correct ? can we just pass a function name as a parameter of class myType ?


Simple answer is when you want the behaviour to remain the same independent of the type being used to instantiate the class.

So a stack of ints will behave in the same way as a stack of floats will behave as a stack of MyClass objects.

Inheritance and base classes are used when you want to allow specialisation of the behaviour.

So say you have a base class called Animal and it has a member function called makeSound(). You have no idea which sound every animal will make so you make the makeSound member function a virtual function. In fact, because there is no default sound for all animals you have no idea what to have as default behaviour so you would declare this member function as a pure virtual function.

This then tells anyone making an instance of a derived class, for example a Lion class, that they must provide an implementation the makeSound member function which will provide a roar in some way.

Edit: I forgot to add that this is one of the articles in Scott Meyers's excellent book "Effective C++" (sanitised Amazon link) which I highly recommend.



When implementing reference counting in objects the "release and possibly delete object" primitive is usually implemented like this:

void CObject::Release()
    if( referenceCount == 0 ) {
       delete this;

First of all, delete this looks scary. But since the member function returns immediately and doesn't try to access any member variables the stuff still works allright. At least that's how it is explained usually. The member function might even call some global function to write to a log that it deleted the object.

Does the C++ standard guarantee that a member function can call delete this and then do anything that will not require access to member variables and calling member functions and this will be defined normal behaviour?

This problem has a number on implications, covered best in Item 27 (10 pages) of Scott Meyers book:

More Effective C++: 35 New Ways to Improve Your Programs and Designs

If you dont have this book, buy it as well as its predecessor

Effective C++: 55 Specific Ways to Improve Your Programs and Designs

They are no "how to" Programming learning books, but rather give clear and straight (and explained) advice what to do and what not to do.


Very briefly the item covers:

  • Item 27 Requiring or prohibiting heap-based objects-

Paragraphs are titled:

  • Requiring Heap-based-Objects
  • Determining wether an Object is on the Heap
  • Prohibiting Heap-based-Objects

One of the Problems is, that you must not delete a object thats created on the stack (local objects created not using new) - this is a illegal case and will lead to a crash. But there are more implications about this items.

I can only repeat myself: Every C++ Programmer should know these books. They won't cost you too much time.


The following code block appears in Scott Meyers' famous book "Effective C++" Item 3:

class TextBlock {
    const char& operator[](std::size_t position) const
        ...    // do bounds checking
        ...    // log access data
        ...    // verify data integrity
        return text[position];
    char& operator[](std::size_t position)
        ...    // do bounds checking
        ...    // log access data
        ...    // verify data integrity
        return text[position];
    std::string text;

The author states that in the above implementation, the contents of the const and the non-const overloads are essentially the same. In order to avoid code duplication, it could be simplified like this:

class TextBlock {
    const char& operator[](std::size_t position) const    // the same as before
        return text[position];
    char& operator[](std::size_t position)        // now just calls const op[]
        return                                    // cast away const on
          const_cast<char&>(                      // op[]'s return type;
            static_cast<const TextBlock&>(*this)  // add const to *this's type;
              [position]                          // call const version of op[]
    std::string text;


My questions are:

  • When shall we need an overload for const T& and another for T&&? (Here, T may be a template parameter or a class type, so T&& may or may not mean a universal reference) I can see that in the standard library, many classes provide both overloads. Examples are constructors of std::pair and std::tuple, there are tons of overloads. (Okay, I know that among the functions, one of them is the copy constructor and one of them is the move constructor.)

  • Is there a similar trick to share the implementations for the const T& and T&& overloads? I mean, if the const T&& overload returns an object that is copy-constructed, and the T&& overload returns something that is move-constructed, after sharing the implementation, this property must still hold. (Just like the above trick: const returns const and non-const returns non-const, both before and after implementation sharing)



The two overloads I'm referring to should look like:

Gadget f(Widget const& w);
Gadget f(Widget&& w);

It is nothing related to returning by rvalue references, that is:

Widget&& g(/* ... */);

(By the way, that question was addressed in my previous post)

In f() above, if Gadget is both copy-constructible and move-constructible, there's no way (except from reading the implementation) to tell whether the return value is copy-constructed or move-constructed. It is nothing to deal with Return Value Optimization (RVO) / Named Return Value Optimization (NRVO). (See my previous post)


Effective C++



When is it a good time to return by rvalue references?

I have a lot of experience with Java/OO. There are tons of C++ tutorials/references out there, but I was wondering if there are a few key ones that a Java programmer might find useful when making the transition.

I will be moving from server-side J2EE to Windows Visual C++ desktop programming.

I have googled and found tons of resources, but am overwhelmed and don't know where to best spend my time. I have only a few days to get a good start.

Is Visual Studio Express / Microsoft Visual C++ the best IDE for me to start with?

Also, any words of wisdom from others who know and work with both languages?

Visual C++ is a good way to go, you can get the express version for free from here

As far as books It really depends what you want to do. I like the Horton book as far as learning Visual C++, GUI, CLR and Database programming. The Lippman book is a very good tutorial on C++, but it only covers the basic language, which is large.

Once you get past the basics then look at the Meyers books, as stated in other answers.
Effective C++: 55 Specific Ways to Improve Your Programs and Designs (3rd Edition)

There are a couple of others from this author, they are real good but have not been updated in a long time.

A real good online C++ FAQ is here.

If you put a comment stating what you plan to do with C++, we could give you narrower guidance to point you in the direction you want to go in

The widely recommended books here are Scott Meyers Effective series. "Effective C++", "More Effective C++" and "Effective STL".

I would also recommend the C++ FAQ Lite and The C++ Programming Language.

I have been developing using c# now since the first release of .NET. I have never really spent time on C or C++ and thought it would be a good idea to get a little more awareness. Does anyone have any recommendations for sites that would provide a good learning/tutorial for someone that has c# experience to venture into C++ a little?


Warning: C++ is not C and the following is related only with C++.

If you are already a c# developer I think you should work in three different directions:

1) copy semantic, memory management and const keyword, these are the main differences between c# and c++. Make yourself familiar with copy constructor, destructor and assignment operator. Learn how to use RAII idiom. Study the differences between passing a variable by: value, reference and pointer.

I will suggest Effective C++ also guru of the week it is a great source.

In More Effective C++ there is a nice chapter on the difference between pointer and reference.

2) you need to make yourself familiar with the standard library, in my opinion this is a really good book

3) the standard library is great but not enough, you will soon need boost.

I am reading this book at the moment

I haven't finished it yet, but it looks good so far.

Keep practise, you are going to love coding in c++.

I'm going to create a class to hold a long list of parameters that will be passed to a function. Let's use this shorter example:

class ParamList{

    ParamList(string& a_string);
    string& getString(); //returns my_string
    string& my_string;

My question is this: my_string is private, yet I'm returning the reference to it. Isn't that called something like private pointer leaking in C++? Is this not good programming practice? I want callers of getString to be able to get the reference and also modify it.

Please let me know.

Thanks, jbu

edit1: callers will use getString() and modify the string that was returned.

Returing a private reference is perfectly okay so long as:

A. That is a const reference, and you have documented when that reference can be invalidated or
B. That reference is intended to be modified (i.e. std::vector<T>::operator[])

While there are useful cases for returning a non-const reference you should usually avoid it. This is covered in Scott Meyers' Effective C++ (3rd Edition, Item 28): Avoid returning "handles" to object internals, if you'd like to take a look.

In brief, my question is about member variables as pointers in unmanaged C++.

In java or c#, we have "advanced pointer". In fact, we can't aware the "pointer" in them. We usually initialize the member of a class like this:

member = new Member();


member = null;

But in c++, it becomes more confusing. I have seen many styles: using new, or leave the member variable in stack.

In my point of view, using boost::shared_ptr seems friendly, but in boost itself source code there are news everywhere. It's the matter of efficiency,isn't it?

Is there a guildline like "try your best to avoid new" or something?


I realize it's not proper to say "leave them in stack", here's a more proper way to say: when i need an object to be my member variable, should i prefer a object than a object*?

Is there any good list of techniques + descriptions for C++ newbies. I was thinking of a list describing RAII, RVO, Lvalues... This would be for newbies that don't currently understand those techniques or come from other languages where those are not applicable.

Something short & sweet would be preferred :-)

Yes, they're in two very great books authored by the same person.

Effective C++
More Effective C++

Since I'm still learning c++ (and with still I mean since 5 years :-) ) I thought, what better way to learn the hidden details than asking for it.

So, I'm not looking for the question with the most votes, but I would like to know, if you have ever read an article here, you think every intermediate c++ programmer should read to gain a bettter understanding of the craft.

I cant suggest you an article but I can advice you two amazing books by Scott Meyers ( I hope they help you). I never seen anything better.

More Effective C++: 35 New Ways to Improve Your Programs and Designs
Effective C++: 55 Specific Ways to Improve Your Programs and Designs

Since the book Effective C++ seems to be still worth reading and the best to start with from the Effective C++ series, I wonder which suggested solutions/implementations I need not understand in detail/memorize because there are better solutions in C++11 or later. So:

Which Effective C++ Items can be implemented much simpler or better via C++11 or later? How can they be implemented now, and in which way is it better?


Since there are many C++ idioms deprecated in C++11, I guess this also influences the solutions in the Effective C++ book. For example, looking at its table of contents, I guess (since I have not yet read the book) that

  • Item 6 (Explicitly disallow the use of compiler-generated functions you do not want) becomes simpler via =delete
  • Item 17 (Store newed objects in smart pointers in standalone statements) becomes simpler via make_shared (and C++14's make_unique)
  • Item 21 (Don't try to return a reference when you must return an object) becomes simpler and more efficient via move semantics
  • Item 55 (Familiarize yourself with Boost) now has fewer examples because many boost features are also part of C++11 or later.

Correct? Any more? How are these Items implemented in modern C++?

This question is from a C# guy asking the C++ people. (I know a fair bit of C but only have some general knowledge of C++).

Allot of C++ developers that come to C# say they miss const correctness, which seems rather strange to me. In .Net in order to disallow changing of things you need to create immutable objects or objects with read only properties/fields, or to pass copies of objects (by default structs are copied).

Is C++ const correctness, a mechanism to create immutable/readonly objects, or is there more to it? If the purpose is to create immutable/readonly objects, the same thing can be done in an environment like .Net.

Excellent Scott Meyer's book Effective C++ has dedicated an item to this issue:

ITEM 3: Use const whenever possible.

It really enlightens you :-)

What makes smartpointers better than normal pointers?

Fewer memory leaks. Maybe Scott Meyers can make it clearer for you:

  1. Effective C++
  2. More Effective C++

Possible Duplicate: What is the difference between const int*, const int * const, and int const *?

What is the difference between the following?

char const *p;
const char  *p;
char *const p;

And is there a good site where I can relearn C and C++? It seems that I forgot it and job interviews are doing me an hard time...

  1. Buy a copy of Kernighan & Ritchie (K&R) and work through it.
  2. Do the exercises in K&R and understand the solutions provided in The C Answer Book.
  3. Buy a copy of Accelerated C++ and work through it, because it treats C++ as its own language and not just C with "bits bolted on".
  4. Buy a copy of Effective C++, don't violate the items and read each one to understand why you shouldn't violate them.

As an added bonus, read Effective STL to use the STL properly.

Possible Duplicate:
C++ blogs that you regularly follow?

where can we find some good c++ programming articles by experts programmers. I want to read their experience, pitfalls, do's n donts etc.

Get and read Scott Meyers' Effective C++ and More Effective C++. Quickly!

  1. Local static variable created once and method goes out of scope but static variable is not destroyed and it will lives in memory until program got end.
  2. Global static variable lives in memory until program got end

so what is difference between local and global static variable?

When we have to use local static variable and global static variable?

Other answers have told you the differences between a local static object (local to a function) and a non-local static object (static objects declared global or in a namespace); however, you should also understand the importance of using one over the other.

The information I use here comes from Effective C++ Third Edition by Scott Myers (a recommended and excellent read)

A static object is one that exists from the time it's constructed until the end of the program.

As others have mentioned, a non-local static object is constructed before main whereas a local static object is constructed the first time the function is called.

But what if you had two static objects and one relied on the other. How could you be sure that one would be constructed before the other? You can't: The relative order of initialisation of non-local static objects defined in different translation units is undefined

Scott Myers definition of a translation unit (from aforementioned book):

A translation unit is the source code giving rise to a single object file. It's basically a single source file, plus all of the #include files.

So imagine you have these two non-local static objects in separate source files, you couldn't guarantee one would be constructed before the other. This is where a local static object prevails!

Consider Scott Myers' example of a FileSystem class and a Directory class, where the Directory relies on the FileSystem:

class FileSystem
    size_t numDisks() const;
extern FileSystem tfs;


class Directory
        size_t disks = tfs.numDisks();

If Directory gets constructed before FileSystem, then you are going to be using an uninitialised class! Fortunately, you can get around this by using local static objects!

class FileSystem
    size_t numDisks() const;
FileSystem& tfs()
    static FileSystem fs;
    return fs;

Now when Directory is constructed, even if it's constructed before FileSystem is, FileSystem is guaranteed to be constructed before it's used!

Could you let me know about books that explains the ideas of smart pointer very clearly (beginner, intermediate and advanced level)?

Thank you.

Scott Meyers has an a few items on it. You might not need a whole book.

Scott Meyers books :

Effective C++

More Effective C++

Effective STL

Does it make any sense to write code like this?

template<bool X>
double foo(double x){
     return (X) ? moo(x) : bar(x);

I know that there are better ways to implement this example, but I wonder, if it is safe in general to assume that the compiler will identify dead code and instantiates this as

double foo<true>(double x){return moo(x);}
double foo<false>(double x){return bar(x);}

The thing to keep in mind here is templates are different from language features like generics in languages like C#.

It is a fairly safe simplification to think of templates as an advanced preprocessor that is type aware. This is the idea behind Template metaprogramming (TMP) which is basically compile time programming.

Much like the preprocessor templates are expanded and the result goes through all of the same optimization stages as your normal logic.

Here is an example of rewritting your logic in a style more consistent with TMP. This uses function specialization.

template<bool X>
double foo(double x);

double foo<true>(double x)
    return moo(x);

double foo<false>(double x)
    return bar(x);

TMP was actually discovered as a happy accident and is pretty much the bread and butter of the STL and Boost.

It is turing complete so you can do all sorts of computation at compile time.

It is lazily evaluated so you could implement your own compile time asserts by putting invalid logic in a specialization of a template that you don't want to be used. For example if I were to comment out the foo<false> specialization and tried to use it like foo<false>(1.0); the compiler would complain, although it would be perfectly happy with foo<true>(1.0);.

Here is another Stack Overflow post that demonstrates this.

Further reading if interested:

  1. Modern C++ Design
  2. C++ Template Metaprogramming: Concepts, Tools, and Techniques from Boost and Beyond
  3. Effective C++

I am a fairly capable Ruby scripter/programmer, but have been feeling pressure to branch out into C++. I haven't been able to find any sites along the lines of "C++ for Ruby Programmers". This site exists for Python (which is quite similar, I know). Does anyone know of a guide that can help me translate my Ruby 'thoughts' into C++?

If you want to learn C++, start here. Once you have learned the fundamentals, you should also look into these: Effective C++, More Effective C++, Effective STL, and Exceptional C++

I am trying to wrap my head around something I've been wondering for quite some time now. Assume I have a class Base

class Base
    virtual ~Base(){}
    virtual bool operator== ( const Base & rhs ) const;

Now, another class inherits from it. It has two equality operators:

class A : public Base
    bool operator== ( const A & rhs ) const;
    bool operator== ( const Base & rhs ) const;
    int index__;

And yet another class which also inherits from Base, and which also has two equality operators:

class B : public Base
    bool operator== ( const B & rhs ) const;
    bool operator== ( const Base & rhs ) const;
    int index__;

This is what I understand (which is not necessarily correct). I can use the first operator only to check if same class objects are equal. Yet, I can use the second operator to check if they are the same type of class, and then if they are equal. Now, yet another class exists, which wraps around pointers of Base, which are however, polymorphic types A, or B.

class Z
    bool operator== ( const Z & rhs ) const;
    std::shared_ptr<Base> ptr__;

First things first, I've found out, that I can't have two operator== overloaded. I get no errors from the compiler, but when I try to run it, it just hangs. I am guessing it has something to do with rtti, which is beyond me.

What I have been using, and is quite ugly, is attempting to downcast, and if I can, then try to compare instances, within class Z:

bool Z::operator== ( const Z & rhs ) const
    if ( const auto a1 = std::dynamic_pointer_cast<A>( this->ptr__ ) )
        if ( const auto a2 = std::dynamic_pointer_cast<A>( rhs.ptr__ ) )
            return *a1 == *a2; 
    else if ( const auto b1 = std::dynamic_pointer_cast<B>( this->ptr__ ) )
        if ( const auto b2 = std::dynamic_pointer_cast<B>( rhs.ptr__ ) )
            return *b1 == *b2;
    return false;

This is quite ugly, and it assumes that your class A and B, have an equality operator which takes as parameter the same type class.

So I tried to come up with a way, which would use the second type of operator, more agnostic, more elegant if you will. And failed. This would require to use it in both classes A and B, thus moving it away from class Z.

bool A::operator== ( const Base & rhs ) const
    return ( typeid( *this ) == typeid( rhs ) ) && ( *this == rhs );

Same for class B. This doesn't seem to work (app hangs without any errors). Furthermore, it uses some kind of default operator, or does it use the base class operator? Ideally, it should use both the Base::operator== and compare class types.

If however, I want a more elaborate comparison, based upon a member of class A, or B, such as index__ then I obviously have to friend each class, because when I try this, it won't compile (unless of course I add a getter or make it somehow visible):

bool A::operator== ( const Base & rhs ) const
    return ( typeid( *this ) == typeid( rhs ) )
           && (*this == *rhs )
           && (this->index__ == rhs.index__ );

Is there an elegant, simple solution to this? Am I confined to downcasting and trying, or is there some other way to achieve what I want?

In general, in a hierarchy, one should have a common interface, and imo the operator== should be only implemented in the Base class using (virtual) getters from the interface. Otherwise it's like re-defining functions (without using virtual) down the hierarchy, which is almost always a bad idea. So you may want to think about your design, having more than one operator== seems fishy.

Very simple example:

#include <iostream>

class A
    int _x;
    A(int x):_x(x){}
    virtual int getx() const { return _x; } // runtime
    bool operator==(const A& other){return getx() == other.getx();} // one implementation

class B: public A
    using A::A;
    int getx() const override // Make all B's equal, runtime
        return 0; // so always 0, all B's are equal

int main()
    A a1(10), a2(20);
    B b1(10), b2(20);
    std::cout << std::boolalpha << (a1==a2) << std::endl; // false
    std::cout << std::boolalpha << (b1==b2) << std::endl; // always true

This pattern is usually called the non-virtual interface idiom and is a manifestation of the so called template method (has nothing to do with templates, just an unfortunate name), in which you have clients (along the hierarchy) call virtual functions indirectly through public non-virtual member functions. Item 55 of Scott Meyers' Effective C++ has an excellent discussion about this issue.

I have a pointer which is pointing to an integer variable. Then I assign this pointer to a reference variable. Now when I change my pointer to point some other integer variable, the value of the reference variable doesn't change. Can anyone explain why?

int rats = 101;
int * pt = &rats;
int & rodents = *pt;                                // outputs    
cout << "rats = " << rats;                          // 101
cout << ", *pt = " << *pt;                          // 101
cout << ", rodents = " << rodents << endl;          // 101
cout << "rats address = " << &rats;                 // 0027f940
cout << ", rodents address = " << &rodents << endl; // 0027f940
int bunnies = 50;
pt = &bunnies;

cout << "bunnies = " << bunnies;                    // 50
cout << ", rats = " << rats;                        // 101  
cout << ", *pt = " << *pt;                          // 50
cout << ", rodents = " << rodents << endl;          // 101
cout << "bunnies address = " << &bunnies;           // 0027f91c
cout << ", rodents address = " << &rodents << endl; // 0027f940

We assigned pt to bunnies, but the value of rodents is still 101. Please explain why.

The line

int & rodents = *pt;

is creating a reference to what pt is pointing to (i.e. rats). It's not a reference to the pointer pt.

Later, when you assign pt to point to bunnies, you would not expect the rodents reference to change.

EDIT: To illustrate @Als point, consider the following code:

int value1 = 10;
int value2 = 20;
int& reference = value1;
cout << reference << endl; // Prints 10
reference = value2; // Doesn't do what you might think
cout << reference << endl; // Prints 20
cout << value1 << endl; // Also prints 20

The second reference assignment does not change the reference ltself. Instead, it applies the assignment operator (=) to the thing referred to, which is value1.

reference will always refer to value1 and cannot be changed.

It's a little tricky to get your head around at first, so I recommend you take a look at Scott Meyer's excellent books Effective C++ and More Effective C++. He explains all this much better than I can.

I'm learning C++ from "C++ for Programmers" book. In "templates" section, there is a code like that:

template<typename T>
void printArray(const T * const array, int size)
    for (int i = 0; i < size; i++)
        cout << array[i] << " ";

    cout << endl;

My question is, the constants of first parameter in function. I have never seen two constants in one parameter. I tried to realize but I could not. Thanks for helps.

In your example, you have a const pointer to a const object of type T. This means you can't change where the pointer is pointing or the object to which it points.

You can actually have const in even more places in a single line. Take this declaration for example:

class MyClass {
    const std::string& get_name(const int * const id) const;

In this case, the function get_name is constant, and can't modify the instance of MyClass. It takes in a constant pointer to a constant integer, and returns a constant reference to a string.

If you'd like to learn more about best practices while using const (and other parts of C++), I highly recommend Bruce Eckel's book Effective C++: 55 Specific Ways to Improve Your Programs and Designs.

Item 25 in Effective c++ third edition, Scott Meyers suggests to implement swap in the same namespace as the class, and then when swapping to employ the using std::swap, and there the author says :

For example, if you were to write the call to swap this way:

std::swap(obj1,obj2);  // the wrong way to call swap

you'd force the compiler to consider only the swap in std, thus eliminating the possibility of getting a more appropriate T-specific version defined elsewhere. Alas, some misguided programmers do qualify calls to swap in this way, and that is why it's important to totally specialize std::swap for your classes.

The author recommends to always swap objects this way :

#include <iostream>
#include <utility>


namespace aaa{

struct A
void swap( A&, A& )
    std::cout<<"not std::swap"<<std::endl;


int main() 
    using std::swap;   // add std::swap to a list of possible resolutions

    aaa::A a1;
    aaa::A a2;


Why isn't std::swap in global namespace? That way, it would be simpler to add custom swap functions.

Probably because the standard says so,

All library entities except macros, operator new and operator delete are defined within the namespace std or namespaces nested within namespace std.

And you would still need to put using ::swap sometimes, so it would introduce even more special cases. Here I use func instead of swap - :

#include <iostream>
using namespace std;

template <class T>
auto func(T) -> void
cout << "::f" << endl;

namespace my_ns {
struct my_struct {};

auto func(my_struct) -> void
cout << "my_ns::func" << endl;

auto another_func() -> void
// won't compile without `using ::func;`

auto main() -> int {}

fails with

prog.cpp: In function ‘void my_ns::another_func()’:
prog.cpp:21:17: error: could not convert ‘123’ from ‘int’ to ‘my_ns::my_struct’

The code is as follows:

template <int __inst>
__malloc_alloc_template<__inst>::_S_oom_malloc(size_t __n)
    void (* __my_malloc_handler)();
    void* __result;

    for (;;) {
        __my_malloc_handler = __malloc_alloc_oom_handler;
        if (0 == __my_malloc_handler) { __THROW_BAD_ALLOC; }
        __result = malloc(__n);
        if (__result) return(__result);

I have two questions. 1. why does _S_oom_malloc use infinite loop? 2. as we known, _S_oom_malloc will be called when malloc fails in __malloc_alloc_template::allocate function. And why does it use malloc to allocate space?

Anyone can help me? Thanks a lot.

First, the loop is not truly infinite. There are two exits: by throwing a BAD_ALLOC exception an by allocating the requested amount of memory. The exception will be thrown when the current new-handler is a null pointer.

To understand how that can happen, consult e.g. Item 49 from Effective C++. Essentially any new-handler can either

  • Make more memory available
  • Install a different new-handler
  • Deinstall the new-handler (i.e. passing a null pointer to set_new_handler
  • Throw an exception
  • abort or exit

Second, the reason that it uses the C library's malloc to allocate space is that malloc on most systems is a well-tested and efficiently implemented function. The Standard Library's new functions are "simply" exception-safe and type-safe wrappers around it (which you as a user can also override, should you want that).

This is the base class:

template <class T>
class DataLogger
        // ...
        void AddData(T Data);
        // ...

And this is the derived class:

#include "DataLogger.h"
#include <utility>

class Plotter : public DataLogger<std::pair<long double, long double>>
        // ...
        void AddData(long double x, long double y);
        // ...

// This method is supposed to wrap the original AddData() method
// which was defined in the base class
void Plotter::AddData(long double x, long double y)
    AddData(std::make_pair(x, y));  // LINE #29

The given error is:

LINE 29: IntelliSense: no suitable conversion function from "std::pair" to "long double" exists

LINE 29: IntelliSense: too few arguments in function call

Apparently, the problem is that I can not access to the method in base class from derived class, even though it is defined public.

How do I make this code work?

(My IDE is Visual Studio 2010.)

Your AddData in derived class hides the function AddData in the base class, so all you need to do is, unhide the latter using using directive:

class Plotter : public DataLogger<std::pair<long double, long double>>

   //unhiding : bringing base class function into scope!
   using DataLogger<std::pair<long double, long double>>::AddData;


Read Item 33: Avoid hiding inherited names from Effective C++ by Scott Meyers.

This should be a simple 100-level question, but I'm seeing something I don't expect in my project, and web searches have failed me, so I thought I'd ask here. Suppose I have the following C++ code:

class BaseClass {
  BaseClass() { 

  int foo() {
    return this->foo_;

  virtual int GetInitialValue() { 
    return 1; 

  void Initialize() {
    this->foo_ = this->GetInitialValue();

  int foo_;

class DerivedClass : public BaseClass {
  DerivedClass() : BaseClass() {

  virtual int GetInitialValue() { 
    return 2; 

What should be the return value of DerivedClass::foo()? Will BaseClass::GetInitialValue() ever get called, or will it always be DerivedClass::GetInitialValue() that gets called? Where should I have searched, and what search terms should I have used to find the answer?

GetInitialValue() isn't virtual so there isn't dynamic dispatch anyway.

In your situation, the expected value of foo() would be 1, as the value of _foo is set in the BaseClass constructor. The derived class's version isn't called as the BaseClass constructor is called first, and the DerivedClass members haven't been initialized yet.

This is also item #9 in Effective C++, and that snippet is in this page from artima:

The summary from that article is:

Things to Remember

Don't call virtual functions during construction or destruction, because such calls will never go to a more derived class than that of the currently executing constructor or destructor

#include <iostream>

class Base {
   Base() { this->initialize(); }
   void initialize() { this->_foo = this->getInitial(); }
   virtual int getInitial() { return 1; }

   int _foo;

class Derived : public Base {
      Derived() : Base() {}
      virtual int getInitial() { return 2;}

int main()
   Base* dp = new Derived();
   std::cout << dp->_foo << std::endl;

This code outputs 1.

What I want to do is that I have a list std::list<Displayable> display_queue

Displayable being defined in Displayable.h as:

class Displayable { 


        int x, y;

        Displayable() : x(0), y(0) {}
        Displayable(int x, int y) : x(x), y(y) {}


and DifferentDisplayable as:

class DifferentDisplayable : public Displayable { 


        std::string id;

        DifferentDisplayable() : Displayable(), id("") {}
        DifferentDisplayable(int x, int y) : Displayable(x, y), id("") {}
        DifferentDisplayable(int x, int y, std::string id) : Displayable(x, y), id(id) {} 


The items added to the list is:

Displayable disp_one;
DifferentDisplayable disp_two(10, 10, "the id");


Since DifferentDisplayable is derived from Displayable it is able to be stored in the list but what I can't figure out is how can I or can I even access std::string id in DifferentDisplayable when iterating through the list (display_queue) like so:

for (std::list<Displayable>::iterator i = display_queue.begin(); i != display_queue.end(); i++) {

    // insert code here


Thanks in advance for any answers

If 'id' isn't needed for all derived classes, then instead of trying to access it directly from your loop, add a base class method that uses it. For example:

class Displayable
  virtual void Display();

(Even better would be to make 'class Displayable' an abstract base class, with Display() as a pure virtual function. See the links below.)

Then the implementations can vary independently:

void Displayable::Display()
  // Do something here with 'x' and 'y'

void DifferentDisplayable::Display()
  // Do something here with 'x', 'y', and 'id'

Then allocate your objects on the heap to avoid the slicing problem:

Displayable* disp_one = new Displayable();
DifferentDisplayable* disp_two = new DifferentDisplayable(10, 10, "the id");


Then your loop becomes:

for (std::list<Displayable>::iterator i = display_queue.begin(); i != display_queue.end(); ++i) {

Remember to 'delete' the pointers when you're done with them.

This strategy is discussed in the Open-Closed Principle and in Item 34 "Differentiate between inheritance of interface and inheritance of implementation" in Effective C++ 3rd Edition by Scott Meyers.

I am new to Stack Overflow, and new to programming. I am learning how to program in C++.

My question is not related to specific code, but is about research and learning the language. What I have learned so far relates to narrow examples of syntax and simple programs which use variables, functions, arrays, etc.

I am wondering if people have or can link to example programs so I can study them.

I'm looking for console programs which:

  • use variables (int, double, string, etc)
  • use functions
  • use arrays use classes with
  • attributes and methods use objects of that class
  • reads and writes to a file
  • validates user inputs, displaying appropriate error messages

and is basically a useful program.

Through Google, I have mostly only been able to find C++ tutorial pages (cplusplus, cprogramming, etc) which deal with each of the above separately, usually in a bare-bones way to show the syntax. I'm looking for something more complex (but not overly so) so I can learn how to combine these things in a meaningful way with the intent of eventually writing programs of my own at the same level.

I've already coded a calculator (though not one that has all of these features; namely it was missing file i/o and I was able to make a basic one which didn't need objects), so I'm looking for something different. I understand console programs are text based and lend themselves well to these kind of programs, so it can be a calculator of another type, as long as it isn't a basic arithmetic one. has a few examples.

As @GMan said, you'd be better off reading a book.

Possibly Effective C++ by Scott Meyers, or maybe one in the Beginner\Introductory section.

The best way to improve is to give yourself a task and code it. Use different techniques/paradigms (OOP, modular, etc). Instead of studying programs, try to create them yourself - you'll learn a lot better this way.

The book can guide you, but you must make the journey.

Here are some exercises. You can try solving puzzles, too. CodeGolf.SE is good if you want to have some fun.

I have a huge C++ solution.

When I change one class and compile In some cases compilation (and linkage) takes little time (less than a second) But in some cases it takes ages (more that 30 seconds)

I do not understand why this happens. The huge difference in performance suggests that something can be done in order to maximize the number of times the compiler is fast.

Any ideas?

Say you have a class A and you add a new data member to it in the header file. Then A has to be recompiled. If B contains A as a member then B has to be recompiled as well. If C has a member B then C also has to be recompiled and so on. A change in A can have a domino effect. A seemingly tiny change (adding a new data member to a class) can result in recompiling the entire project.

On the other hand, if you make substantial changes to implementation of a member function of A in the implementation source file (*.cpp) then, chances are, only A has to be recompiled but nothing else. This is likely to be very fast.

If you wish to understand what triggers the domino effect and what doesn't, I suggest you read Item 31: Minimize compilation dependecies between files in Effective C++ and Items 26-30 on Minimizing Compile-time Dependencies in Exceptional C++.

There is no magic setting of the compiler that will make the compilation fast. Only your understanding and careful coding can help.

I have a vector of structs declared in a class. My question is do I have to explicitly free the memory allocated by the vector in the class destructor or is that done automatically when I destroy the instance. As in, do I have to include code in the class destructor to free the memory of the vector.

If you are allocating the structs yourself using new then you need to deallocate them using delete when you are finished with them. std::vector won't do that for you.

Item 13 in the book Effective C++ (highly recommended) says to use objects to manage resources. This helps you avoid problems like having to worry about your resource de-allocation code not getting called because, for example, an exception was thrown. If you are using C++11 you can look into shared_ptr or just create your own resource management class.

Update: As jogojapan pointed out, std::auto_ptr is unsuitable for STL containers.

I'm interested in improving my understanding of how to avoid writing a C++ class that causes problems when copied.

In particular, I've written a class named Policy that I intend to copy. I have not defined a non-default destructor, copy constructor, or copy assignment operator. The only operator I've overloaded is the following:

friend bool operator== (const Policy& p1, const Policy& p2) {
    for(int i=0; i<p1.x.size(); i++) {
        if(p1.x[i] != p2.x[i])
            return false;
    return true;

The class's members are either standard data types such as int, double, bool, std::string, std::vector<double>, std::vector<int>, std::vector<string>, or one of a few small (and thus not overly complex) classes I defined that are definitely copyable without any problem. Now, there is a member of Policy that is an instance of the NRRan class, which is a class I built as a wrapper around a non-copyable third-party data type; NRRan is as follows:

class NRRan {
    double doub() { return stream->doub(); }

    int intInterval(const int& LB, const int& UB) { return LB+int64()%(UB-LB+1); }

    void setNewSeed(const long& seed) {
        delete stream;
        stream = new Ranq1(seed);

    NRRan() { stream = new Ranq1(12345); }    

    ~NRRan() { delete stream; }

    NRRan(const NRRan& nrran) {
        stream = new Ranq1(12345);
        *stream = *(;

    NRRan& operator= (const NRRan& nrran) { 
        if(this == &nrran)
            return *this;    
        delete stream;
        stream = new Ranq1(12345);
        *stream = *(;    
        return *this;

    Ranq1* stream;  // underlying C-struct 
    Ullong int64() { return stream->int64(); }    

But the whole point of the NRRan class is to make Ranq1 copyable. So, given the Policy class as I've described it (sorry, I am unable to post a large part of the code), is there any thing that might cause a problem when I copy Policy? My expectation is that copying will create a perfect value-for-value copy.

A more general way of asking my question is the following: Generally speaking, what types of things can possibly cause problems when copying a class? Is there anything in addition to the "Rule of Three" (or "Rule of Five") to be concerned about when making a class copyable?

You should take a look at the book "Effective C++", especially Chapter 2.

Chapter 2: Constructors, Destructors, and Assignment Operators

In Chapter 9 of Effective C++: 55 Specific Ways to Improve Your Programs and Designs (3rd Edition) by Scott Meyers, it has a section entitled Item 53: Pay Attention to compiler warnings. Meyers says that the following program should give a warning:

class B {
  virtual void f() const;

class D: public B {
  virtual void f();

And says:

The idea is for D::f to redefine the virtual function B::f, but there’s a mistake: in B, f is a const member function, but in D it’s not declared const. One compiler I know says this about that:

warning: D::f() hides virtual B::f()

Too many inexperienced programmers respond to this message by saying to themselves, "Of course D::f hides B::f — that’s what it’s supposed to do!" Wrong. This compiler is trying to tell you that the f declared in B has not been redeclared in D; instead, it’s been hidden entirely (see Item 33 for a description of why this is so). Ignoring this compiler warning will almost certainly lead to erroneous program behavior, followed by a lot of debugging to discover something this compiler detected in the first place.

But my compiler doesn't give any warning, even with with -Wall. Why doesn't my compiler (GCC) give a warning?

I've studied C++ as a college course. And I have been working on it for last three years. So I kinda have a fairly good idea what is it about. But I believe to know a language is quite different from using it to full potential. My current job doesn't allow me to explore much.

I have seen you guys suggest studying a open source project and perhaps contributing to one too. So my question is, can you suggest one(of both?) to start with that is simple and doesn't overwhelm a starter.

I was in the same situation 12 years ago when I got my first programming job out of college. I didn't do any open source but I managed to gain a lot of practical and advanced C++ knowledge by reading books (the dead tree kind).

In particular, there was an excellent series by Scott Meyers which I feel helped the most in turning me from newbie to professional:

Effective C++: 55 Specific Ways to Improve Your Programs and Designs

More Effective C++: 35 New Ways to Improve Your Programs and Designs

Effective STL: 50 Specific Ways to Improve Your Use of the Standard Template Library

The topics in these books range from beginner to advanced. It took me about 2 years working in C++ to understand every chapter in these books, so don't be disheartened if it goes over your head at some point... just try reading it again later :)

I want to know more about the casting (like static cast, dynamic cast, const cast and reinterpret cast) and when do we REALLY need that (real life scenario)? Any references/links/books will be appreciated.


Chapter 5 of Scott Meyers' Effective C++ Third Edition has a discussion about casting in C++.

alt text

Say I have a class Foo that has a member function which returns a non-const reference, that itself runs a member function that uses a const this pointer:

class Foo{
    Foo& display(std::ostream& os) { do_display(os); return *this; }
    void do_display(std::ostream& os) const { os << contents; }
    std::string contents;

When display runs do_display, the this pointer gets implicitly converted to a pointer to const. Why is it, then, that when do_display terminates, display is still able to change the object it was called on? As far as I know, it's not possible to assign a pointer to const to a pointer to non-const normally. Any insight is appreciated.

In C++ const access is often only a compile-time attribute [1] that is introduced to ease the control of the object's state. [2]

The method do_display() does not change anything of this but it restricts the access to read-only in its scope. After the call of the do_display() method returned, the access is read-write as before in the scope of the display() method.

[1] that's the reason for the option to cast const away, which can be considered safe if the constness is only a declarative one.

[2] see Item #3 in Effective C++: 55 Specific Ways to Improve Your Programs and Designs (3rd Edition): Scott Meyers or for example Const Correctness - C++ Tutorials -

While trying to formulate a C macro to ease the writing of non-const member functions calling const member functions with exact same logic (see Chapter 1, Item 3, "Avoiding Duplication in const and Non-const Member Functions" in Effective C++), I believe I came across a decltype() bug in VS2013 Update 1.

I wanted to use decltype(*this) to build a static_cast<decltype(*this) const&>(*this) expression in the aforementioned macro to avoid having the macro call site pass any explicit type information. However, that latter expression doesn't appear to properly add const in some cases in VS2013.

Here's a small block of code I was able to make repo the bug:

#include <stdio.h>

template<typename DatumT>
struct DynamicArray
    DatumT* elements;
    unsigned element_size;
    int count;

    inline const DatumT* operator [](int index) const
        if (index < 0 || index >= count)
            return nullptr;

        return &elements[index];

    inline DatumT* operator [](int index)
#if defined(MAKE_THIS_CODE_WORK)
        DynamicArray const& _this = static_cast<decltype(*this) const&>(*this);
        return const_cast<DatumT*>(_this[index]);
        // warning C4717: 'DynamicArray<int>::operator[]' : recursive on all control paths, function will cause runtime stack overflow
        return const_cast<DatumT*>(
                static_cast<decltype(*this) const>(*this)

int _tmain(int argc, _TCHAR* argv[])
    DynamicArray<int> array = { new int[5], sizeof(int), 5 };
    printf_s("%d", *array[0]);
    delete array.elements;

    return 0;

(may the first one to blab about not using std::vector be smitten)

You can either compile the above code and see the warning yourself, or refer to my lone comment to see what VC++ would spew at you. You can then ! the defined(MAKE_THIS_CODE_WORK) expression to have VC++ compile the code as how I'm excepting the #else code to work.

I don't have my trusty clang setup on this machine, but I was able to use GCC Explorer to see if clang complains (click to see/compile code). Which it doesn't. However, g++ 4.8 will give you an ‘const’ qualifiers cannot be applied to ‘DynamicArray&’ error message using that same code. So perhaps g++ also has a bug?

Referring to the decltype and auto standards paper (albeit, it's almost 11 years old), the very bottom of page 6 says that decltype(*this) in a non-const member function should be T&, so I'm pretty sure this should be legal...

So am I wrong in trying to use decltype() on *this plus adding const to it? Or is this a bug in VS2013? And apparently g++ 4.8, but in a different manner.

edit: Thanks to Ben Voigt's response I was able to figure out how to craft a standalone C macro for what I'm desire to do.

// Cast [this] to a 'const this&' so that a const member function can be invoked
// [ret_type] is the return type of the member function. Usually there's a const return type, so we need to cast it to non-const too.
// [...] the code that represents the member function (or operator) call
#define CAST_THIS_NONCONST_MEMBER_FUNC(ret_type, ...)   \
    const_cast<ret_type>(                               \
        static_cast<                                    \
            std::add_reference<                         \
                std::add_const<                         \
                    std::remove_reference<              \
                        decltype(*this)                 \
                    >::type                             \
                >::type                                 \
            >::type                                     \
        >(*this)                                        \
        __VA_ARGS__                                     \
// We can now implement that operator[] like so:
return CAST_THIS_NONCONST_MEMBER_FUNC(DatumT*, [index]);

The original desire was to hide this all in a macro, which is why I wasn't wanting to worry about creating typedefs or this aliases. It is still curious that clang in GCC Explorer didn't output a warning...though the output assembly does appear fishy.

You said yourself, decltype (*this) is T&. decltype (*this) const & tries to form a reference to a reference (T& const &). decltype triggers the reference collapsing rule 8.3.2p6. But it doesn't collapse the way you'd like.

You could say decltype(this) const&, but that would be T* const& -- a reference to a const pointer, not a pointer to a const object. For the same reason, decltype (*this) const and const decltype (*this) don't form const T&, but (T&) const. And top-level const on a reference is useless, since references already forbid rebinding.

Perhaps you are looking for something more like

const typename remove_reference<decltype(*this)>::type &

But note that you don't need the cast at all when adding const. Instead of

DynamicArray const& _this = static_cast<decltype(*this) const&>(*this);

just say

DynamicArray const& _this = *this;

These combine to

const typename std::remove_reference<decltype(*this)>::type & this_ = *this;

Still, this is a stupid amount of code for a very simple and pervasive problem. Just say:

const auto& this_ = *this;

FYI here's the text of the reference collapsing rule:

If a typedef-name (7.1.3, 14.1) or a decltype-specifier ( denotes a type TR that is a reference to a type T, an attempt to create the type "lvalue reference to cv TR" creates the type "lvalue reference to T", while an attempt to create the type "rvalue reference to cv TR" creates the type TR.

decltype(*this) is our decltype-specifier which denotes TR, which is DynamicArray<DatumT>&. Here, T is DynamicArray<DatumT>. The attempt TR const& is the first case, attempt to create lvalue reference to (const) TR, and therefore the final result is T&, not const T&. The cv-qualification is outside the innermost reference.

I'm starting C++ programming in my first job. I'm a CS student and I have learn programming in Java. What advice would you tell me to watch out so I don't cause trouble in my new job?
Would you have any advice or references would be appreciated.
(example: I know C++ is more likely to have memory problem than Java)

Thank you very much!

Two things:

  • Get yourself a copy of Effective C++ by Scott Meyers.
  • Lint your code. This will not only catch potential bugs early in the development process, but also teach you good coding habits (e.g. declaring a method's input arguments as const references). I use PC-Lint for this.

I'm using c++ and i'm in a really deeply nested set of functions and a special case has occurred and I would like to exit to the top level.

Now I hear c++ exceptions are deprecated now so what should I use instead in this case?

So what i'm really asking is, are setjmp() and longjmp() OK in c++ code?

If possible I would avoid using setjmp/longjmp, as most C stuff, in C++ code. For what concerns C++ exceptions, as far as I know, they are not deprecated. Indeed, I think it would be very hard to deprecate such a pervasive feature without severely hindering backwards compatibility. It's possible that you have heard that (some form of) exception specifications, a feature of the recent C++11 standard that was not present in the previous version of the language, has been deprecated during the approval process (see, e.g., this post on Herb Sutter's blog).

This said, exceptions in C++ are not easy to use well. C++ has lots of features, and sometimes they interplay in very complex ways. Some necessary (but not sufficient) advices are:

  • Derive your exceptions from std::exception;
  • Manage your resources via RAII;
  • Catch by reference, not by value or by pointer.

But the best advice is: understand exactly how exceptions work - precanned advices do not work well. At the purpose, you might read this, this, this and this about how to use exceptions and RAII. Especially "More Effective C++" has a whole chapter dedicated to exceptions, exposing some intricate consequences of apparently simple snippets of code. It raises your overall awareness of the language.

Should I always add public keyword when inheriting a class? When doing this code:

class Derived : public Base {


I think this the right thing to do in 99% cases. Right?

It depends on what model you are looking for.

From Scott Myers - Effective C++ Third Edition (a recommended read, btw):

public inheritance means "is-a". If you write that class D ("Derived") publicly inherits from class B ("Base"), you are telling C++ compilers (as well as human readers of your code) that every object of type D is also an object of type B, but not vice versa


private inheritance means "is-implemented-in-terms-of"

I have been learning programing, mainly JavaScript and C++, but all the programs I have been writing are simple and in note pad like applications.

What would I need to make a simple calculator that takes user input and dose calculations with it.

What would I use to get the GUI on the screen, how would I compile it, and what IDE should I use.

Develop deep understanding of c++ concepts. Study more and good books including it's standard. Start with normal applications & go towards advanced programming. for GUI, try QT - it's good of go for MFC Application. Write Code yourself and work on different projects, alogirithms. For book suggestion, i suggest you getting Scott Mayers Effective c++

For Compiler, i suggest using Visual Studio on widnows - it's awesome IDE.