Complete C++ Beginners Tutorial (Free)

According to the TIOBE Index, since the 1990’s C++ has consistently ranked as one of the top 5 programming languages.

As a general-purpose, low-level programming language, C++ is widely used for everything from desktop apps to video games. It’s efficient, battle-tested, powerful, and highly in-demand throughout the tech industry. Thus, as you can imagine, it’s not a bad language to learn and add to your toolset!

Through this article, we’re going to cover the basics of C++ in a beginner-friendly way so you can master the principles and get ready to apply them to real-world applications.

Let’s jump into it!

CTA Small Image
FREE COURSES AT ZENVA
LEARN GAME DEVELOPMENT, PYTHON AND MORE
ACCESS FOR FREE
AVAILABLE FOR A LIMITED TIME ONLY

Introduction to C++

What is C++

C++ is a high-level programming language that was created by Bjarne Stroustrup in the early 1980s. It is an extension of the C programming language and is considered to be one of the most widely used programming languages in the world. C++ is used to develop a variety of applications, including games, desktop applications, system software, and much more.

History of C++

C++ was created as an extension of the C programming language in order to add object-oriented programming (OOP) features to the language. The first version of C++ was released in 1985, and it has gone through several updates and improvements over the years. Today, C++ is considered to be a powerful and flexible language that is widely used in many different industries and fields.

Advantages of using C++

C++ has many advantages that make it a popular choice among developers. Some of the main advantages of using C++ include:

  • It is a fast and efficient language that can handle large and complex applications.
  • C++ has a rich set of features, including object-oriented programming, which makes it easy to develop complex and feature-rich applications.
  • C++ has a large and active community of developers who contribute to its development and offer support to other users.
  • There are many resources available for learning C++, including books, tutorials, and online courses, making it easy for new users to get started.

Getting Started with C++

Getting started with C++ is easy, even if you have no prior programming experience. All you need is a basic understanding of how computers work and a willingness to learn. To get started with C++, you will need a compiler, which is a program that can compile and run your C++ code.

Setting up the Development Environment

To get started with C++ programming, you will need to set up a development environment. This typically involves installing a compiler and a code editor on your computer. There are many free compilers and code editors available, including GCC and Code::Blocks, that you can use to get started with C++ programming.

Visual demo of data structures for C++

C++ Fundamentals

Variables and Data Types

In C++, a variable is a named location in memory that is used to store a value. The value stored in a variable can be of different data types, including integers, floating-point numbers, and characters. Here’s an example of declaring and initializing an integer variable in C++:

int age = 25;

In this example, the variable “age” is declared as an integer and is initialized with the value 25. In C++, there are several basic data types, including:

  • Integers (int): used to store whole numbers
  • Floating-point numbers (float, double): used to store real numbers
  • Characters (char): used to store individual characters
  • Booleans (bool): used to store true/false values

Operators and Expressions

In C++, operators are symbols that perform operations on values and variables. For example, the “+” operator can be used to add two values:

int x = 10;
int y = 20;
int result = x + y;

In this example, the values of “x” and “y” are added together using the “+” operator and the result is stored in the variable “result”. In C++, there are several types of operators, including:

  • Arithmetic operators ( +, -, *, /, % )
  • Comparison operators ( ==, !=, >, <, >=, <= )
  • Logical operators ( &&, ||, ! )
  • Assignment operators ( =, +=, -=, *=, /=, %= )

Control Flow Statements

Control flow statements are used to control the flow of execution of a program. Here’s an example of an if-else statement in C++:

int score = 75;

if (score >= 60) {
  cout << "You passed the exam!" << endl;
} else {
  cout << "You failed the exam." << endl;
}

In this example, the if-else statement is used to determine if the value stored in “score” is greater than or equal to 60. If it is, the message “You passed the exam!” is printed. If not, the message “You failed the exam.” is printed. In C++, the main control flow statements include:

  • If-else statements
  • For loops
  • While loops
  • Switch statements

Functions

In C++, functions are blocks of code that perform a specific task. Here’s an example of a simple function in C++:

#include 
using namespace std;

int addNumbers(int x, int y) {
  return x + y;
}

int main() {
  int result = addNumbers(5, 7);
  cout << "The result is: " << result << endl;
  return 0;
}

In this example, the function “addNumbers” takes two parameters (x and y) and returns their sum. The function is then called in the “main” function, where the result is stored in the “result” variable and printed to the console. Functions can greatly simplify your code and make it easier to reuse and maintain. In C++, you can also pass parameters to functions by reference or by value, and you can also have functions that do not return a value.

