C++ Basics

Software to download and install:

All OSes need to install this:

One of the following IDEs:

CLion: https://www.jetbrains.com/clion/

Or Eclipse: https://www.eclipse.org/

CLion is free for students with a .edu email address, but costs money for everyone else. There is a free 30 day trial for CLion, but it costs money after that. Eclipse is free with no strings attached.

That’s not to say that JetBrains CLion isn’t worth it. JetBrains is a very innovative company that makes quality IDEs. They even created a JVM-based programming language called Kotlin, which is used for modern Android development. But if you’d rather not spend money, Eclipse is acceptable.

Windows:

Git Bash: https://gitforwindows.org/

MinGW: http://www.mingw.org/

Within the MinGW Installation Manager, you should check the boxes for the following packages:

mingw-developer-toolkit-bin

mingw32-base-bin

mingw32-gcc-g++-bin

msys-base-bin

After you’ve installed the above packages, then click in the lower lefthand corner search bar and type Control Panel. Within the Control Panel window, click “System and Security” and then click “System.” Then, on the lefthand side, click “Advanced system settings.” Then click “Environment Variables.” Click on the “Path” system variable and hit edit. Then click “new” and add “C:\MinGW\bin” (without quotes). Then hit OK. Then open a Git Bash window. Then type in this command and hit enter to confirm that you have g++ installed:

g++ –version

macOS:

Homebrew: https://brew.sh/

After installing the Homebrew package manager, open a terminal window and type this:

brew install gcc

Linux:

Open a terminal window and use these commands:

sudo apt-get install g++

sudo apt-get install gcc

sudo apt-get install gdb

Background

C was created by Bell Labs, by some of the same people who created Unix. AT&T made a ton of money from being a phone monopoly, and their Bell Labs research division funded experimental technology projects. C and Unix were some of the projects that were made this way.

C is called C because there were some previous programming languages called APL (A Programming Language) and the B programming language. C++ was created by Bjarne Stroustrup, a computer scientist and university professor. C++ is based on C. This chapter covers C++.

The main benefit of C/C++ is performance. The reason why they’re fast is because they were created many generations ago, for computers with extremely limited resources compared to now. So because of resource limitations, they really had to be more efficient in order to run at all. But now, computers are much faster, and C/C++ don’t require more and more resources to run. So these languages seems very fast, even if it didn’t seem that way when the languages were new. New languages like Python are developed on much more capable computers, so the people who make new languages are okay with their performance being subpar.

If you need something to be fast, like an operating system, video renderer, or 3D video game, it should be written in a fast language. However, C and C++ are rough around the edges and not very beginner-friendly. If you don’t need something to be super fast, go with Python or Java instead of C++. There are a lot of things that will give you headaches in these languages and it’s not worth it for many use-cases. Beginners should absolutely not start out with C or C++ as a first language. Learn something like Python, JavaScript (along with HTML and CSS), or Java first. C/C++ can be good languages to learn later once you feel like you’ve already mastered at least one other object-oriented language. C and C++ are often grouped together because of how similar the code is, but keep in mind that they are still separate languages. C++ is C with more stuff added on, though modern C adds a lot of stuff too.

One time, when I was at a job fair near St. Louis, someone was mentioning how their company was rewriting a lot of Python code in C++ because of the performance difference. Python is a nice language, but Python programs can be quite slow. There is a version of Python called Cython, which is Python with C extensions for performance reasons. However, it’s much more common for people to either use C or Python instead.

Aside from performance, another benefit of C++ is the libraries for it. Since it’s a very popular language that has been around for a long time, people have already written a lot of code for it. So even if the standard library doesn’t have what you need, odds are that there’s a third party library that achieves what you want. Don’t reinvent the wheel if someone has already made and shared an adequate solution to something you want to do. Just be careful about library licenses – some can’t be used for commercial purposes, so that’s important to keep in mind if you’re thinking about making an app to sell. Some software uses a dual-license model, where it’s free for personal use, but costs money if you want to use it in a commercial product. Some open source licenses require you to let people see the source code of your program if you add the open source-licensed project into your own. And some licenses will let you use it pretty much however you want. It all depends on the specific license. Read the terms for using third party code before implementing it into your project.

