C++ Online Tutorial

C++

C++ is a popular programming language.

C++ is used to create computer programs, and is one of the most used language in game development.

What is C++?

C++ is a cross-platform language that can be used to create high-performance applications.

C++ was developed by BjarneStroustrup, as an extension to the C language.

C++ gives programmers a high level of control over system resources and memory.

The language was updated 4 major times in 2011, 2014, 2017, and 2020 to C++11, C++14, C++17, C++20.

Why Use C++

C++ is one of the world’s most popular programming languages.

C++ can be found in today’s operating systems, Graphical User Interfaces, and embedded systems.

C++ is an object-oriented programming language which gives a clear structure to programs and allows code to be reused, lowering development costs.

C++ is portable and can be used to develop applications that can be adapted to multiple platforms.

C++ is fun and easy to learn!

As C++ is close to C# and Java, it makes it easy for programmers to switch to C++ or vice versa.

Difference between C and C++

C++ was developed as an extension of C, and both languages have almost the same syntax.

The main difference between C and C++ is that C++ support classes and objects, while C does not.

#include <iostream>

using namespace std;

int main() {

cout<< “Hello World!”;

return 0;

}

C++ Comments

Comments can be used to explain C++ code, and to make it more readable. It can also be used to prevent execution when testing alternative code. Comments can be singled-lined or multi-lined.

Single-line Comments

