Nos camarades Français

Elida Maria Szarota

Mentioned 32

More on

Mentioned in questions and answers.

This question was already asked in the context of C#/.Net.

Now I'd like to learn the differences between a struct and a class in C++. Please discuss the technical differences as well as reasons for choosing one or the other in OO design.

I'll start with an obvious difference:

  • If you don't specify public: or private:, members of a struct are public by default; members of a class are private by default.

I'm sure there are other differences to be found in the obscure corners of the C++ specification.

According to Stroustrup in the C++ Programming Language:

Which style you use depends on circumstances and taste. I usually prefer to use struct for classes that have all data public. I think of such classes as "not quite proper types, just data structures."

Functionally, there is no difference other than the public / private

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.

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:

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.

I have 2 solutions for the same problem - to make some kind of callbacks from one "controller" to the used object and I don't know what to chose.

Solution 1: Use interfaces

struct AInterface
    virtual void f() = 0;

struct A : public AInterface
    void f(){std::cout<<"A::f()"<<std::endl;}

struct UseAInterface
    UseAInterface(AInterface* a) : _a(a){}
    void f(){_a->f();}

    AInterface* _a;

Solution 2: Use templates

struct A
    void f(){std::cout<<"A::f()"<<std::endl;}

template<class T>
struct UseA
    UseA(T* a) : _a(a){}
    void f(){_a->f();}

    T* _a;

This is just a simple sample to illustrate my problem. In real world the interface will have several functions and one class may(and will!) implement multiple interfaces.

The code will not be used as a library for external projects and I don't have to hide the template implementation - I say this because first case will be better if I need to hide "controller" implementation.

Can you please tell me the advantages/disadvantages for each case and what is better to use?

There are pros and cons to each. From the C++ Programming Language:

  1. Prefer a template over derived classes when run-time efficiency is at a premium.
  2. Prefer derived classes over a template if adding new variants without recompilation is important.
  3. Prefer a template over derived classes when no common base can be defined.
  4. Prefer a template over derived classes when built-in types and structures with compatibility constraints are important.

However, templates have their drawbacks

  1. Code that use OO interfaces can be hidden in .cpp/.CC files, whenever templates force to expose the whole code in the header file;
  2. Templates will cause code bloat;
  3. OO interfaces are explicit, whenever requirements to template parameters are implicit and exist only in developer's head;
  4. Heavy usage of templates hurts compilation speed.

Which to use depends on your situation and somewhat on you preferences. Templated code can produce some obtuse compilation errors which has lead to tools such as STL Error decrypt. Hopefully, concepts will be implemented soon.

I'm a Perl5 programmer for 7 years and I'm trying to learn C++ now. Some of the C++ syntax is hard for me to understand and to think in C++ way.

For example: In Perl, you can mix the data in the arrays

@array = (1,"string",5.355);

You can assign any value to a scalar variable:

$var = 1;
$var = "string";
$var = \$reference_to_scalar;

There are many examples.

A friend of mine recommend me the book "Thinking of C++" by Bruce Eckel, but I haven't any C background and it's hard for me to understand some things.

So my question is - could you recommend me a book for this situation. I don't want to learn C. I understand OOP (I'm getting more familiar with C++ oop aswell), I understand the point of the pointers (and some arithmetic) and references (widely used in Perl).

I don't need manuals for dummies (what is int, bool, double, if, while), I just need a direction how to learn C++ from the perspective of a Perl programmer, because I'm sure that there are many like me.

Thank you in advance.

EDIT: Thank you for all the recommended books and the answers, I will try with "Accelerated C++". I will start from the beginning and try to change my mindflow to C++. I have added the "beginner" tag.

Actually, since you already know an imperative language, learning C won't take you much time at all. The basics are all the same -- if statements, while loops, for loops etc. Even the way the namespaces are organized are similar (although the guts of course are different.) You might want to gloss over some of the pointer handling, as C++ does references a little differently, but you would not be doing yourself any harm by picking up and reading through a copy of K&R (the official C reference) at least once. (Every decent programmer should have a copy on his bookshelf as a reference, anyway.)

After that, pick up a recent edition of Stroustrup and have at it, ensuring that you work through the exercises. Some of the concepts may be a little foreign to a Perl-oriented mind, but it won't be too strange. If you encounter a particular concept you find tricky, post again on SO and there will be lots of people happy to go through it with you!

K&R Stroustrup

I have been learning C++ for three months now and in that time created a number of applications for my company. I consider myself fairly comfortable with C++ / MFC and STL, however I don't just want to be an OK programmer, I want to be a good programmer. I have a few books on best practices but I was wondering if anyone could suggest reading materials that helped them and any disciplines which should be encouraged?


You can check out the Boost library and a number of the books written about it. While this may not have been what you had in mind, IMO, the Boost libraries are examples of well-designed modern C++ libraries that use the features of the language in pretty much the way they should be used to create among the most effective solutions for their problem domain. Granted of course, there are bizarre libraries like preprocessor and MPL which make you wonder if you'll ever have any use for them, but they're all round quite good. From my own experience, exploring the library and its literature has given me insight into how C++ can be used effectively.

Boost Beyond the C++ Standard Library: An Introduction to Boost

For C++, Scott Meyers books are very good, and will help take you to the next level.

If you don't already have it C++ by Bjarne Stroustrup, 3rd Edition

3 months into c++ and you're already comfortable with it? Sheesh, I've been learning c# for over a year and have taken numerous Microsoft courses and I'm nowhere near comfortable with it.

That being said, you'll hear Code Complete tossed about as a very good book. I'm in the process of reading it now.

I lot of folks can suggest more modern, up-to-date books. But I still recommend The Annotated C++ Reference Manual by Margaret A. Ellis & Bjarne Stroustrup.

The ARM was published back in '90. It's become somewhat outdated with respect to templates. STL is (obviously) absent. (Though the website at does a good job of covering STL!)