Text-based dungeon crawler made with C++

Advanced C++ Features

Pointers

Pointers are a fundamental concept in C++ that allow you to manipulate memory directly. With pointers, you can access the memory address of a variable and modify the value stored there. Here’s an example of using a pointer in C++:

#include 
using namespace std;

int main() {
  int age = 25;
  int *pAge = &age;
  
  cout << "Age: " << age << endl;
  cout << "Address of age: " << pAge << endl;
  cout << "Value of age using pointer: " << *pAge << endl;
  
  *pAge = 30;
  cout << "Age after modification: " << age << endl;
  
  return 0;
}

In this example, a pointer “pAge” is declared and assigned the address of the “age” variable. The value of “age” can then be accessed and modified using the pointer. Pointers can be used to dynamically allocate memory, pass parameters to functions by reference, and implement complex data structures like linked lists and trees.

Arrays and Strings

Arrays are used to store collections of values of the same data type. Here’s an example of declaring and initializing an array in C++:

#include 
using namespace std;

int main() {
  int numbers[5] = {1, 2, 3, 4, 5};
  
  for (int i = 0; i < 5; i++) {
    cout << numbers[i] << " ";
  }
  cout << endl;
  
  return 0;
}

In this example, an array “numbers” is declared and initialized with 5 values. The values in the array can be accessed using the array index, as demonstrated in the for loop. Strings are arrays of characters that are used to store text. Here’s an example of working with strings in C++:

#include 
#include 
using namespace std;

int main() {
  string name = "John Doe";
  
  cout << "Length of name: " << name.length() << endl;
  cout << "Third character of name: " << name[2] << endl;
  
  name[0] = 'A';
  cout << "Name after modification: " << name << endl;
  
  return 0;
}

In this example, a string “name” is declared and initialized with the value “John Doe”. The length of the string can be obtained using the “length” function, and individual characters can be accessed using the array index. Strings in C++ have many built-in functions for working with text, such as “substr”, “find”, and “replace”.

Structures and Classes

Structures and classes are used to create custom data types in C++. A structure is a collection

of variables of different data types, while a class is a blueprint for creating objects. Here’s an example of using a structure in C++:

#include 
using namespace std;

struct Person {
  string name;
  int age;
};

int main() {
  Person john;
  john.name = "John Doe";
  john.age = 25;
  
  cout << "Name: " << john.name << endl;
  cout << "Age: " << john.age << endl;
  
  return 0;
}

In this example, a structure “Person” is declared with two variables “name” and “age”. An object of type “Person” can then be created and its variables can be accessed and modified. Classes are similar to structures, but they provide additional features such as encapsulation, inheritance, and polymorphism. Here’s an example of using a class in C++:

#include 
using namespace std;

class Person {
  public:
    string name;
    int age;
    
    void print() {
      cout << "Name: " << name << endl;
      cout << "Age: " << age << endl;
    }
};

int main() {
  Person john;
  john.name = "John Doe";
  john.age = 25;
  
  john.print();
  
  return 0;
}

In this example, a class “Person” is declared with two variables “name” and “age”. A member function “print” is also declared to print the values of the variables. An object of type “Person” can then be created and its member function can be called to print the values of the variables.

Templates and Exception Handling

Templates in C++ allow you to write generic code that can work with any data type. Templates are especially useful for writing functions and classes that can work with multiple data types. Here’s an example of using a template function in C++:

#include 
using namespace std;

template 
T max(T a, T b) {
  return (a > b) ? a : b;
}

int main() {
  cout << "Max of 3 and 4: " << max(3, 4) << endl;
  cout << "Max of 3.14 and 2.71: " << max(3.14, 2.71) << endl;
  cout << "Max of John and Doe: " << max("John", "Doe") << endl;
  
  return 0;
}

In this example, a template function “max” is declared to find the maximum of two values. The function can be used with different data types, such as integers, floating-point numbers, and strings, as demonstrated in the main function. Exception handling in C++ allows you to handle errors and exceptional conditions in your code. Here’s an example of using exception handling in C++:

#include 
double divide(double a, double b) {
if (b == 0) {
throw "Division by zero error";
}

return a / b;
}

int main() {
double x, y;

cout << "Enter x: "; cin >> x;

cout << "Enter y: "; cin >> y;

try {
cout << "x / y = " << divide(x, y) << endl;
} catch (const char* error) {
cout << "Error: " << error << endl;
}

return 0;
}

Roguelike game made with C++

File Handling in C++

Introduction to File Handling

