|
Published:
January 7, 2021

C++ All-in-One For Dummies

Overview

Get ready for C++20 with all you need to know for complete mastery! 

Your comprehensive and updated guide to one of the world’s most popular programming languages is here! Whether you’re a novice or expert, you’ll find what you need to get going with the latest features of C++20. The workhorse of programming languages, C++ gives you the utmost control of data usage and interface and resource allocation. If your job involves data, proficiency in C++ means you’re indispensable!

This edition gives you 7 books in 1 for total C++ mastery. Inside, internationally renowned expert John Paul Mueller takes you from the fundamentals of working with objects and classes to writing applications that use paradigms not normally associated with C++, such as those used for functional programming strategies. The book also includes online resources such as source code. You discover how to use a C++ GNU compiler to build applications and even how to use your mobile device for coding.

  • Conquer advanced programming and troubleshooting 
  • Streamline your code with lambda expressions
  • Use C++ where you need it: for gaming, enterprise applications, and Web services
  • Uncover object secrets including the use of design patterns 
  • Discover how to use functional programming techniques to make code concise and easy to read

If you want to be your organization’s C++ guru, C++ All-In-One for Dummies is where it’s at!

Read More

About The Author

John Paul Mueller has produced 116 books and more than 600 articles on a range of topics that include functional programming techniques, application devel- opment using C++, and machine learning methodologies.

Sample Chapters

c++ all-in-one for dummies

CHEAT SHEET

C++ continues to get better over the years because people just keep contributing to it and finding new ways to work with it. You can find C++ in an amazing array of applications because it works everywhere — from desktop and mobile applications to embedded applications and other types of systems.Because C++ is so incredibly flexible, people keep coming to it as a best solution for many general programming needs and some specific needs as well.

HAVE THIS BOOK?

Articles from
the book

