C++ is a popular programming language.
C++ is used to create computer programs, and is one of the most used language in game development.
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.
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.
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;
}
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 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
Multi-line comments start with /* and ends with */.
Any text between /* and */ will be ignored by the compiler:
/* 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:
To create a variable, specify the type and assign it a value:
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;
}
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;
}
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;
}
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;
}
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;
}
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;
}
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;
}
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 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 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 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 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 | |
|| | Logical or | Returns true if one of the statements is true | x < 5 || x < 4 | |
! | Logical not | Reverse the result, returns false if the result is true | !(x < 5 && x < 10) |
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;
}
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;
}
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;
}
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;
}
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;
}
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++ has many functions that allows you to perform mathematical tasks on numbers.
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;
}
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:
For this, C++ has a bool data type, which can take the values true (1) or false (0).
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
A 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:
You can use these conditions to perform different actions for different decisions.
C++ has the following conditional statements:
Use the if statement to specify a block of C++ code to be executed if a condition is true.
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;
}
Use the else statement to specify a block of code to be executed if the condition is false.
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;
}
Use the else if statement to specify a new condition if the first condition is false.
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;
}
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:
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;
}
Use the switch statement to select one of many code blocks to be executed.
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
++++++++++
This is how it works:
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;
}
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 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;
}
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.
The while loop loops through a block of code as long as a specified condition is true:
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 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.
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;
}
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:
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;
}
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.
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;
}
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;
}
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;
}
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};
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;
}
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;
}
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.).
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
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;
}
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:
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:
To create a class, use the class keyword:
Create a class called “MyClass”:
class MyClass { // The class
public: // Access specifier
int myNum; // Attribute (int variable)
string myString; // Attribute (string variable)
};
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:
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;
}
You can create multiple objects of one class:
// 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;
}
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.
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:
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;
}