If you want to make a 3D video game, you could either learn a language like C# and the Unity game engine, which is somewhat cookie cutter, or you can learn C++ and OpenGL to make something more DIY. Possibly more rough around the edges, but you’d have more ownership of your project due to making it yourself rather than using a game engine that was made entirely by other people. The Unity video game engine was written in C++, although if you use the game engine, you will have to code for it in C#, which is more like Java. There is also a library for C++ called SDL, or Simple DirectMedia Layer, which is used for making games in C++.

Lots of well-known software is written in C or C++. Even if you’ve never coded in C++ before, you’ve certainly used software that was written in it.

Firefox used to be written in C++, but now a lot of the codebase has been ported over to Rust. Rust is similar to C++ but has better memory safety features built into the language. WebKit, an open source browser engine created by Apple, was written in C++. Safari, Chrome, Opera, and now even Microsoft Edge are all based on WebKit. So odds are, if you’re using a browser, you’re relying on C++ code.

Windows 10 was written in C, C++, and C#. Unix was written in C and assembly. The Linux kernel is C, but Linux userland stuff is often C++. Photoshop used to be written in Pascal (a very outdated programming language), but now it’s written in C++. GIMP, which is a free and open source alternative to Photoshop, was written in C, although you can write scripts or plugins for it in Python.

C is a procedural programming language, whereas C++ is object-oriented. The original name for C++ was C with Classes, but was later changed. ++ is the unary increment operator, so it’s like saying +1 more than C.

Most C code can run in C++, but the reverse is not necessarily true.

One bad aspect of C/C++ is that a lot of malware is written in these languages because computers can often run executables in these languages using OS API components, like DLLs, with no need to install a separate dependency. By contrast, code written in Java or Python isn’t guaranteed to run on all computers. If a criminal wants to infect as many people as possible with malware, they can’t assume that they’re going to have things like Java or Python installed, which most people don’t have unless they’re developers (and the vast majority of computer users don’t do any programming). Even though you need to install something like GCC or G++ to compile C/C++ programs, you don’t need these compilers just for your computer to be able to run compiled C/C++ code.

Some versions of C include ANSI C, C99, and C11. C99 was made in 1999 and C11 was released in 2011. There is also a hacking tool called C99 shell, which actually isn’t written in C at all, but instead it’s written in PHP.

C++ has a new version every three years of so. For example, C++11, C++14, and C++17 are all versions of C++. They often add new features. If you’re trying to use a feature and it doesn’t work for you, it might be because you’re using an older version. On the other hand, some features get deprecated, so if you’re looking up an ancient tutorial, it might show features that are no longer supported.

When you compile, you can specify a version to use, or if you don’t, it will just use whatever default your IDE or compiler has set up. Examples of choosing which version (also called a standard) to use when compiling (you might not have the same ones installed or set up on your own system, so your mileage may vary):

g++ -std=gnu++14 main.cpp -o output_name.exe

g++ is the GNU C++ compiler. A compiler turns code that a human can read into code that a computer can read. You may or may not be using a different compiler, but this is what I use. To use C++14 in g++, you’d use gnu++14. You might want to use -std=c++14 instead. It depends on a lot of things, but you can still compile code without picking which version to use.

Just be aware that, if you look for code online, and it uses a feature that was introduced in a newer version of C++, it might not work if you’re using an older version. The same is true for Python, Java, and basically any other programming language out there.

C++ compiling turns source code into assembly code, converts assembly into machine code, and then links different files together to create an executable, such as a file ending in .exe or .out.

Because a lot of malware is written in C/C++, and because of the way these languages are compiled, malware analysis tools often “disassemble” code, meaning they turn machine code into assembly code. Assembly code can be harder to understand than C++, but still significantly easier than dealing with machine code. If you want to get into malware analysis, it would be good to know C/C++ and assembly, as well as disassembly tools such as NSA Ghidra, IDA Pro, x64dbg, or OllyDbg.

It’s relatively easy to write and compile a C/C++ program, but harder to disassemble or reverse engineer it once it’s compiled.

ANSI – American National Standards Institute. If you get into C, you might see the term “ANSI C” used every now and then.

C++ boilerplate:

Boilerplate is repetitive code that you will be writing a lot, for most if not all of your projects, often for the entry point of execution in something called a driver class or driver file, meaning it drives the program (not to be confused with something called a device driver, which is how a computer talks to hardware such as printers, graphics cards, etc). The following is boilerplate C++ from JetBrains CLion. Just like how you need a main method in Python or Java, you need one in C++ too.