In a typical C++ application, the main() function receives an array and a count as command line parameters — parameters provided as part of the command to execute that application at the command line. However, to beginning programmers, the parameters can look intimidating. But they’re not: Think of the two parameters as an array of strings and a size of the array.
The name of the array is a pointer to the array itself. The array is a sequence of variables stored in memory. The array name points to the first item. This is an interesting question about pointers: Can you have a function header, such as the following line, and just use sizeof to determine how many elements are in the array?
Every time you start a new application, you create one or more processes. A process is simply executable code that is loaded into memory. The CPU reads and executes the instructions to perform the tasks you ask the application to do. When the CPU loads your application into memory, it assigns each process the application creates a Process IDentifier (PID), which is pronounced pid (think of lid with a p instead of an l).
Many developers use the Boost libraries because it provides high-quality code — so high quality that some of Boost is being standardized for inclusion in the Standard Library. One of the best things about Boost is that the library itself is free. The Boost website makes a point of letting developers know that they won’t pay anything for using Boost, even in a commercial setting.
If you have an array and you don’t want its contents to change, you can make it a constant array. The following lines of code, found in the Array05 example, demonstrate this approach: const int Permanent[5] = { 1, 2, 3, 4, 5 }; cout << Permanent[1] << endl; This array works like any other array, except you cannot change the numbers inside it.
C++ continues to get better over the years because people just keep contributing to it and finding new ways to work with it. You can find C++ in an amazing array of applications because it works everywhere — from desktop and mobile applications to embedded applications and other types of systems.Because C++ is so incredibly flexible, people keep coming to it as a best solution for many general programming needs and some specific needs as well.
Remembering a bunch of C++ syntax can make you "loopy." The following samples show the syntax of some of the more easily forgotten C++ situations: a for loop, a while loop, and a switch statement; a class and the code for a member function; a base class and a derived class; a function, function pointer type, and pointer to the function; and a class template and then a class based on the template.
Click here to download the code example files for C++ All-in-One For Dummies, 3rd Edition. These files contain all the sample code from the book. Use them to work through all the C++ sample applications describe in our book. During the writing of this book, a few of our beta readers reported some odd behavior from their anti-virus programs.
When you create an application, you write your code in various source code files. For one application, you can have many different source code files. Some large corporate projects may have hundreds (or even thousands) of source code files with dozens of programmers working on the different files. As you can imagine, dozens of strong-willed programmers working together makes for quite an adventure; but by using tools like make, these programmers are able to easily work together.
One of the advantages of using C++ is that you can create concise code that is easy to read. Because you can see more of the code in one glance, C++ is often easier to understand as well because you don’t have to scroll the editor page to see the entire solution to a particular problem. However, there are some types of C++ problems that did require a rather verbose solution in earlier versions of C++.
Saving time and effort is part of the reason you use literals. There is a shorthand way to create literals and ensure that you obtain the correct constant type. Many of the standard literals provide you with a prefix or suffix you can use to access them. Precisely how the prefix or suffix is interpreted depends on how you use it.
The Standard Library, coupled with the built-in features of C++, provide you with an interesting array of literals. However, the true value of literals becomes more obvious when you create your own. There are many different needs you can address using User-Defined Literals (UDLs), but three common needs are supporting data conversions, making custom types easier to work with, and obtaining desired side effects without the usual number of coding problems.
When you read from a file, you can use the extraction operator, >>. This operator is very easy to use, provided you recognize that the phrase, “Look mom, no caveats!” just doesn’t apply to the extraction operator. Suppose you have a file called Numbers.txt with the following text on one line: 100 50 30 25 You can easily read in these numbers with the following code.
When you open a file by constructing either an ofstream or ifstream instance, you can modify the way the file will open by supplying what are called flags. In computer terms, a flag is simply a small item whose presence or lack of presence tells a function how to do something. With the ofstream and ifstream classes, the function in question is the constructor.
Since the beginning of time, or at least since the beginning of the Unix operating system, programmers have used a utility called make to build their applications. And it’s still often used today. The make utility looks at which of your source code files have changed and decides what needs to be compiled and built.
When you open a file, all kinds of things can go wrong. A file lives on a physical device — a fixed disk, for example, or perhaps on a flash drive or SD card — and you can run into problems when working with physical devices. For example, part of the disk might be damaged, causing an existing file to become corrupted.
Most of the Boost library works just fine by adding headers to your application code. However, a few components, such as RegEx, require a library. Before you can use a library, you must build it. After you build the library, you must add it to your application.There are two techniques for adding the required headers and libraries to an application.
Structure templates have many interesting uses, such as creating a data repository that doesn’t depend on a particular type. The StructureTemplate example here shows one such use. #include <iostream> using namespace std; template<typename T> struct Volume { T height; T width; T length; Volume() { height = 0; width = 0; length = 0; } T getvolume() { return height * width * length; } T getvolume(T H, T W, T L) { height = H; width = W; length = L; return height * width * length; } }; int main() { Volume<int> first; cout << "First volume: " << first.
The static library starts with a standard C file. To make this library work well with templates, you need to delete the C file, add a C++ file, and add a header file. The following steps describe how to perform this process:Right-click main.c in the Projects tab of the Management window and choose Remove File From Project from the context menu that appears.
Ah, copying a file — something so simple, it happens all the time. Copy this file there; copy that file here. But what exactly takes place when you copy a file? You actually create a new file, and fill it with the same contents as the original file. And how do you do that? Well, it sounds like you have to read each and every byte from the first file, and write it to the second.
With a math template, you usually need access to a wealth of calculations but may only use one or two of those calculations at a time. For example, if someone is calculating your mortgage, he or she doesn’t need to know the amortization calculation. However, the person might need the amortization calculation when working with the next customer.
If you want to create a directory, you can call the mkdir function. If the function can create the directory for you, it returns a 0. Otherwise it returns a nonzero value. (When you run it you get a –1, but your best bet — always — is to test it against 0.) Here’s some sample code (found in the MakeDirectory example) that uses this function: #include <iostream> #include <stdio.
Creating a library project in C++ is only a little different than creating a console application. The following steps describe how to create a library project:Choose File→New→Project.You see the New From Template dialog box shown. Highlight the Static Library icon on the Projects tab, then click Go.You see the Welcome page of the Static Library wizard.
Many C++ newbies want to create the projects they find in books by typing in the code they come across to better see how the process works. However, sometimes just getting the project started can be a serious problem. You may find step-by-step instructions online that provide you with techniques you can use to create the projects, but often, these procedures build on what you've done before.
The usual way of declaring an array is to simply line up the type name, followed by a variable name, followed by a size in brackets, as in this line of code: int Numbers[10]; This code declares an array of 10 integers. The first element gets index 0, and the final element gets index 9. Always remember that in C++ arrays start at 0, and the highest index is one less than the size.
It’s fun to go on a cleaning spree and just toss everything out. And so it makes sense that deleting a directory is easy. To do it, you just call the rmdir function, passing the name of the directory. If you want to find out whether it worked, test its results against 0. Here’s some sample code: #include <iostream> #include <stdio.
Class templates perform the heavy lifting of the template types. You use a class template to define objects of nearly any size. In most cases, you use classes to represent complex objects or to perform tasks ill-suited for function or structure templates. You normally code classes in a separate file using the name of the class as the filename.
If you want to read the contents of a directory, you’re really going against what’s available in the standard C++ language. However, the Kind Souls of the Great Libraries of C++ (that is, the people who wrote most of the available C++ libraries) usually built in some handy functions for getting the contents of a directory.
Most containers let you perform random access of data they contain. For example, the RandomAccess example shows that you can create an iterator and then add to or subtract from the current offset to obtain values within the container that iterator supports: #include <iostream> #include <vector> using namespace std; int main() { vector<string> Words; Words.
Temporary buffers are useful for all kinds of tasks. Normally, you use them when you want to preserve the original data, yet you need to manipulate the data in some way. For example, creating a sorted version of your data is a perfect use of a temporary buffer. The TemporaryBuffer example shows how to use a temporary buffer to sort some strings.
Just as you can initialize a single-dimensional array by using braces and separating the elements by commas, you can initialize a multidimensional array with braces and commas and all that jazz, too. But to do this, you combine arrays inside arrays, as in this code: int Numbers[5][6] = { {1,2,3,4,5,6}, {7,8,9,10,12}, {13,14,15,16,17,18}, {19,20,21,22,23,24}, {25,26,27,28,29,30} }; The hard part is remembering whether you put in five batches of six or six batches of five.
Writing to a file is easy in C++. You’re probably already familiar with how you can write to the console by using the cout object, like this: cout << "Hey, I'm on TV!" << endl; Well, guess what! The cout object is a file stream! Amazing! And so, if you want to write to a file, you can do it the same way you would with cout:.
The Standard Library in C++ contains a number of functions to find something you need within a container. Locating what you need as efficiently as possible is always a good idea. Unlike your closet, you want your applications well organized and easy to manage! The four common find() algorithms are find() find_end() find_first_of() find_if() The algorithm you use depends on what you want to find and where you expect to find it.
Hashes are an important security requirement for applications today. A hash creates a unique numeric equivalent of any string you feed it. Theoretically, you can’t duplicate the number that the hash creates by using another string. A hash isn’t reversible — it isn’t the same as encryption and decryption. A common use for hashes is to send passwords from a client to a server.
If you have to pass a multidimensional array to a function, things can get just a bit hairy. That’s because you don’t have as much freedom in leaving off the array sizes as you do with single-dimensional arrays. Suppose you have this function: int AddAll(int MyGrid[5][6]) { int x,y; int sum = 0; for (x = 0; x < 5; x++) { for (y = 0; y < 6; y++) { sum += MyGrid[x][y]; } } return sum; } So far, the function header is fine because we’re explicitly stating the size of each dimension.
Computer applications perform many comparisons. In most cases, you don’t know what the values are in advance or you wouldn’t be interested in performing the comparison in the first place. The min() and max() functions make it possible to look at two values and determine the minimum or maximum value. The MinAndMax example demonstrates how you use these two functions: #include <iostream> using namespace std; int main() { int Number1, Number2; cout << "Type the first number: "; cin >> Number1; cout << "Type the second number: "; cin >> Number2; cout << "The minimum number is: " << min(Number1, Number2) << endl; cout << "The maximum number is: " << max(Number1, Number2) << endl; return 0; } In this case, the code accepts two numbers as input and then compares them using min() and max().
Sometimes you want to place data in a specific common folder, such as the current working directory — the directory used by the application. C++ provides a method to obtain this information: getcwd(). This method appears in the header. Using the getcwd() method is relatively straightforward. You create a place to put the information, called a buffer, and then ask C++ to provide the information.
When an application is running, the functions in the application exist in the memory; so just like anything else in memory, they have an address. And having an address is good, because that way, people can find you. You can take the address of a function by taking the name of it and putting the address-of operator (&) in front of the function name, like this: address = &MyFunction; But to make this work, you need to know what type to declare address.
It’s surprising to find out that most C++ programmers have no idea that a pointer called this exists. So this is a big secret! Revel in it! What is the secret? The secret is that you can take the address of an object’s member function so that you can access the member function instance data directly. Ooh-wee! Now, remember that each instance of a class gets its own copy of the member variables, unless the variables are static.
A static member function is, in many senses, just a plain old function. The difference is that you have to use a class name to call a static function. But remember that a static member function does not go with any particular instance of a class; therefore you don’t need to specify an instance when you call the static function.
The ANSI C++ standard document gives a complete library of classes that handle streams and general input/output. Fortunately, most of the classes in the Standard Library are available with almost all the compilers currently available. Getting the right header file The streams library includes several classes that make your life much easier.
There's a quick-and-dirty way you can copy a file, and you can use this to also move, delete, and rename files. However, this method is absolutely not portable: in effect, if you do this on Windows, for example, you won't be able to run the same application on Unix, and vice versa. That is, you have to make a version for the operating system you're using.
There are many ways to define literals. Of course, the kind of information that a literal affects is the most common method. However, literals can also be raw or cooked. A raw literal receives input from the application source and doesn’t interpret it in any way. What this means is that the information is interpreted character by character, precisely as the sender has presented it.
This following file has a general format (or protocol!). The text is easy because it can only be interpreted in one way — as text. Sooner or later, you may be reading a file that has this kind of information in it: Hello there my favorite number is 13. When I go to the store I buy 52 items each week, except on dates that start with 2, in which case I buy 53 items.
Declaring a variable that is a reference is easy. Whereas the pointer uses an asterisk, *, the reference uses an ampersand, &. But there’s a twist to it. You cannot just declare it like this: int &BestReference; // Nope! This won't work! If you try this, you see an error that says BestReferencedeclaredasreferencebutnotinitialized.
It’s possible to return a reference from a function. But be careful if you try to do this: You do not want to return a reference to a local variable within a function — because when the function ends, the storage space for the local variables goes away. Not good! But you can return a reference to a global variable.
Most programmers think of a stream as the same thing as a file. You know — a file that’s stored on your hard drive or maybe on a Universal Serial Bus (USB) flash drive or Secure Digital (SD) card. But streams go beyond just files. A stream is any type of data structure that you stream (that is, flow) your data into and out of in a sequence of bytes.
Some templates don’t go together quite as easily as you might expect because they express a concept that doesn’t translate the same way for every data type. For example, when you use stringify to turn a data type into its string representation, the technique differs based on data type. For example, when you want to use stringify on an int, you might use the following template: #include <iostream> #include <sstream> using namespace std; template<typename T> inline string stringify(const T& input) { ostringstream output; output << input; return output.
Although many C++ programmers take measures to prevent bugs, mistakes still slip through. This list of the ten most common mistakes while writing C++ code can help both new and veteran programmers: You forgot to declare the variable. You used the wrong uppercase and lowercase letters; for example, you typed Main when you meant main.
Random number generators fulfill a number of purposes. Everything from games to simulations require a random number generator to work properly. Randomness finds its way into business what-if scenarios as well. In short, you need to add random output to your application in many situations. Creating a random number isn’t hard.
The Standard Library documentation uses a formal approach that you’re going to find difficult to read and even harder to understand. The best way to begin is to break the Standard Library into smaller pieces. You can categorize the Standard Library functions in a number of ways. One of the most common approaches is to use the following categories: Containers Containers work just like the containers in your home — they hold something.
The template you create has to look professional and work as expected. The first decision you have to make is what kind of template to create. You can choose among these three types: Function: A function represents the simplest way to create a template and eases debugging requirements. You can group functions in libraries to make them easier to access.
The whole point of literals is to make code more readable and easier to maintain. However, built-in literals are limited to a few data types, summarized as follows: Integer Floating-point Character String Boolean Pointer UDL Sometimes you need a literal of a type other than these built-in types and that’s where UDLs come into play.
QuickBook is an add-on for BoostBook. This utility started as someone’s weekend project. Originally, QuickBook outputted simple HTML documents. However, now it outputs XML in BoostBook format so that you can quickly generate documentation that links with the rest of the documentation for your project. QuickBook is a WikiWiki style documentation tool.
Even though you can currently create User-Defined Literals (UDLs) for some basic types, there are many situations where developers need UDLs for classes as well. In some cases, these classes are part of the Standard Library. There are now consistent and standardized UDLs attached to some classes. Following are some of the more important classes and how to use them.
In C++, a header file holds forward declarations of identifiers. Here are some of the most common C++ header files that you’ll be using, along with their correct spellings. These aren’t by any means all of them, but they are the most common: Include if you’re going to be using the string class. Include when you want to use cout and cin.
A map provides a method for quickly working with lists of data in such a manner that you can access each element easily with a key. Using a map is convenient because you can access the items in a random order. However, every key must be unique. It’s not as if your application will fail if you assign a value to a duplicate key — the duplicate will simply overwrite the original value.
Static arrays are allocated on the stack, which can limit their usability. Dynamic arrays are allocated on the heap, which means they're only limited by the size of memory. Admittedly, you'll find a few other differences between dynamic and static arrays, but the bottom line here is that, although dynamic arrays require a little more work to use because you must manage the memory yourself, they also provide added flexibility in working with data.
The first step in creating a template is deciding whether your idea will generate a useful template. Most developers have thousands of creative thoughts that translate into ideas during their careers; however, only a few of these ideas are exceptionally useful. By determining whether the template you want to create is a good idea at the outset, you waste less time on bad ideas and have more time to create that truly useful idea that will help you ascend to the pinnacle of development notoriety (and the astronomical amount of cash that such as position tends to generate).
Most applications require some level of configuration. The user or administrator selects application options or the application itself detects environmental needs. The kinds of input for configuration vary, but the fact remains that applications need to know how to interact with the user in a meaningful way through settings that the application reads each time it starts.
https://cdn.prod.website-files.com/6630d85d73068bc09c7c436c/69195ee32d5c606051d9f433_4.%20All%20For%20You.mp3

Frequently Asked Questions

No items found.