File handling is an important part of any programming language, and C++ is no exception. With file handling, you can store and retrieve data from files, which can be saved on your computer or other storage devices. In this section, we’ll cover the basics of file handling in C++, including how to read from and write to files.

Opening and Closing Files

Before you can read from or write to a file, you first need to open it. You can do this using the “fstream” library, which stands for “file stream”. The following code demonstrates how to open a file named “example.txt” for writing:

#include 
#include 

int main() {
  std::ofstream file("example.txt");
  
  if (file.is_open()) {
    file << "Hello, World!" << std::endl;
    file.close();
  } else {
    std::cout << "Unable to open file" << std::endl;
  }
  
  return 0;
}

In this example, we’re using the “ofstream” class, which stands for “output file stream”. The “open” method is called to open the file, and the “is_open” method is used to check if the file was successfully opened. If the file was opened successfully, we can write to it using the “<<” operator, just like we would with “cout”. Finally, the “close” method is called to close the file.

Reading from Files

Reading from files is just as easy as writing to them. You can use the “ifstream” class, which stands for “input file stream”. The following code demonstrates how to open a file named “example.txt” for reading:

#include 
#include 
#include 

int main() {
  std::ifstream file("example.txt");
  std::string line;
  
  if (file.is_open()) {
    while (getline(file, line)) {
      std::cout << line << std::endl;
    }
    
    file.close();
  } else {
    std::cout << "Unable to open file" << std::endl;
  }
  
  return 0;
}

In this example, we’re using the “ifstream” class to open the file for reading. The “getline” function is used to read a line of text from the file and store it in a string. The “while” loop continues reading lines until there are no more lines to read. Finally, the “close” method is called to close the file.

C++ Idle clicked game screenshot

Introduction to the Standard Template Library (STL)

The Standard Template Library (STL) is a collection of C++ templates and algorithms that are used to perform common programming tasks. The STL is designed to be efficient, reusable, and flexible, making it a powerful tool for any C++ programmer. In this section, we will introduce some of the most commonly used STL components and show you how to use them in your own programs.

STL Containers

One of the main components of the STL are the containers. Containers are used to store collections of objects, and there are several different types of containers to choose from, including arrays, vectors, lists, and more. Here’s an example of how to use a vector:

#include <vector>

#include <iostream>

int main() {
  std::vector < int > myNumbers;
  myNumbers.push_back(1);
  myNumbers.push_back(2);
  myNumbers.push_back(3);
  for (int i: myNumbers) {
    std::cout << i << std::endl;
  }
  return 0;

In this example, we create a vector of integers, and then use the `push_back()` method to add three numbers to the vector. We then use a range-based for loop to iterate over the vector and print out each number.

Common C++ Libraries

In addition to the Standard Template Library (STL), there are several other libraries that are commonly used in C++. Here is a list of some of the most important ones:

      • Boost – A collection of libraries that provide a wide range of functionality, including things like algorithms, data structures, and networking. Boost is known for its well-designed and highly optimized libraries, making it a popular choice among C++ developers.
      • OpenCV – A library for computer vision and image processing. It provides tools for things like object detection, face recognition, and video analysis. OpenCV is widely used in the field of computer vision and has a large community of users and contributors.
      • SFML – A library for multimedia development, including graphics, audio, and network functions. SFML is a great choice for developing 2D games and other multimedia applications.
      • Qt – A cross-platform framework for developing GUI applications. Qt provides a variety of tools for building user interfaces, connecting to databases, and handling user interactions. It is widely used for developing desktop, mobile, and embedded applications.
      • Armadillo – A library for linear algebra and optimization. Armadillo provides fast and efficient implementation of common linear algebra operations, making it a popular choice for scientific computing and machine learning applications.

These are just a few of the many libraries available for C++. By using libraries, you can save time and effort by leveraging pre-existing code and solutions, and focus on developing your own unique features and functionality.

Conclusion

Congratulations! You’ve made it through a comprehensive beginner’s guide to C++. You now have a solid foundation in the basics of the language, as well as some of its advanced features. With this knowledge, you are well on your way to becoming a proficient C++ programmer.

The journey doesn’t stop here though – now it’s time to put everything you learned about C++ into practical application.

Below, we’ve included a great collection of resources for not only expanding your knowledge of C++ further, but learning how to create your first C++ projects.

We hope you check them out, and we’re looking forward to seeing what else you program with the C++ language!

Did you come across any errors in this tutorial? Please let us know by completing this form and we’ll look into it!

FREE COURSES
Python Blog Image

FINAL DAYS: Unlock coding courses in Unity, Godot, Unreal, Python and more.