#include <iostream>

int main() {

std::cout << “Hello, World!” << std::endl;

return 0;

}

In the above example, no namespace is specified, so you have to specify the std namespace to use cout and endl. However, you can also do something like this to use the standard namespace so you don’t have to use std:: all the time:

#include <iostream>

using namespace std;

int main() {

cout << “Hello, World!” << endl;

return 0;

}

:: means specifying a particular namespace. You use the namespace name, such as std, followed by :: and then what you want to use from that namespace. For small programs, you aren’t likely to use anything other than the standard (std) namespace. For more advanced projects, you might be working with things from different namespaces, so you might eventually use ::.

cout is sort of like printing. You are outputting to the standard output, which in this case is the window you’re running the program in, such as a terminal. return 0 means the program finished successfully. Any other int return values from the main function means there was some sort of error.

#include is how you add stuff to a program, like import in Java or Python. <iostream> is for basic IO stuff, like getting keyboard input from a user or displaying text in a terminal. For any given #include, you need <> around it. Some includes, such as header includes, will include .h at the end, designating that it’s a header. Headers use quotes instead of <>, such as the following example:

#include “MyHeader.h”

The main() function needs to have an int return type because it returns an integer. The main() is where all your code should go. You can have other .cpp files later, but the main.cpp with the main() function is what’s called your driver file, similar to Python or Java. C++ supports classes and objects, just like other OOP languages.

If you want to make functions with no return value, use the void return type instead of int. But a main() should always return an int, such as 0 to indicate no errors.

In a function, () is where you put any optional arguments to be passed into the function, such as void myCoolFunc(int arg1, int arg2){}.

{} is where the body of a function goes.

Unlike Python, statements need to be ended with a semicolon, such as return 0;

If you forget a semicolon, it can cause problems, and the compiler’s error message you get will look very weird. It won’t necessarily say something simple like “you forgot a semicolon.”

Here is an example of trying to compile when you forgot a semicolon (but it can look different, depending on the context and compiler):

$ g++ main.cpp -o hello.exe

main.cpp: In function ‘void shiftUp(Transmission&)’:

