C++ Articles
C++ is a flexible and powerful programming language. Learn the basics, plus some cool tidbits you haven't seen before.
Articles From C++
Filter Results
Cheat Sheet / Updated 03-19-2021
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.
View Cheat SheetArticle / Updated 03-09-2017
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). The PID is simply a number associated with the process for easy identification. In most cases, you debug an application by running it in the IDE in debug mode. However, there are some situations where you must debug the application in a different way — by attaching to its process. Attaching to the process means telling the CPU to send the instructions in the executable code to a debugger before they're executed by the CPU. In other words, you place the debugger between the executable code and the CPU. Here are some of the most common reasons for performing this task: The executable code is behaving differently in the debugger than it does when executed as a regular application. Instead of working with a debug version, you want to debug the release version. It's important to see the disassembled code as it loads in memory. You don't actually have source code to load into the debugger and execute. There are many other reasons to attach to a running process, but these are the most common reasons. Of course, before you can attach to the process, you need to know the PID. Determining the PID depends on the platform you're using. Here are some common approaches: Windows: Look at the Processes tab of the Windows Task Manager Mac OS X: Use the PS utility in the Terminal window or the Activity Monitor Linux: Use the PS utility in the Terminal window Once you have a PID, you can use it to attach to the process in Code::Blocks. The following steps get you started. Open your copy of Code::Blocks using a technique appropriate for your operating system. You see the Code::Blocks IDE open with the Start Here tab opened. Choose Debug→Attach to Process The Input Text dialog box appears. Type the PID in the PID to Attach To field and then click OK. You see the Debugger tab of the Logs and Others window appear. This tab contains information about the current process. You can type commands in the Command field to perform debugging tasks. At this point, you can type commands in the Command field to perform debugging tasks. The most common commands are: Break: Stops application execution so you can examine the application state. Step: Steps one source line (which may be several assembly lines). Continue: Restarts application execution. Go: Continues application execution to a specific point in the code. Detach: Detaches a previously attached PID so that you can safely shut the debugger down. Help: Displays additional command information.
View ArticleStep by Step / Updated 06-27-2016
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. The first technique is to add it to the compiler settings. The second technique is to add the settings to a specific project. You use the first technique when you work with Boost for a large number of projects and require access to all libraries. The second technique is best when you use Boost only for specific projects and require access only to specific libraries. The following steps show you how to perform the project-specific setup for any library, not just the RegEx library:
View Step by StepStep by Step / Updated 06-27-2016
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:
View Step by StepStep by Step / Updated 06-27-2016
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:
View Step by StepArticle / Updated 03-26-2016
The C++ programming language consists of a vocabulary of commands that humans can understand and that can be converted into machine language fairly easily and a language structure (or grammar) that allows humans to combine these C++ commands into a program that actually does something (well, maybe does something) The vocabulary is often known as the semantics, while the grammar is the syntax. What's a program? A C++ program is a text file containing a sequence of C++ commands put together according to the laws of C++ grammar. This text file is known as the source file . A C++ source file carries the extension .CPP just as a Microsoft Word file ends in .DOC or an MS-DOS batch file ends in .BAT. The concept extension .CPP is just a convention, but it's used almost exclusively in the PC world. The point of programming is to write a sequence of C++ commands that can be converted into a machine language program that does whatever it is that you want done. Such machine executable programs carry the extension .EXE. The act of creating an executable program from a C++ program is called compiling (or building — there is a difference, but it's small). How do I program? To write a program, you need two things: an editor to build your .CPP source file with and a program that converts your source file into a machine executable .EXE file to carry out your commands. The tool that does the conversion is known as a compiler. Nowadays, tool developers generally combine the compiler with an editor into a single work-environment package. After entering your program, you need only click a button to create the executable file. The most popular of all C++ environments is Microsoft's Visual C++, but the software is expensive. Fortunately, there are public domain C++ environments — the most popular of which is GNU C++. (Pronounce GNU like this: guh NEW). You can download public domain programs from the Internet. Some of these programs are not free — you are either encouraged to or required to pay some usually small fee. You do not have to pay to use GNU C++. GNU stands for the circular definition "GNU is Not UNIX." This joke goes way back to the early days of C++ — just accept it as is. GNU is a series of tools built by the Free Software Foundation. GNU C++ is not some bug-ridden, limited edition C++ compiler from some fly-by-night group of developers. GNU C++ is a full-fledged C++ environment. GNU C++ supports the entire C++ language and executes all C++ programs. GNU C++ is not a Windows development package for the Windows environment. You'll have to break open the wallet and go for a commercial package like Visual C++.
View ArticleArticle / Updated 03-26-2016
C++ variables are stored internally as so-called binary numbers. Binary numbers are stored as a sequence of 1 and 0 values known as bits. Most of the time, you don't really need to deal with numbers at the bit level; however, there are occasions when doing so is convenient. C++ provides a set of operators for this purpose. The so-called bitwise logical operators operate on their arguments at the bit level. To understand how they work, examine how computers store variables. The decimal number system The numbers that you are familiar with are known as decimal numbers because they are based on the number 10. In general, the programmer expresses C++ variables as decimal numbers. Thus, you would say that the value of var is 123, for example. A number such as 123 refers to 1 * 100 + 2 * 10 + 3 * 1. Each of these base numbers — 100, 10, and 1 — is a power of 10. 123 = 1 * 100 + 2 * 10 + 3 * 1 Expressed in a slightly different but equivalent way: 123 = 1 * 102 + 2 * 101 + 3 * 100 Remember that any number to the zero power is 1. Other number systems The use of a base number of 10 for the counting system stems, in all probability, from the fact that humans have 10 fingers, the original counting tools. The alternative would have been base 20. If dogs had invented our numbering scheme, it may well have been based on the numeral 8 (one digit of each paw is out of sight on the back part of the leg). Such an octal system would have worked just as well: 12310 = 1 * 82 + 7 * 81 + 3 * 80 = 1738 The small 10 and 8 here refer to the numbering system, 10 for decimal (base 10) and 8 for octal (base 8). A counting system may use any positive base. The binary number system Computers have essentially two fingers. (Maybe that's why computers are so stupid: Without an opposable thumb, they can't grasp anything. And then again, maybe not.) Computers prefer counting using base 2. The number 12310 would be expressed as: 12310 = 0*128 + 1*64 + 1*32 + 1*16 + 1*8 + 0*4 +1*2 + 1*1 = 011110112 It is always convention to express binary numbers by using 4, 8, 32, or 64 binary digits even if the leading digits are zero. This is also because of the way computers are built internally. Because the term digit refers to a multiple of ten, a binary digit is called a bit. The term stems from binary (b-) digit (-it). Eight bits make up a byte. A word is usually either two or four bytes. With such a small base, it is necessary to use a large number of bits to express numbers. It is inconvenient to use an expression such as 011110112 to express such a mundane value as 12310. Programmers prefer to express numbers by units of bytes, or eight bits. A single, four-bit digit is essentially base 16, because four bits can express up to any value from 0 to 15. Base 16 is known as the hexadecimal counting system. Hexadecimal is often contracted to simply hex. Hexadecimal uses the same digits for the numbers 0 through 9. For the digits between 9 and 16, hexadecimal uses the first six letters of the alphabet: A for 10, B for 11, and so on. Thus, 12310 becomes 7B16. 123 = 7 * 161 + B (i.e., 11) * 160 = 7B16 Because programmers prefer to express numbers in 4, 8, 32, or 64 bits, they similarly prefer to express hexadecimal numbers in 1, 2, 4, or 8 hexadecimal digits even when the leading digits are 0. Finally, it is inconvenient to express a hexadecimal number such as 7B16 using a subscript, because terminals don't support subscripts. Even on a word processor, it is inconvenient to change fonts to and from subscript mode just to type two digits. Therefore, programmers use the convention of beginning a hexadecimal number with a 0x (the reason for such a strange conviction goes back to the early days of C). Thus, 7B becomes 0x7B. Using this convention, 0x7B is equal to 123 (while 0x123 is equal to 291.) All of the mathematical operators can be performed on hexadecimal numbers in the same way that they are applied to decimal numbers. The reason that we can't perform a multiplication such as 0xC * 0xE in our heads has more to do with the multiplication tables we learned in school than on any limitation in the number system.
View ArticleArticle / Updated 03-26-2016
Developers often need the ability to break programs up into smaller chunks that are easier to develop. "Real world" programs can be many of thousands (or millions!) of lines long. Without this ability to divide the program into parts, developing such large programs would quickly become impossible. C++ allows programmers to divide their code up into chunks known as functions. A function with a simple description and a well-defined interface to the outside world can be written and debugged without worrying about the code that surrounds it. Overloading function names C++ allows the programmer to assign the same name to two or more functions. This multiple use of names is known as overloading functions or, simply, overloading. In general, two functions in a single program cannot share the same name. If they did, C++ would have no way to distinguish them. However, the name of the function includes the number and type of its arguments. (The name of the function does not include its return argument.) Thus, the following are not the same functions: void someFunction(void){ // ....perform some function}void someFunction(int n){ // ...perform some different function}void someFunction(double d){ // ...perform some very different function}void someFunction(int n1, int n2){ // ....do something different yet} C++ still knows that the functions someFunction(void), someFunction(int), someFunction(double), and someFunction(int, int) are not the same. Like so many things that deal with computers, this has an analogy in the human world. void as an argument type is optional. sumFunction(void) and sumFunction() are the same function. A function has a shorthand name, such as someFunction(). As long as we use the entire name, no one gets confused — no matter how many someFunctions there may be. The full name for one of the someFunctions()is someFunction(int). As long as this full name is unique, no confusion occurs. A typical application may appear as follows: int intVariable1, intVariable2; // equivalent to // int Variable1; // int Variable2;double doubleVariable;// functions are distinguished by the type of// the argument passedsomeFunction(); // calls someFunction(void)someFunction(intVariable1); // calls someFunction(int)someFunction(doubleVariable); // calls someFunction(double)someFunction(intVariable1, intVariable2); // calls // someFunction(int, int)// this works for constants as wellsomeFunction(1); // calls someFunction(int)someFunction(1.0); // calls someFunction(double)someFunction(1, 2); // calls someFunction(int, int) In each case, the type of the arguments matches the full name of the three functions. The return type is not part of the extended name (also known as the function signature) of the function. The following two functions have the same name and, thus, cannot be part of the same program: int someFunction(int n); // full name of the function // is someFunction(int)double someFunction(int n); // same name The following is acceptable: int someFunction(int n);double d = someFunction(10); // promote returned value The int returned by someFunction() is promoted into a double. Thus, the following would be confusing: int someFunction(int n);double someFunction(int n);double d = someFunction(10);// promote returned int? // or use returned double as is C++ would know whether to use the value returned from the double version of someFunction() or promote the value returned from int version. Defining function prototypes The programmer may provide the remainder of a C++ source file, or module, the extended name (the name and functions) during the definition of the function. A function may be defined anywhere in the module. (A module is another name for a C++ source file.) However, something has to tell main() the full name of the function before it can be called. Consider the following code snippet: int main(int argc, char* pArgs[]){ someFunc(1, 2);}int someFunc(double arg1, int arg2){ // ...do something} The call to someFunc() from within main() doesn't know the full name of the function. It may surmise from the arguments that the name is someFunc(int, int) and that its return type is void; however, as you can see, this is incorrect. C++ could be less lazy and look ahead to determine the full name of someFunc()s on its own, but it doesn't. What is needed is some way to inform main() of the full name of someFunc() before it is used. What is needed is a before use function declaration. Some type of prototype is necessary. A prototype declaration appears the same as a function with no body. In use, a prototype declaration appears as follows: int someFunc(double, int);int main(int argc, char* pArgs[]){ someFunc(1, 2);}int someFunc(double arg1, int arg2){ // ...do something} The prototype declaration tells the world (at least that part of the world after the declaration), that the extended name for someFunc() is someFunction(double, int). The call in main() now knows to cast the 1 to a double before making the call. In addition, main() knows that the value returned by someFunc() is an int. A function call that returns a value is an expression. As with any other provide expression, you are allowed to throw the value returned by a function. Variable storage types Function variables are stored in three different places. Variables declared within a function are said to be local. In the following example, the variable localVariable is local to the function fn(): int globalVariable;void fn(){ int localVariable; static int staticVariable;} The variable localVariable doesn't exist until the function fn() is called. localVariable ceases to exist when the function returns. Upon return, whatever value that is stored in localVariable is lost. In addition, only fn() has access to localVariable — other functions cannot reach into the function to access it. By comparison, the variable globalVariable exists as long as the program is running. All functions have access to globalVariable all of the time. The static variable staticVariable is something of a mix between a local and a global variable. The variable staticVariable is created when execution first reaches the declaration (roughly, when the function fn() is called). In addition, staticVariable is only accessible within fn(). Unlike localVariable, however, staticVariable continues to exist even after the program returns from fn(). If fn() assigns a value to staticVariable once, it will still be there the next time that fn() is called. In case anyone asks, there is a fourth type, auto, but today it has the same meaning as local, so just ignore them.
View ArticleArticle / Updated 03-26-2016
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. Here’s a for loop: int i; for (i=0; i<10; i++) { cout << i << endl; } Here’s a while loop that counts from 10 down to 1: int i = 10; while (i > 0) { cout << i << endl; i—; } And here’s a switch statement: switch (x) { case 1: cout << “1” << endl; case 2: cout << “2” << endl; default: cout << “Something else” << endl; } Here’s a class and the code for a member function: class MyClass { private: int x; public: void MyFunction(int y); }; void MyClass::MyFunction(int y) { x = y; } Here’s a base class and a derived class: class MyBase { private: // derived classes can // not access this int a; protected: // derived classes can // access this int b; }; class Derived : public MyBase { public: void test() { b = 10; } }; Here’s a function, a function pointer type, and a pointer to the function: int function(char x) { return (int)x; } typedef int (* funcptr)(char); funcptr MyPtr = function; And here’s a class template and then a class based on the template: template <typename T> class MyTemplate { public: T a; }; MyTemplate<int> X;
View ArticleArticle / Updated 03-26-2016
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. Include when you want to read or write files. Include if you want advanced manipulator usage in your streams. Include for general operations, including system(“PAUSE”).
View Article