Pangram verdict · v3.3
We believe that this document is fully human-written
AI likelihood · overall
HumanArticle text · 1,839 words · 5 segments analyzed
home | C++ | FAQ | technical FAQ | publications | WG21 papers | TC++PL | Tour++ | Programming | D&E | bio | interviews | videos | quotes | applications | guidelines | compilers Bjarne Stroustrup's C++ Style and Technique FAQ Modified February 26, 2022 These are questions about C++ Style and Technique that people ask me often. If you have better questions or comments on the answers, feel free to email me (bs at cs dot tamu dot edu). Please remember that I can't spend all of my time improving my homepages. I have contributed to the new, unified, isocpp.org C++ FAQ maintained by The C++ Foundation of which I am a director. The maintenance of this FAQ is likely to become increasingly sporadic. Also, the C++ Core Guidelines contains a large set of maintained guidelines for the use of modern C++. For more general questions, see my general FAQ. For terminology and concepts, see my C++ glossary. Please note that these are just a collection of questions and answers. They are not a substitute for a carefully selected sequence of examples and explanations as you would find in a good textbook. Nor do they offer detailed and precise specifications as you would find in a reference manual or the standard. See The Design and Evolution of C++ for questions related to the design of C++. See The C++ Programming Language for questions about the use of C++ and its standard library. Translations: Chinese of some of this Q&A with annotations another Chinese version Hungarian Japanese Ukrainian Russian Topics: Getting started Classes Hierarchy Templates and generic programming Memory Exceptions Other language features Trivia and style Getting started: How do I write this very simple program? Can you recommend a coding standard? How do I read a string from input? How do I convert an integer to a string? Classes: How are C++ objects laid out in memory? Why is "this" not a reference? Why is the size of an empty class not zero? How do I define an in-class constant? Why isn't the destructor called at the end of scope? Does "friend" violate encapsulation? Why doesn't my constructor work right? Class hierarchies: Why do my compiles take so long? Why do I have to put the data in my class declarations? Why are member functions not virtual by default? Why don't we have virtual constructors? Why are destructors not virtual by default?
What is a pure virtual function? Why doesn't C++ have a final keyword? Can I call a virtual function from a constructor? Can I stop people deriving from my class? Why doesn't C++ have a universal class Object? Do we really need multiple inheritance? Why doesn't overloading work for derived classes? Can I use "new" just as in Java? Templates and generic programming: Why can't I define constraints for my template parameters? Why can't I assign a vector<Apple> to a vector<Fruit>? Is "generics" what templates should have been? why use sort() when we have "good old qsort()"? What is a function object? What is an auto_ptr and why isn't there an auto_array? Why doesn't C++ provide heterogenous containers? Why are the standard containers so slow? Memory: How do I deal with memory leaks? Why doesn't C++ have an equivalent to realloc()? What is the difference between new and malloc()? Can I mix C-style and C++ style allocation and deallocation? Why must I use a cast to convert from void*? Is there a "placement delete"? Why doesn't delete zero out its operand? What's wrong with arrays? Exceptions: Why use exceptions? How do I use exceptions? Why can't I resume after catching an exception? Why doesn't C++ provide a "finally" construct? Can I throw an exception from a constructor? From a destructor? What shouldn't I use exceptions for? Other language features: Can I write "void main()"? Why can't I overload dot, ::, sizeof, etc.? Can I define my own operators? How do I call a C function from C++? How do I call a C++ function from C? Why does C++ have both pointers and references? Should I use NULL or 0? What's the value of i++ + i++? Why are some things left undefined in C++? What good is static_cast? So, what's wrong with using macros? Trivia and style: How do you pronounce "cout"? How do you pronounce "char"? Is ``int* p;'' right or is ``int *p;'' right? Which layout style is best for my code? How do you name variables? Do you recommend "Hungarian"? Should I use call-by-value or call-by-reference?
Should I put "const" before or after the type? How do I write this very simple program? Often, especially at the start of semesters, I get a lot of questions about how to write very simple programs. Typically, the problem to be solved is to read in a few numbers, do something with them, and write out an answer. Here is a sample program that does that: #include<iostream> #include<vector> #include<algorithm> using namespace std; int main() { vector<double> v; double d; while(cin>>d) v.push_back(d); // read elements if (!cin.eof()) { // check if input failed cerr << "format error\n"; return 1; // error return } cout << "read " << v.size() << " elements\n"; reverse(v.begin(),v.end()); cout << "elements in reverse order:\n"; for (int i = 0; i<v.size(); ++i) cout << v[i] << '\n'; return 0; // success return } Here are a few observations about this program: This is a Standard ISO C++ program using the standard library. Standard library facilities are declared in namespace std in headers without a .h suffix. If you want to compile this on a Windows machine, you need to compile it as a "console application". Remember to give your source file the .cpp suffix or the compiler might think that it is C (not C++) source. Yes, main() returns an int. Reading into a standard vector guarantees that you don't overflow some arbitrary buffer. Reading into an array without making a "silly error" is beyond the ability of complete novices - by the time you get that right, you are no longer a complete novice. If you doubt this claim, I suggest you read my paper "Learning Standard C++ as a New Language", which you can download from my publications list. The !cin.eof() is a test of the stream's format. Specifically, it tests whether the loop ended by finding end-of-file (if not, you didn't get input of the expected type/format). For more information, look up "stream state" in your C++ textbook. A vector knows its size, so I don't have to count elements.
Yes, I know that I could declare i to be a vector<double>::size_type rather than plain int to quiet warnings from some hyper-suspicious compilers, but in this case,I consider that too pedantic and distracting. This program contains no explicit memory management, and it does not leak memory. A vector keeps track of the memory it uses to store its elements. When a vector needs more memory for elements, it allocates more; when a vector goes out of scope, it frees that memory. Therefore, the user need not be concerned with the allocation and deallocation of memory for vector elements. for reading in strings, see How do I read a string from input?. The program ends reading input when it sees "end of file". If you run the program from the keybord on a Unix machine "end of file" is Ctrl-D. If you are on a Windows machine that because of a bug doesn't recognize an end-of-file character, you might prefer this slightly more complicated version of the program that terminates input with the word "end": #include<iostream> #include<vector> #include<algorithm> #include<string> using namespace std; int main() { vector<double> v; double d; while(cin>>d) v.push_back(d); // read elements if (!cin.eof()) { // check if input failed cin.clear(); // clear error state string s; cin >> s; // look for terminator string if (s != "end") { cerr << "format error\n"; return 1; // error return } } cout << "read " << v.size() << " elements\n"; reverse(v.begin(),v.end()); cout << "elements in reverse order:\n"; for (int i = 0; i<v.size(); ++i) cout << v[i] << '\n'; return 0; // success return } For more examples of how to use the standard library to do simple things simply, see the "Tour of the Standard Library" Chapter of TC++PL4. Can you recommend a coding standard? Yes: The C++ Core Guidelines. This is an ambitious project to guide people to an effective style of modern C++ and to provide tool to support its rules. It encourages people to use C++ as a completely type- and resource-safe language without compromising performance or adding verbosity.
There are videos describing the guidelines project. The main point of a C++ coding standard is to provide a set of rules for using C++ for a particular purpose in a particular environment. It follows that there cannot be one coding standard for all uses and all users. For a given application (or company, application area, etc.), a good coding standard is better than no coding standard. On the other hand, I have seen many examples that demonstrate that a bad coding standard is worse than no coding standard. Don't use C coding standards (even if slightly modified for C++) and don't use ten-year-old C++ coding standards (even if good for their time). C++ isn't (just) C and Standard C++ is not (just) pre-standard C++. Why do my compiles take so long? You may have a problem with your compiler. It may be old, you may have it installed wrongly, or your computer might be an antique. I can't help you with such problems. However, it is more likely that the program that you are trying to compile is poorly designed, so that compiling it involves the compiler examining hundreds of header files and tens of thousands of lines of code. In principle, this can be avoided. If this problem is in your library vendor's design, there isn't much you can do (except changing to a better library/vendor), but you can structure your own code to minimize re-compilation after changes. Designs that do that are typically better, more maintainable, designs because they exhibit better separation of concerns. Consider a classical example of an object-oriented program: class Shape { public: // interface to users of Shapes virtual void draw() const; virtual void rotate(int degrees); // ... protected: // common data (for implementers of Shapes) Point center; Color col; // ... }; class Circle : public Shape { public: void draw() const; void rotate(int) { } // ... protected: int radius; // ... }; class Triangle : public Shape { public: void draw() const; void rotate(int); // ... protected: Point a, b, c; // ... }; The idea is that users manipulate shapes through Shape's public interface, and that implementers of derived classes (such as Circle and Triangle) share aspects of the implementation represented by the protected members. There are three serious problems with this apparently simple idea: It is not easy to define shared aspects of the implementation that are helpful to all derived classes.