However, the ARM is dirt cheap (used). (Shipping will exceed the cost of the book.) Its signal-to-noise ratio remains off the scale. It's very good at digging into C++'s dirty areas, explaining what was done & why.

I still use it as a reference. I rank it up there with K&R.

Good blogs: Guru of the Week, and all the books by Herb Sutter. Those will give you quite a lot to chew already.

Modern C++ Design by Alexandrescu if you want to get a good feel for what you don't yet know, and probably don't want to know.

Code Kata's for practice!

As I see, nobody mentioned Bruce Eckel brilliant books "Thinking in C++". IMHO, it`s one of the best books to start your C++ development from. From my point of view, first volume is more helpful that the second, but both of them worth reading.

I've recently started to learn C++ and am completely confused with the choices of IDEs and compilers out there. I am competent with interpreted languages and like the simplicity of using any IDE or text editor and then running the interpreter from the command line. Everything works as I expect, regardless of the IDE used, because I use the same interpreter each time.

Now that I have started learning C++ I am overwhelmed by the choice of different compilers and more importantly, their differences. It seems that things will be simpler for me (not necessarily easier) if, while learning, I use a text editor and a compiler that I run from the command line. I have a basic understanding of how compiling and linking works and I understand the role of header files.

Firstly, are there any books or websites that teach C++ from this approach? (IDE-less) Many books try to point out the differences between IDEs and compilers by selecting two and comparing them, which confuses me.

Secondly, how should I set up my workflow? (Ignore the choice of text editor, I am talking about compilers, linkers etc.) I am struggling to understand what differences different compilers have and so please bear this in mind when answering. It seems like the most popular compilers are g++ and CL. Similar question but I am more interested in why some programs will work with some compilers and not others: C++ Compiler for Windows without IDE?

Further information: I am developing on Windows and from what I understand, it seems that there is 'pure' C++ and then C++ that is somehow related to windows, is this Visual C++? I would like to write programs that make use of Windows features but I want to know when I am using windows features and when I am writting code that would work on any platform.

Update: So it seems that I shouldn't be worrying about compilers when I am just starting out. The reason for me wanting to understand the differences is because I don't want to write code for a specific compiler and get into bad habits. Is this a non-issue?

Firstly, are there any books or websites that teach C++ from this approach? (IDE-less)

Yes, definitely. Stroustrup's book has already been mentioned. For learning C++ I'd also recommend two other books: If you like thorough explanations and don't shy away from 1000 pages, look at Lippman et al. If you rather like a short introduction and don't fear a steep learning curve, look at Koenig/Moo. Both are excellent books. (BTW, a good place to look for good books has always been the book review section at the ACCU.)

As for which tool chain you want to use: If you rather have a standalone editor and invoke the compiler from the command line, you can do this with either GCC or VC. This approach has the advantage that it is more unlikely to lure you into using something proprietary (like C++/CLI). If you would like to try an IDE, VC Express is fine, once you're past setting up a new C++ project. Of course, the number of options you can tweak for a new project can be very overwhelming. But on the other hand you get things like an integrated debugger. Note that there are other integrated solutions, too. The most mature and prominent is probably eclipse.

Edit: If you don't mind spending a little money, look at Comeau. It's not free, but it's not expensive either and it's usually considered to be the most standard-conforming C++ compiler around and has excellent error messages. (You can test-drive it at the website.) Note that it emits C code, though. That means you have to have another compiler to create an executable program. But both GCC and VC Express will do, so there's no other cost. (Note that using VC you will get Dinkumware's std lib implementation, which is also considered to be a very good one.)

I wrote the following function to get a date/time string using boost.date_time.

namespace bpt = boost::posix_time;

get_date_time_string(bpt::ptime time)
  bpt::time_facet * facet(new bpt::time_facet);

  stringstream return_value;
  return_value.imbue(std::locale(std::locale::classic(), facet));
  return_value << time;

  return return_value.str();

I had a quick question about the ownership/delete'ing of the facet object. std::locale's constructor is not explicit on the ownership/delete'ing of the facet. Tried using shared_ptr-wrapped and stack allocated versions of facet - both of which caused seg-faults. Also, running the above function through valgrind didn't show any leaks(which probably implies that the locale or stream is taking care of delete'ing), but I just wanted to be clear that I am doing the right thing here. Thanks.

According to Stroustrup, a 0 argument passed to the constructor tells the facet that the locale will handle destruction, and the both constructors of bpt::time_facet default to 0 when it isn't supplied. A non-zero value, though, implies that the programmer must explicitly handle the destruction of the facet.

Is there any difference between a variable declared as static outside any function between C and C++. I read that static means file scope and the variables will not be accessible outside the file. I also read that in C, global variables are static . So does that mean that global variables in C can not be accessed in another file?

I want to add to Southern Hospitality's answer Static variables in C and C++

the following remarks:

The use of static to indicate "local to translation unit" is deprecated in C++ ( href="" The C++ Programming Language: Special Edition, Appendix B.2.3, Deprecated Features).

You should use unnamed namespaces instead:

static int reply = 42; // deprecated

namespace {
    int reply1 = 42;  // The C++ way

As already said by Southern Hospitality, the order of initialization of global objects is undefined. In that situation, you should consider using the href="", Singleton pattern.

UPDATE: GMan commented my answer:

"The order is defined per-translation unit, ...": This really slipped my mind, so I looked it up in The C++ Programming Language.

In Section 9.4.1, Initialization of Non-local Variables, Prof. Stroustrup suggests that "a function returning a reference is a good alternative to a global variable":

int& use_count()
        static int uc = 0;
        return uc;

"A call to use_count() now acts as a global variable that is initialized at its first use. For example:"

void f()
        std::cout << ++use_count() << '\n';

In my understanding, this is very similar to the Singleton pattern.

GMan commented further: "We need to limit our ability to create these objects to one, and provide global access to it." Does the limiting to one really relate to anything in the problem? We may need one globally, but who's to say we don't want it in other places?"

Some quotes from Singleton(127) (Gamma et al, Design Patterns):

"The Singleton pattern is an improvement over global variables. It avoids polluting the name space with global variables that store sole instances."

"The pattern makes it easy to change your mind and allow more than one instance of the Singleton class."

Singletons are initialized in the order they are first used.

In Herb Sutter, Andrei Alexandrescu, C++ Coding Standards, Item 10 says:

"Avoid shared data, especially global data."

Therefore I use often Singletons to avoid global data. But of course, as everything is overusable, this could be a overuse of the Singleton pattern. (Johshua Kerievsky calls this "Singletonitis" in his book "Refactoring to Patterns".)


(Sorry, but I cannot write comments, therefore this Update.)

Jalf wrote in his comment: "The gang of four were smoking something illegal when they wrote about the singleton pattern."

Obviously, other C++ developers smoked interesting substances, too. For example, Herb Sutter (he served for over a decade as secretary and chair of the ISO C++ standards committee during the development of the second C++ standard, C++0x, and as lead architect of C++/CLI at Microsoft. Herb is currently the designer of the Prism memory model for Microsoft platforms and the Concur extensions to Visual C++ for parallel programming), wrote in C++ Coding Standards, Item 21:

"When you need such a (namespace level) variable that might depend upon another, consider the Singleton design pattern; used carefully, it might avoid implicit dependencies by ensuring that an object is initialized upon first access. Still, Singleton is a global variable in sheep's clothing, and is broken by mutual or cyclic dependencies."

So, avoid global data, if you can. But if you have to use global data in separate translation units, Singleton should be an acceptable solution for enforcing a specific initialization sequence.

Note that in the Java language global data does not even exist. Obviously, global data is substituted/emulated by the use of the Singleton design pattern.

(For I am working in my dayjob with a Java team, I strive for a maximal similarity of my C++ programs with Java programs. E.g, every class is situated in its own source file/translation unit.)

Whenever I follow C++ related IRC channels, I see folk giving each other C++ papers' standard's links to come to a decision on ongoing discussions, since they all boil down to standard, naturally. However, those papers are rather boring and hard to read. How do you manage to read those bloated papers? and Is reading those papers inevitable to learn C++ thoroughly? I have just run into a similar statement in a recent C++ article:

But before you can use its awesome powers, you just have to wrap your mind around one little detail: C++ isn't a programming language; it's a worldwide research project running about in disguise.

Here's the lowdown. Reading compiler manuals will only get you so far. The bulk of C++ is documented in papers, presentations, and (most importantly) the experience of its users.

The definitive resource on C++ is generally considered to be "The C++ Programming Language" by Bjarne Stroustrup. It describes in minute detail the language as well as the STL. It is well worth the read.

While you can learn a language without going to it's original source (Book, specs etc.) it is unlikely you would ever be able to master it.

how can i get C++ documentation, I just came across python's documentation and it was very elaborate. is there anything like that for c++?

I would really suggest reading : The C++ Programming Language: Special Edition by Bjarne Stroustrup since he created the language. The book gives a lot of details on the design decisions that went into the language. It also makes a great reference after you learn the language.

alt text

Amazon link to book

Here is the newest book on Amazon with x11

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.

I have two namespaces that each have a function with the same name. If from one of the namespaces I want to call the function that matches the best. From a function in NamespaceA, if I call MyFunction(...), of course it uses the one in NamespaceA. However, if I add a 'using NamespaceB::MyFunction', I would then expect the behavior I described. However, what I actually see is that it ALWAYS finds the NamespaceB function, even though I am in NamespaceA. HOWEVER, if I ALSO add a using::NamespaceA (even though I am already in NamespaceA), it works as I'd expect. A demonstration is below. Can anyone explain how this works?

#include <iostream>

namespace NamespaceA
  void DoSomething();
  void MyFunction(int object);

namespace NamespaceB
  void MyFunction(float object);

namespace NamespaceA
  void DoSomething()
    using NamespaceA::MyFunction; // Note that without this line the lookup always fins the NamespaceB::MyFunction!
    using NamespaceB::MyFunction;


  void MyFunction(int object)
    std::cout << "int: " << object << std::endl;

namespace NamespaceB
  void MyFunction(float object)
    std::cout << "float: " << object << std::endl;

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

  return 0;

Short answer: Local defined name and the name declared by a using-declaration hides nonlocal names.

Detailed answer:

Your question is very interesting. I didn't open standarts of C++98,03,11 for that question, but open Bjarne Stroustrup's book

Namespace - is a named scope. Verbosity can be eliminated using two techniques:

  • create synonymous with using NS :: x; (using-declaration)
  • create synonymous for all the variables with using namespace NS :: x; (using-directive)

The answer to your question is here:

Appendix B 10.1
local definitions, and names defined with using-declaration hides 
the name of a non-local definitions.

Bonus with opposite situation:

Also if you

using NamespaceA::MyFunction;
using NamespaceB::MyFunction;

change to

using namespace NamespaceB;

Then you due to text below get situation with call only void MyFunction(int object)
Names explicitly declared in namespace (also made with using declaration)
have priority over the names made available by using directives

Extra code to play with:

#include <iostream>

// var in global namespace
const char* one = "G_one";

// vars in named namespace
namespace NS1 {
    const char* one = "NS1_one";
    const char* two = "NS1_two";
    const char* three = "NS1_three";

namespace NS2 {
    const char* one = "NS2_one";
    const char* two = "NS2_two";
    const char* three = "NS2_three";

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

    using namespace NS1;       // using-directive
    using namespace NS2;       // using-directive

    // const char* two = "L_two"; // local namespace
    using NS2::two;               // using-declaration

    // C++ rules
    // Local names and names with using-declarations
    // takes precedence over the name of the NS     
    std::cout << "two: " << two << std::endl;

    //std::cout << "three: " << three << std::endl; // ambiguous symbol

    // But the name in global-namespace does not have priority over imported name from namespace
    //std::cout << "one: " << one << std::endl; // ambiguous symbol. Because wGlobal names does not have priority over
    return 0;

Is there a canonical or recommended pattern for implementing arithmetic operator overloading in C++ number-like classes?

From the C++ FAQ, we have an exception-safe assignment operator that avoids most problems:

class NumberImpl;

class Number {
   NumberImpl *Impl;


Number& Number::operator=(const Number &rhs)
   NumberImpl* tmp = new NumberImpl(*rhs.Impl);
   delete Impl;
   Impl = tmp;
   return *this;

But for other operators (+, +=, etc..) very little advice is given other than to make them behave like the operators on built-in types.

Is there a standard way of defining these? This is what I've come up with - are there pitfalls I'm not seeing?

// Member operator
Number& Number::operator+= (const Number &rhs)
    Impl->Value += rhs.Impl->Value; // Obviously this is more complicated
    return *this;

// Non-member non-friend addition operator
Number operator+(Number lhs, const Number &rhs)
     return lhs += rhs;

In Bjarne Stroustrup's book "The C++ Programming Language", in chapter 11 (the one devoted to Operator Overloading) he goes through witting a class for a complex number type (section 11.3).

One thing I do notice from that section is that he implements mixed type operations... this is probably expected for any numeric class.

In general, what you've got looks good.

I haven't used C++ since college. Even though I've wanted to I haven't needed to do any until I started wanting to write plugins for Launchy. Is there a good book to read to get back into it? My experience since college is mainly C# and recently ruby. I bought some book for C# developers and it ended up being on how to write C++ with CLI. While a good book it wasn't quite what I was looking for.

The C++ Programming Language by Bjarne Stroustrup covers C++ in depth. Bjarne is the inventor of C++. It also provides insights into why the language is the way it is. Some people find the book a little terse. I found it to be an enjoyable read. If you have done some C++ before it's a great place to start. It is by no means a beginners book on C++.

I need to read "A Practical Introduction to Data Structures and Algorithm Analysis" by Shaffer for class but the code examples in the book are all in C++ which I do not know. I know C and Java already and was wondering if you knew any resources that helped learn enough C++ to understand these examples fast if you already know another language. Thanks!

This is quite a textbook (and quite expensive, so see if your library has it), but I would recommend the man's book itself, the C++ Programming Language linky. I used it to enhance, rather than create, my understanding of C++, but I used it in the form of a dictionary, and it seemed to work out well. It is written for people comfortable with programming, and you've gotten the pointers AND the OO stuff down, so it may mesh well.

For example... Chapter 2, a Tour of C++ (as I have it open in my lap now), talks about a large number of things, many of which compare themselves to the "C" way of doing things. The things are not new to a Java programmer, but different syntax, etc. Basically, if you want to learn about C++ iterators, look up the iterators chapter, etc.

I think you'll do ok without necessarily needing a book, but C++ has ridiculously tricky syntax, (try figuring out how to assign a constant field in an object instance using the constructor, for example) and I found the book to be quite illuminating. Thankfully, there's a pretty nifty index including operators, which is quite helpful.

Lastly, if you want to be a guru (which I certainly am not), there are discussions about everything from "Exception-Safe implementation techniques" (Appendix E.3) to philosophy of developing large software projects.

So I've given you quite the advertisement (I've never met the guy, honest), but I've found the book to be quite useful.

I'd recommend taking a look through C++ Primer Plus (5th Edition). What you probably need to get your head around is the syntax for:

  • the type system
  • templates
  • operator overloading

The basic syntax of C++ is usually fairly easy to get a hold of, however, C++ is a complex multi-paradigm language, which requires some serious study to use it effectively.

C++ Primer Plus (5th Edition)

In the example below, what exactally is the << operator doing? I'm guessing it is not a bitwise operator.

std::cout << "Mouse down @ " << event.getPos() << std::endl;

I understand what the code will do here: Use standard out, send this text, send an end of line. Just I've never come accross the use of this << apart from on raw binary.

I'm starting out with C++. And, as an operator of sorts, it's hard to search for a description of this and what it means. Can someone enlighten me and/or give me a pointer as to what to google for?

Thanks Ross

The answer is: The << operator does left shifts by default for integral types, but it can be overloaded to do whatever you want it to!

This syntax for piping strings into a stream was first (I think) demonstrated in C++ inventor Bjarne Stroustroup's eponymous book The C++ Programming Language. Personally, I feel that redefining an operator to do IO is gimmicky; it makes for cool-looking demo code but doesn't contribute to making code understandable. Operator overloading as a technique has been widely criticized in the programming language community.

EDIT: Since nobody else has mentioned this yet:

operator<< is defined in the ostream class, of which cout is an instance. The class definition sits in the iostream library, which is #include'd as <iostream>.

Or does it?

Should an object-oriented design use a language construct that exposes member data by default, if there is an equally useful construct that properly hides data members?

EDIT: One of the responders mentioned that if there's no invariant one can use a struct. That's an interesting observation: a struct is a data structure, i.e. it contains related data. If the data members in a struct are related isn't there's always an invariant?

See these similar questions:

When should you use a class vs a struct in C++?

What are the differences between struct and class in C++


According to Stroustrup in the C++ Programming Language:

Which style you use depends on circumstances and taste. I usually prefer to use struct for classes that have all data public. I think of such classes as "not quite proper types, just data structures."

1) I checked out the C++ recommended reading list. I'm probably still a beginner. So, would I still start with a beginner book, and go from there? And, do you recommend reading one book for each level, or all of the books in one level before moving up?

Obviously, I can only start on one book. Which one should I begin with?

2) What kind of projects could I do in my spare time to practice and improve upon my skills?

I'm particularly interested in designed web applications. Is that possible as a beginner? Examples would be great.

1: I'd say find a good beginner book and read/work through it, then a more in depth one. The O'Reilly "Learning" books are good beginner-reads in my experience (the C++ In A Nutshell maybe for those with prior programming experience), and Bjarne's book (The C++ Programming Language) is probably a good choice for a not-quite-so-beginner but not deep magic book.

2: When I learn a new programming language I like to write copies of common Unix/Linux commands I use (wc, grep, sort, etc). This allows me to learn control structures, file and console I/O, and other necessities within the context of always having the original version to compare my results with. I don't program on Windows machines, but I'm sure there are some comparable commands, or you could use the ones in Cygwin.

1) I am assuming that when you say you're a beginner, you mean a beginner in programming in general. You may want to look at Bjarne's Stroustrup's new book:

Programming: Principles and Practice using C++

alt text

This book is very pedagogical and assumes essentially zero background. I would recommend doing a large fraction of the exercises as you go along.

See also Stroustrup's page on the book.

2) Another introductory C++ book that is written for those with minimal background in programming is Francis Glassborrow's:

You Can Do It!: A Beginners Introduction to Computer Programmin

3) If you have a solid background in another modern programming language then (as mentioned in the relevant SO question) Andrew Koenig and Barbara Moo's:

Accelerated C++

is definitely a great choice for you. Once again, work through most of the exercises.

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.

So a pretty simple question, but I can't seem to find a general rule of choosing one over the other in some cases.

Let's say I have a simple Point class, like this:

class Point
    Point(double, double, double);

    Point(const Point& other);
    Point& operator=(const Point& other);

    bool operator==(Point& lhs, Point& rhs);

    void translate(double, double, double);

    double getX() const;
    double getY() const;    
    double getZ() const;

    void setX(const double);
    void setY(const double);
    void setZ(const double);

    double x_, y_, z_;

All well, but why not make it a struct with public x, y, z and save half of the code?

Another example lets say I have a Header struct like this:

struct Header
    short int id;
    short int version;        
    size_t indexOffset;
    size_t indexSize;

Under what circumstances I'd want to make it a class? Also is there any difference between the above and something I've also seen in a quality code like this:

class Header
    short int id;
    short int version;        
    size_t indexOffset;
    size_t indexSize;

So I guess a sub-question to this is how do I decide when to make member variables private. I know OO purists will probably say always, but I'm not sure about the benefit.

Many thanks.

Thanks to the link provided by Bo Persson I've found the following to be a relevant answer:

The members and base classes of a struct are public by default, while in class, they default to private. Note: you should make your base classes explicitly public, private, or protected, rather than relying on the defaults.

struct and class are otherwise functionally equivalent.

OK, enough of that squeaky clean techno talk. Emotionally, most developers make a strong distinction between a class and a struct. A struct simply feels like an open pile of bits with very little in the way of encapsulation or functionality. A class feels like a living and responsible member of society with intelligent services, a strong encapsulation barrier, and a well defined interface. Since that's the connotation most people already have, you should probably use the struct keyword if you have a class that has very few methods and has public data (such things do exist in well designed systems!), but otherwise you should probably use the class keyword.


Which style you use depends on circumstances and taste. I usually prefer to use struct for classes that have all data public. I think of such classes as "not quite proper types, just data structures.


Some background: My job involves maintaining a large multi-threaded multi-process C++ / C# application, and so I'm often tasked with understanding access violations, memory leaks, heap curruption issues and the like.

I quite enjoy this, and I've amassed quite a good understanding of various low level concepts, but the trouble is that I don't program in C++, and aside for the purposes of maintenance I don't really intend to.

What I mean by that is that if I ever need to develop something then at the company I work at the best choice is C# (more developers, other apps also in C# means better interops), so its not that I don't program in C++, it's just that whenever I do program in C++ it will be purely for the purpose of learning C++, and so I want to get the most out of it.

My view is that "Teach yourself C++" books and the like aren't very suitable as they focus too much on getting things done - there are usually many ways of doing things and so they tend to pick one method, so when I'm presented with some code that does things a different way I'm stuffed (e.g. a book teaches MFC, I then get presented with some ATL code and the book hasn't even taught me what ATL and MFC are, let alone how to recognise that what I'm looking at is different!)

I'm really looking for teach yourself C++, with the emphasis on understanding other peoples code.

It sounds like you really need a copy of the C++ standard. (ISO/IEC 14882 - available in draft form for free online. the final version costs a few bucks)

Of course, Stroustrup's book would be a good choice too. But in general, focus on material that describes the language, rather than, as you say, "how to get things done".

This is my first program I really created besides hello world. The code is over 400 lines of code and wanted to know of new functions and what not that would help improve my code and my knowledge of C++. I figured I would just dive in and learn on my own instead of out of the book I have "Teach yourself C++ in one hour a day 6th edition".

What are some new functions I can learn that would improve my code?

// Runescape Mining Calculator

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

int main()
    int lvl;
    int exp;
    int result;

    cout << " \t\t\tRunescape Skill Calculator" << endl;
    cout << " Enter Target level: ";

                    case 2: cout << " What is your current experience? ";;
                    cin >> exp;
                    result=83 - exp;
                    case 3: cout << " What is your current experience? ";
                    cin >> exp;
                    result=174 - exp;
                    case 4: cout << " What is your current experience? ";
                    cin >> exp;
                    result=276 - exp;
                    case 5: cout << " What is your current experience? ";
                    cin >> exp;
                    result=388 - exp;
                    case 6: cout << " What is your current experience? ";
                    cin >> exp;
                    result=512 - exp;
                    case 7: cout << " What is your current experience? ";
                    cin >> exp;
                    result=650 - exp;
                    case 8: cout << " What is your current experience? ";
                    cin >> exp;
                    result=801 - exp;
                    case 9: cout << " What is your current experience? ";
                    cin >> exp;
                    result=969 - exp;
                    case 10: cout << " What is your current experience? ";
                    cin >> exp;
                    result=1154 - exp;
                    case 11: cout << " What is your current experience? ";
                    cin >> exp;
                    result=1358 - exp;
                    case 12: cout << " What is your current experience? ";
                    cin >> exp;
                    result=1584 - exp;
                    case 13: cout << " What is your current experience? ";
                    cin >> exp;
                    result=1833 - exp;
                    case 14: cout << " What is your current experience? ";
                    cin >> exp;
                    result=2107 - exp;
                    case 15: cout << " What is your current experience? ";
                    cin >> exp;
                    result=2411 - exp;
                    case 16: cout << " What is your current experience? ";
                    cin >> exp;
                    result=2746 - exp;
                    case 17: cout << " What is your current experience? ";
                    cin >> exp;
                    result=3115 - exp;
                    case 18: cout << " What is your current experience? ";
                    cin >> exp;
                    result=3523 - exp;
                    case 19: cout << " What is your current experience? ";
                    cin >> exp;
                    result=3973 - exp;
                    case 20: cout << " What is your current experience? ";
                    cin >> exp;
                    result=4470 - exp;
                    case 21: cout << " What is your current experience? ";
                    cin >> exp;
                    result=5018 - exp;
                    case 22: cout << " What is your current experience? ";
                    cin >> exp;
                    result=5624 - exp;
                    case 23: cout << " What is your current experience? ";
                    cin >> exp;
                    result=6291 - exp;
                    case 24: cout << " What is your current experience? ";
                    cin >> exp;
                    result=7028 - exp;
                    case 25: cout << " What is your current experience? ";
                    cin >> exp;
                    result=7842 - exp;
                        case 26: cout << " What is your current experience? ";
                    cin >> exp;
                    result=8740 - exp;
                    case 27: cout << " What is your current experience? ";
                    cin >> exp;
                    result=9730 - exp;
                    case 28: cout << " What is your current experience? ";
                    cin >> exp;
                    result=10824 - exp;
                    case 29: cout << " What is your current experience? ";
                    cin >> exp;
                    result=12031 - exp;
                    case 30: cout << " What is your current experience? ";
                    cin >> exp;
                    result=13363 - exp;
                    case 31: cout << " What is your current experience? ";
                    cin >> exp;
                    result=14833 - exp;
                    case 32: cout << " What is your current experience? ";
                    cin >> exp;
                    result=16456 - exp;
                    case 33: cout << " What is your current experience? ";
                    cin >> exp;
                    result=18247 - exp;
                    case 34: cout << " What is your current experience? ";
                    cin >> exp;
                    result=20224 - exp;
                    case 35: cout << " What is your current experience? ";
                    cin >> exp;
                    result=22406 - exp;
                    case 36: cout << " What is your current experience? ";
                    cin >> exp;
                    result=24815 - exp;
                    case 37: cout << " What is your current experience? ";
                    cin >> exp;
                    result=27473 - exp;
                    case 38: cout << " What is your current experience? ";
                    cin >> exp;
                    result=30408 - exp;
                    case 39: cout << " What is your current experience? ";
                    cin >> exp;
                    result=33648 - exp;
                    case 40: cout << " What is your current experience? ";
                    cin >> exp;
                    result=37224 - exp;
                    case 41: cout << " What is your current experience? ";
                    cin >> exp;
                    result=41171 - exp;
                    case 42: cout << " What is your current experience? ";
                    cin >> exp;
                    result=45529 - exp;
                    case 43: cout << " What is your current experience? ";
                    cin >> exp;
                    result=50339- exp;
                    case 44: cout << " What is your current experience? ";
                    cin >> exp;
                    result=55649 - exp;
                    case 45: cout << " What is your current experience? ";
                    cin >> exp;
                    result=61512 - exp;
                    case 46: cout << " What is your current experience? ";
                    cin >> exp;
                    result=67983 - exp;
                    case 47: cout << " What is your current experience? ";
                    cin >> exp;
                    result=75127 - exp;
                    case 48: cout << " What is your current experience? ";
                    cin >> exp;
                    result=83014 - exp;
                    case 49: cout << " What is your current experience? ";
                    cin >> exp;
                    result=91721 - exp;
                    case 50: cout << " What is your current experience? ";
                    cin >> exp;
                    result=101333 - exp;
                    case 51: cout << " What is your current experience? ";
                    cin >> exp;
                    result=111945 - exp;
                    case 52: cout << " What is your current experience? ";
                    cin >> exp;
                    result=123660 - exp;
                    case 53: cout << " What is your current experience? ";
                    cin >> exp;
                    result=136594 - exp;
                    case 54: cout << " What is your current experience? ";
                    cin >> exp;
                    result=150872 - exp;
                    case 55: cout << " What is your current experience? ";
                    cin >> exp;
                    result=166636 - exp;
                    case 56: cout << " What is your current experience? ";
                    cin >> exp;
                    result=184040 - exp;
                    case 57: cout << " What is your current experience? ";
                    cin >> exp;
                    result=203254 - exp;
                    case 58: cout << " What is your current experience? ";
                    cin >> exp;
                    result=224466 - exp;
                    case 59: cout << " What is your current experience? ";
                    cin >> exp;
                    result=247886 - exp;
                    case 60: cout << " What is your current experience? ";
                    cin >> exp;
                    result=273742 - exp;
                    case 61: cout << " What is your current experience? ";
                    cin >> exp;
                    result=302288 - exp;
                    case 62: cout << " What is your current experience? ";
                    cin >> exp;
                    result=333804 - exp;
                    case 63: cout << " What is your current experience? ";
                    cin >> exp;
                    result=368599 - exp;
                    case 64: cout << " What is your current experience? ";
                    cin >> exp;
                    result=407015 - exp;
                    case 65: cout << " What is your current experience? ";
                    cin >> exp;
                    result=449428 - exp;
                    case 66: cout << " What is your current experience? ";
                    cin >> exp;
                    result=496254 - exp;
                    case 67: cout << " What is your current experience? ";
                    cin >> exp;
                    result=547953 - exp;
                    case 68: cout << " What is your current experience? ";
                    cin >> exp;
                    result=605032 - exp;
                    case 69: cout << " What is your current experience? ";
                    cin >> exp;
                    result=668051 - exp;
                    case 70: cout << " What is your current experience? ";
                    cin >> exp;
                    result=737627 - exp;
                    case 71: cout << " What is your current experience? ";
                    cin >> exp;
                    result=814445 - exp;
                    case 72: cout << " What is your current experience? ";
                    cin >> exp;
                    result=899257 - exp;
                    case 73: cout << " What is your current experience? ";
                    cin >> exp;
                    result=992895 - exp;
                    case 74: cout << " What is your current experience? ";
                    cin >> exp;
                    result=1096278 - exp;
                    case 75: cout << " What is your current experience? ";
                    cin >> exp;
                    result=1210421 - exp;
                    case 76: cout << " What is your current experience? ";
                    cin >> exp;
                    result=1336443 - exp;
                    case 77: cout << " What is your current experience? ";
                    cin >> exp;
                    result=1475581 - exp;
                    case 78: cout << " What is your current experience? ";
                    cin >> exp;
                    result=1629200 - exp;
                    case 79: cout << " What is your current experience? ";
                    cin >> exp;
                    result=1798808 - exp;
                    case 80: cout << " What is your current experience? ";
                    cin >> exp;
                    result=1986068 - exp;
                    case 81: cout << " What is your current experience? ";
                    cin >> exp;
                    result=2192818 - exp;
                    case 82: cout << " What is your current experience? ";
                    cin >> exp;
                    result=2421087 - exp;
                    case 83: cout << " What is your current experience? ";
                    cin >> exp;
                    result=2673114 - exp;
                    case 84: cout << " What is your current experience? ";
                    cin >> exp;
                    result=2951373 - exp;
                    case 85: cout << " What is your current experience? ";
                    cin >> exp;
                    result=3258594 - exp;
                    case 86: cout << " What is your current experience? ";
                    cin >> exp;
                    result=3597792 - exp;
                    case 87: cout << " What is your current experience? ";
                    cin >> exp;
                    result=3972294 - exp;
                    case 88: cout << " What is your current experience? ";
                    cin >> exp;
                    result=4385776 - exp;
                    case 89: cout << " What is your current experience? ";
                    cin >> exp;
                    result=4842295 - exp;
                    case 90: cout << " What is your current experience? ";
                    cin >> exp;
                    result=5346332 - exp;
                    case 91: cout << " What is your current experience? ";
                    cin >> exp;
                    result=5902831 - exp;
                    case 92: cout << " What is your current experience? ";
                    cin >> exp;
                    result=6517253 - exp;
                    case 93: cout << " What is your current experience? ";
                    cin >> exp;
                    result=7195629 - exp;
                    case 94: cout << " What is your current experience? ";
                    cin >> exp;
                    result=7944614 - exp;
                    case 95: cout << " What is your current experience? ";
                    cin >> exp;
                    result=8771558 - exp;
                    case 96: cout << " What is your current experience? ";
                    cin >> exp;
                    result=9684577 - exp;
                    case 97: cout << " What is your current experience? ";
                    cin >> exp;
                    result=10692629 - exp;
                    case 98: cout << " What is your current experience? ";
                    cin >> exp;
                    result=11805606 - exp;
                    case 99: cout << " What is your current experience? ";
                    cin >> exp;
                    result=13034431 - exp;
                    case 100: cout << " What is your current experience? " <<endl;
                    cin >> exp;
                    result=14391160 - exp;
                    default: exit(0);
                    cout << " Experience Needed: " << result  << endl;
// Ores needed to be mined to acquire the level up.
                    cout << " Rune Essence: " << ceil(result/5.0) << endl;
                    cout << " Clay: " << ceil(result/5.0) << endl;
                    cout << " Copper: " << ceil(result/17.5) << endl;
                    cout << " Tin: " << ceil(result/17.5) << endl;
                    cout << " Bluerite: " << ceil(result/17.5) << endl;
                    cout << " Iron: " << ceil(result/35.0) << endl;
                    cout << " Silver: " << ceil(result/40.0) << endl;
                    cout << " Coal: " << ceil(result/50.0) << endl;
                    cout << " Gold: " << ceil(result/65.0) << endl;
                    cout << " Mithril: " << ceil(result/80.0) << endl;
                    cout << " Adamant: " << ceil(result/ 95.0) << endl;
                    cout << " Runite: " << ceil(result/125.0) << endl;
                    cout << endl << endl << endl << "\t\t\tCreated by USDblades" << endl;
         return 0;

Edit: Sorry was not clear. I am trying to improve the code for the Runescape Skill Calculator I am working on. I am curious if I could have cut out some lines of code by using different functions. The Code provided is my project I am working on. Can you review it and give me pointers?

There is hardly a way without reading anything.

Language reference:


I like this one a lot but it's probably not the first step:

This is the unbelievable book but its content borders with insanity at some point :)

Possible Duplicate:
What's the difference between new char[10] and new char(10)

what is different between

char* t1=new char


char* t2=new char[10];

both allocate memory and t1[100]='m' and t2[100]='m' is correct for them

-----------after edit:

but why we can use t1[100] if t1 is dynamically allocated char not array of char

Your first case creates a single char element (1 byte) whereas your second case creates 10 consecutive char elements (10 bytes). However, your access of t(x)[100]='m' is undefined in both cases. That is, you are requesting 100 bytes after the position of the pointer, which is most likely garbage data.

In other words, your assignment of 'm' will overwrite whatever is already there, which could be data from another array. Thus, you may encounter some bizarre errors during runtime.

C/C++ allows programmers to access arrays out of bounds because an array is really just a pointer to consecutive memory. The convention t1[100] is just 100 bytes after the pointer, no matter what that is.

If you want "safe" arrays, use the vector class and invoke the at() function. This will throw the out_of_range exception if the access is invalid.

Stroustrup gives the following example:

template<class T> class Vec : public vector<T> {
    Vec() : vector<T>() {}
    Vec(int s) : vector<T>(s) {}

    T& operator[] (int i) {return at(i);}
    const T& operator[] (int i) const {return at(i);}

This class is boundary-safe. I can use it like this:

Vec<char> t3(10);                // vector of 10 char elements
try {
    char t = t3[100];            // access something we shouldn't
catch (out_of_range) {
    cerr << "Error!" << endl;    // now we can't shoot ourselves in the foot

I came across this presentation while browsing SO some time ago, and it relates performance to specific memory allocation decisions. The author has some interesting diagrams that show how various objects are allocated by a C++ program, and goes on to optimise the program by making some changes in the code. His diagrams make sense in their own context, but I'd like to know more about how to draw my own.

Where can I learn more about how C++ allocates objects in memory? I would like to know how various structures (arrays, pointers, ints, etc...) are placed when I write a program, in detail. Related to this are pre-caching techniques such as _dcbt, which sound interesting as well.

I recommand you the ultimate learning book of the C++ language:

C++ Programming Language, by Bjarne Stroustrup, the father of C++ language

You should have no problem finding any number of sites with information on C++ memory allocation. Here is a small sample from a quick Google search:

Here are a couple of books that might be of interest to you as well:

If you want to read the "source" of a language in C you go to C Programming Language by Kernighan; Ritchie; 0131103628

And in Java you read Goslings The Java(tm) Language Specification; 0321246780

But what do you read if you want to read a good book about the "specs" on C++ and C#?

C++: Stroustrup's book and/or Stroustrup's D&E or Stroustrups ARM though the latter two are not in date. The ISO spec is available (see Charles bailey's answer) and is the final word if that's the type of doc you want. The most thorough answer is in the comments by aJ :- The Definitive C++ Book Guide and List. The equivalent of K&R for C++ is the first one.

C#: The C# Programming Language (3rd Edition) by Anders Hejlsberg, Mads Torgersen, Scott Wiltamuth, and Peter Golde). If you're looking for the generally accepted definitive book on C#, that's C# in depth.

I have following code

 //in main
 int x;
 while ( cin>>x ){
        // code goes here

Now,i know that this loop executes untill read to x fails which occurs when type mismatch occurs
So pressing a char lets me to come out of loop as x is of type int and char will not be read from input stream.
But problem is with whitespaces, as they are also not int so why loop does not ends when i press enter or whitespace?

According to The C++ Programming Language Special Edition, $21.9 Advice [5]:

Remember that by default >> skips whitespace; §21.3.2.

And in $21.3.2:

Whitespace is defined as the standard C whitespace (blank, tab, newline, formfeed, and carriage return) by a call to isspace() as defined in (§20.4.2).

I am currenlty trying to grasp the concept of multiple virtual/non-virtual inheritance in c++. if I understand correctly if a class B and C inherit virtually from class A, they share a kind of singleton object i.e. they both access same fields of one common object A. Multiple inheritance would create separate A objects for any B and C object.

Taking above into consideration, would anyone be so kind and present it in a simple, practical context? Why mutiple inheritance in the first place and then why virtual/non-virtual?


Multiple inheritance is not often used in C++. In most cases it's a mixin of interface / implementation. It's not forbidden, also. The need for (virtual) multiple inheritance comes from design decisions to derive from one general base class:

class Window 
{ /* draw, show, hide, background ... */ };

class WindowWithBorder : public virtual Window 
{ /* methods to manipulate / draw border ... */ };

class WindowWithMenu : public virtual Window
{ /* methods to manipulate / draw Menu ... */ };

class MyWindow : public WindowWithBorder, public WindowWithMenu
{ /* now it's your turn ... */ };

Those diamond-shaped inheritance graphs must be foreseen by the library implementer. Without virtual there would be two base Window objects, with virtual it's only one, but not a singleton, since there can be many windows.

Libraries can often (but not in every case) avoid such situations, e.g. by implementing a composite design pattern, having a "fat" base class, by implementing abstract interface classes, or by using templates with traits / policies.

I would recommend to read the chapter on class hierarchies in Bjarne Stroustrup's The C++ Programming language (ch. 15 in my 3rd edition, I borrowed the example from).

If I'd like to know how a function written in like standard C++ library work (not just the MSDN description). I mean how does it allocate, manage, deallocate memory and return you the result. where or what do you need to know to understand that?

You need to know the techniques used to write C++ libraries. Getting Bjarne Stroustrup's book is a good start. Also, SGI has very detailed documentation on the STL at a suitably high level of abstraction.

If you are going to be investigating the windows based stuff you might want to study the systems part of the windows library.

To complement windows: understanding the Posix specification is also important.

I haven't this book, but according to its description, includes

-Practical techniques for using and implementing the component

Isn't this what you want?

I would like to learn about streams in C++. I have done some googling and searching on Amazon and have not had any success in finding a book/web resource on this topic. Any suggestions would be much appreciated! I have found some information on sites like cplusplus and forums, but I'm still still unclear about a number of issues. I would really like a clear, comprehensive resource.

One thing that I would like to do is get input for my programs from external files.

Thank you for any suggestions.

I don't know of a book that deals with streams as its major subject. I'm sure you can find a lot of resources on the Internet, but judging their quality may be difficult. The following two books have rather good coverage of streams and might be work looking into. Of course they cover a lot more than just streams.

Just what the title says, "What is the technical definition of dynamic storage in C++?" I'm curious as to how to discuss dynamic memory allocation on the heap without making any mistakes in my explanation.

From the The C++ Programming Language: Special Edition

Free store, from which memory for objects is explicitly requested by the program and where a program can free memory again once it is done with it (using new and delete ). When a program needs more free store, new requests it from the operating system. Typically, the free store (also called dynamic memory or the heap) grows throughout the lifetime of a program because no memory is ever returned to the operating system for use by other programs.