Single-line comments start with two forward slashes (//).

Any text between // and the end of the line is ignored by the compiler (will not be executed).

This example uses a single-line comment before a line of code:

// This is a comment
cout<< “Hello World!”;

or

cout<< “Hello World!”; // This is a comment

C++ Multi-line Comments

Multi-line comments start with /* and ends with */.

Any text between /* and */ will be ignored by the compiler:

Example

/* The code below will print the words Hello World!
to the screen, and it is amazing */
cout<< “Hello World!”;

C++ Variables

Variables are containers for storing data values.

In C++, there are different types of variables (defined with different keywords), for example:

  • int – stores integers (whole numbers), without decimals, such as 123 or -123
  • double – stores floating point numbers, with decimals, such as 19.99 or -19.99
  • char – stores single characters, such as ‘a’ or ‘B’. Char values are surrounded by single quotes
  • string – stores text, such as “Hello World”. String values are surrounded by double quotes
  • bool – stores values with two states: true or false

Declaring (Creating) Variables

To create a variable, specify the type and assign it a value:

Syntax

type variableName = value;

#include <iostream>

using namespace std;

int main() {

intmyNum = 15;

cout<<myNum;

  return 0;

}

#include <iostream>

using namespace std;

int main() {

intmyNum = 15;   // Now myNum is 15

myNum = 10;       // Now myNum is 10

cout<<myNum;

  return 0;

}

Declare Many Variables

To declare more than one variable of the same type, use a comma-separated list:

#include <iostream>

using namespace std;

int main() {

int x = 5, y = 6, z = 50; 

cout<< x + y + z;

  return 0;

}

C++ Identifiers

All C++ variables must be identified with unique names.

These unique names are called identifiers.

Identifiers can be short names (like x and y) or more descriptive names (age, sum, totalVolume).

Note: It is recommended to use descriptive names in order to create understandable and maintainable code:

#include <iostream>

using namespace std;

int main() {

  // Good name

intminutesPerHour = 60;

  // OK, but not so easy to understand what m actually is

int m = 60;

cout<<minutesPerHour<< “\n”;

cout<< m;

  return 0;

}

Constants

When you do not want others (or yourself) to override existing variable values, use the const keyword (this will declare the variable as “constant”, which means unchangeable and read-only):

#include <iostream>

using namespace std;

int main() {

constintmyNum = 15;

myNum = 10;

cout<<myNum;

  return 0;

}

C++ User Input

You have already learned that cout is used to output (print) values. Now we will use cin to get user input.

cin is a predefined variable that reads data from the keyboard with the extraction operator (>>).

In the following example, the user can input a number, which is stored in the variable x. Then we print the value of x:

#include <iostream>

using namespace std;

int main() {

int x;

cout<< “Type a number: “; // Type a number and press enter

cin>> x; // Get user input from the keyboard

cout<< “Your number is: ” << x;

  return 0;

}

Creating a Simple Calculator

In this example, the user must input two numbers. Then we print the sum by calculating (adding) the two numbers:

#include <iostream>

using namespace std;

int main() {

int x, y;

int sum;

cout<< “Type a number: “;

cin>> x;

cout<< “Type another number: “;

cin>> y;

  sum = x + y;

cout<< “Sum is: ” << sum;

  return 0;

}

C++ Data Types

As explained in the Variables chapter, a variable in C++ must be a specified data type:

#include <iostream>

#include <string>

using namespace std;

int main () {

  // Creating variables

intmyNum = 5;               // Integer (whole number)

  float myFloatNum = 5.99;     // Floating point number

  double myDoubleNum = 9.98;   // Floating point number

  char myLetter = ‘D’;         // Character

  bool myBoolean = true;       // Boolean

  string myString = “Hello”;   // String

  // Print variable values

cout<< “int: ” <<myNum<< “\n”;

cout<< “float: ” <<myFloatNum<< “\n”;

cout<< “double: ” <<myDoubleNum<< “\n”;

cout<< “char: ” <<myLetter<< “\n”;

cout<< “bool: ” <<myBoolean<< “\n”;

cout<< “string: ” <<myString<< “\n”;

  return 0;

}

C++ Operators

Operators are used to perform operations on variables and values.

In the example below, we use the + operator to add together two values:

#include <iostream>

using namespace std;

int main() {

int sum1 = 100 + 50;        // 150 (100 + 50)

int sum2 = sum1 + 250;      // 400 (150 + 250)

int sum3 = sum2 + sum2;     // 800 (400 + 400)

cout<< sum1 << “\n”;

cout<< sum2 << “\n”;

cout<< sum3;

  return 0;

}

Arithmetic Operators

Arithmetic operators are used to perform common mathematical operations.

#include <iostream>

using namespace std;

int main() {

int x = 5;

int y = 3;

cout<< x + y;

  return 0;

}

Assignment Operators

Assignment operators are used to assign values to variables.

In the example below, we use the assignment operator (=) to assign the value 10 to a variable called x:

#include <iostream>

using namespace std;

int main() {

int x = 10;

cout<< x;

  return 0;

}

Comparison Operators

Comparison operators are used to compare two values.

Note: The return value of a comparison is either true (1) or false (0).

In the following example, we use the greater than operator (>) to find out if 5 is greater than 3:

#include <iostream>

using namespace std;

int main() {

int x = 5;

int y = 3;

cout<< (x > y); // returns 1 (true) because 5 is greater than 3

  return 0;

}

Logical Operators

Logical operators are used to determine the logic between variables or values:

#include <iostream>

using namespace std;

int main() {

int x = 5;

int y = 3;

cout<< (x > 3 && x < 10); // returns true (1) because 5 is greater than 3 AND 5 is less than 10

  return 0;

}

Operator

Name

Description

Example

Try it

&& 

Logical and

Returns true if both statements are true

x < 5 &&  x < 10

Try it »

|| 

Logical or

Returns true if one of the statements is true

x < 5 || x < 4

Try it »

!

Logical not

Reverse the result, returns false if the result is true

!(x < 5 && x < 10)

 

C++ Strings

Strings are used for storing text.

A string variable contains a collection of characters surrounded by double quotes:

#include <iostream>

#include <string>

using namespace std;

int main() {

  string greeting = “Hello”;

cout<< greeting;

  return 0;

}

String Concatenation

The + operator can be used between strings to add them together to make a new string. This is called concatenation:

#include <iostream>

#include <string>

using namespace std;

int main () {

  string firstName = “John “;

  string lastName = “Doe”;

  string fullName = firstName + lastName;

cout<<fullName;

  return 0;

}

Adding Numbers and Strings

WARNING!

C++ uses the + operator for both addition and concatenation.

Numbers are added. Strings are concatenated.

If you add two numbers, the result will be a number:

#include <iostream>

using namespace std;

int main () {

int x = 10;

int y = 20;

int z = x + y;

cout<< z;

  return 0;

}

String Length

To get the length of a string, use the length() function:

#include <iostream>

#include <string>

using namespace std;

int main() {

  string txt = “ABCDEFGHIJKLMNOPQRSTUVWXYZ”;

cout<< “The length of the txt string is: ” <<txt.length();

  return 0;

}

Access Strings

You can access the characters in a string by referring to its index number inside square brackets [].

This example prints the first character in myString:

#include <iostream>

#include <string>

using namespace std;

int main() {

  string myString = “Hello”;

cout<<myString[0];

  return 0;

}

User Input Strings

It is possible to use the extraction operator >> on cin to display a string entered by a user:

#include <iostream>

#include <string>

using namespace std;

int main() {

  string fullName;

cout<< “Type your full name: “;

getline (cin, fullName);

cout<< “Your name is: ” <<fullName;

  return 0;

}

C++ Math

C++ has many functions that allows you to perform mathematical tasks on numbers.

Max and min

The max(x,y) function can be used to find the highest value of x and y:

#include <iostream>

using namespace std;

int main() {

cout<< max(5, 10);

  return 0;

}

C++ <cmath> Header

Other functions, such as sqrt (square root), round (rounds a number) and log (natural logarithm), can be found in the <cmath> header file:

#include <iostream>

#include <cmath>

using namespace std;

int main() {

cout<<sqrt(64) << “\n”;

cout<< round(2.6) << “\n”;

cout<< log(2) << “\n”;

  return 0;

}

C++ Booleans

Very often, in programming, you will need a data type that can only have one of two values, like:

  • YES / NO
  • ON / OFF
  • TRUE / FALSE

For this, C++ has a bool data type, which can take the values true (1) or false (0).

Boolean Values

A boolean variable is declared with the bool keyword and can only take the values true or false:

#include <iostream>

using namespace std;

int main() {

  bool isCodingFun = true;

  bool isFishTasty = false;

cout<<isCodingFun<< “\n”;

cout<<isFishTasty;

  return 0;

}

From the example above, you can read that a true value returns 1, and false returns 0.

However, it is more common to return boolean values from boolean expressions

Boolean Expression

Boolean expression is a C++ expression that returns a boolean value: 1 (true) or 0 (false).

You can use a comparison operator, such as the greater than (>) operator to find out if an expression (or a variable) is true:

#include <iostream>

using namespace std;

int main() {

int x = 10;

int y = 9;

cout<< (x > y);

  return 0;

}

C++ Conditions and If Statements

C++ supports the usual logical conditions from mathematics:

  • Less than: a < b
  • Less than or equal to: a <= b
  • Greater than: a > b
  • Greater than or equal to: a >= b
  • Equal to a == b
  • Not Equal to: a != b

You can use these conditions to perform different actions for different decisions.

C++ has the following conditional statements:

  • Use if to specify a block of code to be executed, if a specified condition is true
  • Use else to specify a block of code to be executed, if the same condition is false
  • Use else if to specify a new condition to test, if the first condition is false
  • Use switch to specify many alternative blocks of code to be executed

The if Statement

Use the if statement to specify a block of C++ code to be executed if a condition is true.

Syntax

if (condition) {
  // block of code to be executed if the condition is true
}

Note: that if is in lowercase letters. Uppercase letters (If or IF) will generate an error.

#include <iostream>

using namespace std;

int main() {

  if (20 > 18) {

cout<< “20 is greater than 18”;

  } 

  return 0;

}

+++++++++++++

#include <iostream>

using namespace std;

int main() {

int x = 20;

int y = 18;

  if (x > y) {

cout<< “x is greater than y”;

  }  

  return 0;

}

The else Statement

Use the else statement to specify a block of code to be executed if the condition is false.

Syntax

if (condition) {
  // block of code to be executed if the condition is true
} else {
  // block of code to be executed if the condition is false
}

#include <iostream>

using namespace std;

int main() {

int time = 20;

  if (time < 18) {

cout<< “Good day.”;

  } else {

cout<< “Good evening.”;

  }

  return 0;

}

The else if Statement

Use the else if statement to specify a new condition if the first condition is false.

Syntax

if (condition1) {
  // block of code to be executed if condition1 is true
} else if (condition2) {
  // block of code to be executed if the condition1 is false and condition2 is true

} else if (condition3) {
  // block of code to be executed if the condition1 is false and condition2 is true
} else {
  // block of code to be executed if the condition1 is false and condition2 is false
}

#include <iostream>

using namespace std;

int main() {

int time = 22;

  if (time < 10) {

cout<< “Good morning.”;

  } else if (time < 20) {

cout<< “Good day.”;

  } else {

cout<< “Good evening.”;

  }

  return 0;

}

Short Hand If…Else (Ternary Operator)

There is also a short-hand if else, which is known as the ternary operator because it consists of three operands. It can be used to replace multiple lines of code with a single line. It is often used to replace simple if else statements:

Syntax

variable = (condition) ? expressionTrue : expressionFalse;

#include <iostream>

using namespace std;

int main() {

int time = 20;

  if (time < 18) {

cout<< “Good day.”;

  } else {

cout<< “Good evening.”;

  }

  return 0;

}

 

#include <iostream>

#include <string>

using namespace std;

int main() {

int time = 20;

  string result = (time < 18) ? “Good day.” : “Good evening.”;

cout<< result;

  return 0;

}

C++ Switch Statements

Use the switch statement to select one of many code blocks to be executed.

Syntax

switch(expression) {
  case x:
    // code block
    break;
  case y:
    // code block
    break;
  default:
    // code block
}

++++++++++

This is how it works:

  • The switch expression is evaluated once
  • The value of the expression is compared with the values of each case
  • If there is a match, the associated block of code is executed
  • The break and default keywords are optional, and will be described later in this chapter

The example below uses the weekday number to calculate the weekday name:

#include <iostream>

using namespace std;

int main() {

int day = 4;

  switch (day) {

  case 1:

cout<< “Monday”;

    break;

  case 2:

cout<< “Tuesday”;

    break;

  case 3:

cout<< “Wednesday”;

    break;

  case 4:

cout<< “Thursday”;

    break;

  case 5:

cout<< “Friday”;

    break;

  case 6:

cout<< “Saturday”;

    break;

  case 7:

cout<< “Sunday”;

    break;

  }

  return 0;

}

The break Keyword

When C++ reaches a break keyword, it breaks out of the switch block.

This will stop the execution of more code and case testing inside the block.

When a match is found, and the job is done, it’s time for a break. There is no need for more testing.

The default Keyword

The default keyword specifies some code to run if there is no case match:

#include <iostream>

using namespace std;

int main() {

int day = 4;

  switch (day) {

    case 6:

cout<< “Today is Saturday”;

      break;

    case 7:

cout<< “Today is Sunday”;

      break;

    default:

cout<< “Looking forward to the Weekend”;

  }

  return 0;

}

C++ Loops

Loops can execute a block of code as long as a specified condition is reached.

Loops are handy because they save time, reduce errors, and they make code more readable.

C++ While Loop

The while loop loops through a block of code as long as a specified condition is true:

Syntax

while (condition) {
  // code block to be executed
}

In the example below, the code in the loop will run, over and over again, as long as a variable (i) is less than 5:

#include <iostream>

using namespace std;

int main() {

int i = 0;

  while (i < 5) {

cout<< i << “\n”;

    i++;

  }

  return 0;

}

Note: Do not forget to increase the variable used in the condition, otherwise the loop will never end!

The Do/While Loop

The do/while loop is a variant of the while loop. This loop will execute the code block once, before checking if the condition is true, then it will repeat the loop as long as the condition is true.

Syntax

do {
  // code block to be executed
}
while (condition);

 

#include <iostream>

using namespace std;

int main() {

int i = 0;

  do {

cout<< i << “\n”;

    i++;

  }

  while (i < 5);

  return 0;

}

C++ For Loop

When you know exactly how many times you want to loop through a block of code, use the for loop instead of a while loop:

Syntax

for (statement 1; statement 2; statement 3) {
  // code block to be executed
}

Statement 1 is executed (one time) before the execution of the code block.

Statement 2 defines the condition for executing the code block.

Statement 3 is executed (every time) after the code block has been executed.

The example below will print the numbers 0 to 4:

#include <iostream>

using namespace std;

int main() {

  for (int i = 0; i < 5; i++) {

cout<< i << “\n”;

  }

  return 0;

}

Example explained

Statement 1 sets a variable before the loop starts (int i = 0).

Statement 2 defines the condition for the loop to run (i must be less than 5). If the condition is true, the loop will start over again, if it is false, the loop will end.

Statement 3 increases a value (i++) each time the code block in the loop has been executed.

C++ Break

You have already seen the break statement used in an earlier chapter of this tutorial. It was used to “jump out” of a switch statement.

The break statement can also be used to jump out of a loop.

This example jumps out of the loop when i is equal to 4:

#include <iostream>

using namespace std;

int main() {

  for (int i = 0; i < 10; i++) {

    if (i == 4) {

      break;

    }

cout<< i << “\n”;

  }

  return 0;

}

C++ Continue

The continue statement breaks one iteration (in the loop), if a specified condition occurs, and continues with the next iteration in the loop.

This example skips the value of 4:

#include <iostream>

using namespace std;

int main() {

  for (int i = 0; i < 10; i++) {

    if (i == 4) {

      continue;

    }

cout<< i << “\n”;

  }  

  return 0;

}

Break and Continue in While Loop

You can also use break and continue in while loops:

#include <iostream>

using namespace std;

int main() {

int i = 0;

  while (i < 10) {

cout<< i << “\n”;

    i++;

    if (i == 4) {

      break;

    }

  }

  return 0;

}

C++ Arrays

Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value.

To declare an array, define the variable type, specify the name of the array followed by square brackets and specify the number of elements it should store:

string cars[4];

We have now declared a variable that holds an array of four strings. To insert values to it, we can use an array literal – place the values in a comma-separated list, inside curly braces:

string cars[4] = {“Volvo”, “BMW”, “Ford”, “Mazda”};

To create an array of three integers, you could write:

int myNum[3] = {10, 20, 30};

Access the Elements of an Array

You access an array element by referring to the index number inside square brackets [].

This statement accesses the value of the first element in cars:

#include <iostream>

#include <string>

using namespace std;

int main() {

  string cars[4] = {“Volvo”, “BMW”, “Ford”, “Mazda”};

cout<< cars[0];

  return 0;

}

Loop Through an Array

You can loop through the array elements with the for loop.

The following example outputs all elements in the cars array:

#include <iostream>

#include <string>

using namespace std;

int main() {

  string cars[4] = {“Volvo”, “BMW”, “Ford”, “Mazda”};

  for (int i = 0; i < 4; i++) {

cout<< cars[i] << “\n”;

  }

  return 0;

}

 

#include <iostream>

#include <string>

using namespace std;

int main() {

  string cars[4] = {“Volvo”, “BMW”, “Ford”, “Mazda”};

  for (int i = 0; i < 4; i++) {

cout<< i << “: ” << cars[i] << “\n”;

  }

  return 0;

}

C++ Structures

Structures (also called structs) are a way to group several related variables into one place. Each variable in the structure is known as a member of the structure.

Unlike an array, a structure can contain many different data types (int, string, bool, etc.).

Create a Structure

To create a structure, use the struct keyword and declare each of its members inside curly braces.

After the declaration, specify the name of the structure variable (myStructure in the example below):

struct {             // Structure declaration
  int myNum;         // Member (int variable)
  string myString;   // Member (string variable)
} myStructure;       // Structure variable

Access Structure Members

To access members of a structure, use the dot syntax (.):

#include <iostream>

#include <string>

using namespace std;

int main() {

struct {

intmyNum;

    string myString;

  } myStructure;

myStructure.myNum = 1;

myStructure.myString = “Hello World!”;

cout<<myStructure.myNum<< “\n”;

cout<<myStructure.myString<< “\n”;

  return 0;

}

C++ What is OOP?

OOP stands for Object-Oriented Programming.

Procedural programming is about writing procedures or functions that perform operations on the data, while object-oriented programming is about creating objects that contain both data and functions.

Object-oriented programming has several advantages over procedural programming:

  • OOP is faster and easier to execute
  • OOP provides a clear structure for the programs
  • OOP helps to keep the C++ code DRY “Don’t Repeat Yourself”, and makes the code easier to maintain, modify and debug
  • OOP makes it possible to create full reusable applications with less code and shorter development time

C++ What are Classes and Objects?

Classes and objects are the two main aspects of object-oriented programming.

Look at the following illustration to see the difference between class and objects:

Create a Class

To create a class, use the class keyword:

Example

Create a class called “MyClass”:

class MyClass {       // The class
  public:             // Access specifier
    int myNum;        // Attribute (int variable)
    string myString;  // Attribute (string variable)
};

Example explained
  • The class keyword is used to create a class called MyClass.
  • The public keyword is an access specifier, which specifies that members (attributes and methods) of the class are accessible from outside the class. You will learn more about access specifiers later.
  • Inside the class, there is an integer variable myNum and a string variable myString. When variables are declared within a class, they are called attributes.
  • At last, end the class definition with a semicolon ;.

Create an Object

In C++, an object is created from a class. We have already created the class named MyClass, so now we can use this to create objects.

To create an object of MyClass, specify the class name, followed by the object name.

To access the class attributes (myNum and myString), use the dot syntax (.) on the object:

Example

Create an object called “myObj” and access the attributes:

class MyClass {       // The class
  public:             // Access specifier
    int myNum;        // Attribute (int variable)
    string myString;  // Attribute (string variable)
};

int main() {
  MyClass myObj;  // Create an object of MyClass

  // Access attributes and set values
  myObj.myNum = 15; 
  myObj.myString = “Some text”;

  // Print attribute values
  cout<<myObj.myNum << “\n”;
  cout<<myObj.myString;
  return 0;
}

Multiple Objects

You can create multiple objects of one class:

Example

// Create a Car class with some attributes
class Car {
  public:
    string brand;   
    string model;
    int year;
};

int main() {
  // Create an object of Car
  Car carObj1;
  carObj1.brand = “BMW”;
  carObj1.model = “X5”;
  carObj1.year = 1999;

  // Create another object of Car
  Car carObj2;
  carObj2.brand = “Ford”;
  carObj2.model = “Mustang”;
  carObj2.year = 1969;

  // Print attribute values
  cout<< carObj1.brand << ” ” << carObj1.model << ” ” << carObj1.year << “\n”;
  cout<< carObj2.brand << ” ” << carObj2.model << ” ” << carObj2.year << “\n”;
  return 0;
}

Encapsulation

The meaning of Encapsulation, is to make sure that “sensitive” data is hidden from users. To achieve this, you must declare class variables/attributes as private (cannot be accessed from outside the class). If you want others to read or modify the value of a private member, you can provide public get and set methods.

Access Private Members

To access a private attribute, use public “get” and “set” methods:

#include <iostream>

using namespace std;

class Employee {

  private:

int salary;

  public:

    void setSalary(int s) {

      salary = s;

    }

intgetSalary() {

      return salary;

    }

};

int main() {

  Employee myObj;

myObj.setSalary(50000);

cout<<myObj.getSalary();

  return 0;

}

Inheritance

In C++, it is possible to inherit attributes and methods from one class to another. We group the “inheritance concept” into two categories:

  • derived class (child) – the class that inherits from another class
  • base class (parent) – the class being inherited from

To inherit from a class, use the : symbol.

In the example below, the Car class (child) inherits the attributes and methods from the Vehicle class (parent):

#include <iostream>

#include <string>

using namespace std;

// Base class

class Vehicle {

  public:

    string brand = “Ford”;

    void honk() {

cout<< “Tuut, tuut! \n” ;

    }

};

// Derived class

class Car: public Vehicle {

  public:

    string model = “Mustang”;

};

int main() {

  Car myCar;

myCar.honk();

cout<<myCar.brand + ” ” + myCar.model;

  return 0;

}