main.cpp:23:5: error: expected ‘;’ before ‘}’ token

} else {

^

Unlike Python, C++ is a compiled language. And unlike Java, compiled C++ programs aren’t as cross-platform. A Java JAR file (or any compiled Java bytecode) will run on any computer with Java installed, but a lot of C++ compilation is specific to a particular operating system. For example, .exe is associated with Windows. Not only that, but some features are OS-specific. If you write a C++ program, if it’s quite complicated (as opposed to something simple like a hello world program), it’s possible that you might have to change some of the code so that it can work on different operating systems, in addition to compiling it for a different OS. For example, to pause the program for a certain amount of time (kind of like Thread.sleep() in Java), C++ on Windows uses Sleep() from winbase.h, but Unix platforms use usleep() from unistd.h. That’s just one example of how not every OS has the same exact C++ code. Don’t get too caught up in the small details though. The point to understand here is that C++ is not as portable as newer languages like Java, Python, or JavaScript.

If you want to compile code for one platform when you’re using a different one, that’s called cross-compiling. And if your favorite coding machine is a slow laptop, you can even do something called remote compiling, where you use a faster computer, such as a server, to compile the code for you, thus saving time. But for simple programs, it’s not worth it to get into complicated remote compilation stuff.

Depending on your computer and the code you’re compiling, the process of compiling can use a lot of CPU cycles and even make your computer hotter. This is less of a problem on desktops, but it can be an issue on laptops because they have poorer cooling due to being really thin and light (meaning the heatsink and fan are sometimes inadequate for intense workloads).

Here’s one way you can compile a simple C++ program from a bash shell, assuming you have g++ installed, such as through Git Bash with MinGW or your Unix-like OS’s package manager or default packages:

g++ main.cpp -o hello.exe

This means use the GNU C++ compiler (g++) to compile main.cpp, and output (-o) it to a file called hello.exe. If you don’t specify a file name, it will default to a.exe or a.out, depending on your OS.

The way to run your hello world program is to use ./ followed by the name, such as this:

./hello.exe

The output will be as follows:

Hello, World!

But you need the .exe to be executable, so you might need to change the file mode bits, such as by doing something like this:

chmod +x hello.exe

Also, don’t use .exe if you’re on macOS or Linux. Just called it hello.out or something like that.

I was listening to a coding podcast called Coding Blocks during my commute the other day, and they brought up how some developers don’t know how to manually use a compiler. For a list of tech podcasts to listen to, check out Appendix F at the end of the book.

Many developers just rely on their IDE doing all the compiling, linking, loading, etc. for them. IDEs often let you compile and build everything with the click of a button, abstracting away all the complicated stuff, meaning you might not even understand what it’s doing. While it’s true that it’s good to know how to do things on your own, the fact of the matter is that there is more build automation these days, so there are higher and higher levels of abstraction for coding. It’s good to have command line skills, but in all likelihood, you will probably be clicking the “build” button in your IDE rather than manually compiling stuff. Is that a bad thing? No, not really. The more time you spend on compiling, the less time you spend on what your app is actually supposed to do. This concept is called yak shaving.

Wiktionary.org defines yak shaving as “any apparently useless activity which, by allowing you to overcome intermediate difficulties, allows you to solve a larger problem.”

Compiling is a computationally-intensive process, and if the program is sufficiently large, it can take a while to compile. It’s best to only recompile .cpp files than have been changed, rather than recompiling everything, which would add unnecessary time to compilation.

Once a C++ program is compiled, it’s much faster than Python or Java. Performance is the main draw of C++. So if you want to write software like games, 3D rendering, a ray tracer, or something like that, C++ is the right language to use. However, I personally don’t think the performance gains are worth the headaches and all the yak shaving involved. C++ also doesn’t hold your hand and will let you make serious mistakes that can lead to either instability or security issues, which more highly abstracted languages take care of for you in the background. It’s still possible to write insecure code in Python/Java/etc. but it’s a lot easier to write insecure code in C++.

C++ filetypes:

Files commonly associated with C/C++ programs include .c, .cpp, .h, .o, .out, .exe, and .obj. C++ is based on C, but there are many common things between them. C source code files are .c, whereas C++ source code files are .cpp, standing for c plus plus. .h is a header file, .out are output files (executables), .exe is a windows executable, and .o and .obj are object files. A complex program might have multiple object files that are linked together into a final .exe. But don’t worry about that for now, because you will be making simple single-file executables to start with.

C++ single-line comments:

// this is a single-line comment in C++

C++ multi-line comments:

/*

This is a multi-

line comment in C++

*/

C++ printing:

You can use cout << “some string” << endl; to print. Or you can use printf().

Here is an example of printf():

#include <iostream>

using namespace std;

int main() {

printf(“Hello\n”);

return 0;

}

However, printf() has some issues with strings. C didn’t even have support for strings back in the day – just char arrays. C++ string support is still a little dodgy compared to newer languages. So I’d recommend just avoiding printf() and just using cout << something << endl;

Here’s how you can print string variables with cout:

#include <iostream>

using namespace std;

int main() {

string someName = “Bob”;

cout << “Hello, ” << someName << “!” << endl;

return 0;

}

C++ <iostream>:

Basic IO stuff. Not to be confused with file IO, which is different. Just for getting user input and displaying stuff to the screen.

C++ main function (in a file called main.cpp):

#include <iostream>

using namespace std;

int main() {

//main stuff goes here

//this is where the program will start

cout << “This is a main() function” << endl;

return 0;

}

C++ puts():

#include <iostream>

using namespace std;

int main() {

puts(“Hello”);

return 0;

}

C++ <string>:

#include <string> can be useful if you want to use strings.

C++ endl:

endl is essentially a new line. It’s usually used with cout.

C/C++ include:

#include <iostream>

#include <iterator>

#include <string>

#include <cstdlib>

#include <typeinfo>

#include <tuple>

#include <compare>

#include <exception>

#include <array>

#include <vector>

#include <set>

#include <map>

#include <fstream>

#include <iomanip>

#include <thread>

#include <filesystem>

#include <ctime>

#include <cmath>

#include <random>

#include <regex>

#include “myOwnFile.h”

Just like “import” in other languages.

← Previous | Next →

C++ Topic List

Main Topic List

Leave a Reply

Your email address will not be published. Required fields are marked *