What Is C++?
What Is C++?
What is C++?
C++ is a cross-platform language that can be used to create high-performance
applications.
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++ can be found in today's operating systems, Graphical User Interfaces, and
embedded systems.
C++ is portable and can be used to develop applications that can be adapted to
multiple platforms.
C++ Syntax
Let's break up the following code to understand it better:
Example
#include <iostream>
using namespace std;
int main() {
cout << "Hello World!";
return 0;
}
Example explained
Line 1: #include <iostream> is a header file library that lets us work with
input and output objects, such as cout (used in line 5). Header files add
functionality to C++ programs.
Line 2: using namespace std means that we can use names for objects and
variables from the standard library.
Example
#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).
C++ Variables
Variables are containers for storing data values.
In C++, there are different types of variables (defined with different keywords),
for example:
Constants
When you do not want others (or yourself) to change existing variable values,
use the const keyword (this will declare the variable as "constant", which
means unchangeable and read-only):
Example
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:
Example
int x;
cout << "Type a number: "; // Type a number and press enter
cout << "Your number is: " << x; // Display the input value
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:
Example
Assignment Operators
Assignment operators are used to assign values to variables.
= x=5 x=5
+= x += 3 x=x+3
-= x -= 3 x=x-3
*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3
Comparison Operators
Comparison operators are used to compare two values (or variables). This is
important in programming, because it helps us to find answers and make
decisions.
Operator Name Exampl
e
== Equal to x == y
!= Not equal x != y
Logical Operators
As with comparison operators, you can also test for true (1) or false (0) values
with logical operators.
Logical operators are used to determine the logic between variables or values:
C++ Strings
Strings are used for storing text.
Example
Create a variable of type string and assign it a value:
To use strings, you must include an additional header file in the source code,
the <string> library:
Example
#include <string>
String Concatenation
The + operator can be used between strings to add them together to make a
new string. This is called concatenation:
Example
string firstName = "John ";
String Length
To get the length of a string, use the length() function:
Access Strings
You can access the characters in a string by referring to its index number inside
square brackets [].
Example
string myString = "Hello";
myString[0] = 'J';
string txt = "We are the so-called "Vikings" from the north.";
The solution to avoid this problem, is to use the backslash escape character.
The backslash (\) escape character turns special characters into string
characters:
Example
string txt = "We are the so-called \"Vikings\" from the north.";
strcpy(s1, s2);
strcat(s1, s2);
strcmp(s1, s2);
Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0 if
s1>s2.
strchr(s1, ch);
strstr(s1, s2);
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:
Example
And the min(x,y) function can be used to find the lowest value of x and y:
Example
Example
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) {
else {
The example below uses the weekday number to calculate the weekday name:
Example
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;
}
// Outputs "Thursday" (day 4)
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.
Syntax
while (condition) {
int i = 0;
do {
cout << i << "\n";
i++;
}
while (i < 5);
Example
for (int i = 0; i < 5; i++) {
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.
if (i == 4) {
break;
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.
Example
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];
Result:
20
Multi-Dimensional Arrays
A multi-dimensional array is an array of arrays.
To declare a multi-dimensional array, define the variable type, specify the name
of the array followed by square brackets which specify how many elements the
main array has, followed by another set of square brackets which indicates how
many elements the sub-arrays have:
string letters[2][4];
As with ordinary arrays, you can insert values with an array literal - a
comma-separated list inside curly braces. In a multi-dimensional array, each
element in an array literal is another array literal.
string letters[2][4] = {
};
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
Example
struct {
int myNum;
string myString;
} myStructure;
// Assign values to members of myStructure
myStructure.myNum = 1;
Creating Pointers
You learned from the previous chapter, that we can get the memory address of
a variable by using the & operator:
Example
Example
string food = "Pizza";
// Access the memory address of food and output its value (Pizza)
*ptr = "Hamburger";
Functions are used to perform certain actions, and they are important for
reusing code: Define the code once, and use it many times.
Create a Function
C++ provides some pre-defined functions, such as main(), which is used to
execute code. But you can also create your own functions to perform certain
actions.
Example Explained
● myFunction() is the name of the function
● void means that the function does not have a return value. You will learn
more about return values later in the next chapter
● inside the function (the body), add code that defines what the function
should do
Call a Function
Declared functions are not executed immediately. They are "saved for later
use", and will be executed later, when they are called.
To call a function, write the function's name followed by two parentheses () and
a semicolon ;
Example
Inside main, call myFunction():
// Create a function
void myFunction() {
int main() {
return 0;
Parameters are specified after the function name, inside the parentheses. You
can add as many parameters as you want, just separate them with a comma:
void myFunction(string fname) {
int main() {
myFunction("Liam");
myFunction("Jenny");
myFunction("Anja");
return 0;
Pass By Reference
In the examples from the previous page, we used normal variables when we
passed parameters to a function. You can also pass a reference to the function.
This can be useful when you need to change the value of the arguments:
Example
void swapNums(int &x, int &y) {
int z = x;
x = y;
y = z;
int main() {
// Call the function, which will change the values of firstNum and
secondNum
swapNums(firstNum, secondNum);
return 0;
Example
void myFunction(int myNumbers[5]) {
for (int i = 0; i < 5; i++) {
int main() {
myFunction(myNumbers);
return 0;
Function Overloading
With function overloading, multiple functions can have the same name with
different parameters:
Example
int myFunction(int x)
float myFunction(float x)
Consider the following example, which have two functions that add numbers of
different type:
Example
int plusFuncInt(int x, int y) {
return x + y;
return x + y;
int main() {
return 0;
}
Recursion
Recursion is the technique of making a function call itself. This technique
provides a way to break complicated problems down into simple problems which
are easier to solve.
Recursion may be a bit difficult to understand. The best way to figure out how it
works is to experiment with it.
Recursion Example
Adding two numbers together is easy to do, but adding a range of numbers is
more complicated. In the following example, recursion is used to add a range of
numbers together by breaking it down into the simple task of adding two
numbers:
Example
int sum(int k) {
if (k > 0) {
} else {
return 0;
int main() {
return 0;
}
C++ Files
The fstream library allows us to work with files.
To use the fstream library, include both the standard <iostream> AND the
<fstream> header file:
Example
#include <iostream>
#include <fstream>
There are three classes included in the fstream library, which are used to
create, write or read files:
Class Description
Example
#include <iostream>
#include <fstream>
int main() {
ofstream MyFile("filename.txt");
MyFile.close();
Read a File
To read from a file, use either the ifstream or fstream class, and the
name of the file.
Note that we also use a while loop together with the getline() function
(which belongs to the ifstream class) to read the file line by line, and to
print the content of the file:
Example
// Create a text string, which is used to output the text file
string myText;
ifstream MyReadFile("filename.txt");
// Use a while loop together with the getline() function to read the
file line by line
MyReadFile.close();
C++ Exceptions
When executing C++ code, different errors can occur: coding errors
made by the programmer, errors due to wrong input, or other
unforeseeable things.
When an error occurs, C++ will normally stop and generate an error
message. The technical term for this is: C++ will throw an exception
(throw an error).
The try statement allows you to define a block of code to be tested for
errors while it is being executed.
try {
int age = 15;
if (age >= 18) {
cout << "Access granted - you are old enough.";
} else {
throw (age);
}
}
catch (int myNum) {
cout << "Access denied - You must be at least 18 years old.\n";
cout << "Age is: " << myNum;
}
Example
try {
} else {
throw 505;
catch (...) {
Tip: The "Don't Repeat Yourself" (DRY) principle is about reducing the repetition
of code. You should extract out the codes that are common for the application,
and place them at a single place and reuse them instead of repeating it.
Look at the following illustration to see the difference between class and
objects:
class
Fruit
objects
Apple
Banana
Mango
Another example:
class
Car
objects
Volvo
Audi
Toyota
So, a class is a template for objects, and an object is an instance of a class.
When the individual objects are created, they inherit all the variables and
functions from the class.
C++ Classes/Objects
C++ is an object-oriented programming language.
Everything in C++ is associated with classes and objects, along with its
attributes and methods. For example: in real life, a car is an object. The car has
attributes, such as weight and color, and methods, such as drive and brake.
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
};
int main() {
myObj.myNum = 15;
return 0;
Class Methods
Methods are functions that belongs to the class.
Inside Example
class MyClass { // The class
}
};
int main() {
return 0;
Outside Example
class MyClass { // The class
};
void MyClass::myMethod() {
int main() {
return 0;
void display()
{
cout<<endl<<rno<<"\t"<<name<<"\t"<<fee;
}
};
int main()
{
student s; //constructor gets called automatically when we create
the object of the class
s.display();
return 0;
Types of Constructors
CPP
// Cpp program to illustrate the
// concept of Constructors
#include <iostream>
class construct {
public:
int a, b;
// Default Constructor
construct()
a = 10;
b = 20;
};
int main()
construct c;
cout << "a: " << c.a << endl << "b: " <<
c.b;
return 1;
Output
a: 10
b: 20
class Point {
private:
int x, y;
public:
// Parameterized Constructor
x = x1;
y = y1;
};
int main()
// Constructor called
return 0;
Output
p1.x = 10, p1.y = 15
Copy Constructor:
#include <iostream>
using namespace std;
class Sample
{
int id;
public:
void init(int x)
{
id=x;
}
Sample(){} //default constructor with empty body
Output
ID=10
ID=10
Destructor:
~Test()
{
cout << "\n No. of Object destroyed:\t" << count;
--count;
}
};
main()
{
Test t, t1, t2, t3;
return 0;
}
No. of Object created: 1
No. of Object created: 2
No. of Object created: 3
No. of Object created: 4
No. of Object destroyed: 4
No. of Object destroyed: 3
No. of Object destroyed: 2
No. of Object destroyed: 1
Access Specifiers
he public keyword is an access specifier. Access specifiers define how
the members (attributes and methods) of a class can be accessed. In
the example above, the members are public - which means that they
can be accessed and modified from outside the code.
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.
Example
#include <iostream>
using namespace std;
class Employee {
private:
// Private attribute
int salary;
public:
// Setter
void setSalary(int s) {
salary = s;
}
// Getter
int getSalary() {
return salary;
}
};
int main() {
Employee myObj;
myObj.setSalary(50000);
cout << myObj.getSalary();
return 0;
}
Why Encapsulation?
● It is considered good practice to declare your class attributes as
private (as often as you can). Encapsulation ensures better
control of your data, because you (or others) can change one part
of the code without affecting other parts
● Increased security of data
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
In the example below, the Car class (child) inherits the attributes and methods
from the Vehicle class (parent):
// 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;
}
Multilevel Inheritance
A class can also be derived from one class, which is already derived
from another class.
Example
// Base class (parent)
class MyClass {
public:
void myFunction() {
cout << "Some content in parent class." ;
}
};
int main() {
MyGrandChild myObj;
myObj.myFunction();
return 0;
}
Multiple Inheritance
A class can also be derived from more than one base class, using a
comma-separated list:
Example
// Base class
class MyClass {
public:
void myFunction() {
cout << "Some content in parent class." ;
}
};
// Derived class
class MyChildClass: public MyClass, public MyOtherClass {
};
int main() {
MyChildClass myObj;
myObj.myFunction();
myObj.myOtherFunction();
return 0;
}
Polymorphism
he word “polymorphism” means having many forms. In simple words, we can
define polymorphism as the ability of a message to be displayed in more than
one form.
A real-life example of polymorphism is a person who at the same time can have
different characteristics. A man at the same time is a father, a husband, and an
employee.
Types of Polymorphism
● Compile-time Polymorphism.
● Runtime Polymorphism.
Types of Polymorphism
1. Compile-Time Polymorphism
This type of polymorphism is achieved by function overloading or operator
overloading.
A. Function Overloading
When there are multiple functions with the same name but different parameters,
then the functions are said to be overloaded, hence this is known as Function
Overloading. Functions can be overloaded by changing the number of
arguments or/and changing the type of arguments. In simple terms, it is a
feature of object-oriented programming providing many functions to have the
same name but distinct parameters when numerous tasks are listed under one
function name. There are certain Rules of Function Overloading that should be
followed while overloading a function.
#include <bits/stdc++.h>
// Driver code
int main()
{
Geeks obj1;
Operator Overloading
C++ has the ability to provide the operators with a special meaning for a data
type, this ability is known as operator overloading. For example, we can make
use of the addition operator (+) for string class to concatenate two strings. We
know that the task of this operator is to add two operands. So a single operator
‘+’, when placed between integer operands, adds them and when placed
between string operands, concatenates them.
Below is the C++ program to demonstrate operator overloading:
#include <iostream>
using namespace std;
class Complex {
private:
int real, imag;
public:
Complex(int r = 0,
int i = 0)
{
real = r;
imag = i;
}
// Driver code
int main()
{
Complex c1(10, 5), c2(2, 4);
Runtime Polymorphism
This type of polymorphism is achieved by Function Overriding. Late binding
and dynamic polymorphism are other names for runtime polymorphism. The
function call is resolved at runtime in runtime polymorphism. In contrast, with
compile time polymorphism, the compiler determines which function call to bind
to the object after deducing it at runtime.
A. Function Overriding
Function Overriding occurs when a derived class has a definition for one of the
member functions of the base class. That base function is said to be overridden.
#include <bits/stdc++.h>
using namespace std;
class base {
public:
virtual void print()
{
cout << "print base class" <<
endl;
}
void show()
{
cout << "show base class" <<
endl;
}
};
void show()
{
cout << "show derived class" <<
endl;
}
};
// Driver code
int main()
{
base* bptr;
derived d;
bptr = &d;
return 0;
}
Output
print derived class
show base class
A complete example:
A pure virtual function is implemented by classes which are derived from a
Abstract class. Following is a simple example to demonstrate the same.
#include<iostream>
using namespace std;
class Base
{
int x;
public:
virtual void fun() = 0;
int getX() { return x; }
};
int main(void)
{
Derived d;
d.fun();
return 0;
}
Output:
fun() called
// One function works for all data types. This would work
// even for user defined types if operator '>' is overloaded
template <typename T> T myMax(T x, T y)
{
return (x > y) ? x : y;
}
int main()
{
// Call myMax for int
cout << myMax<int>(3, 7) << endl;
// call myMax for double
cout << myMax<double>(3.0, 7.0) << endl;
// call myMax for char
cout << myMax<char>('g', 'e') << endl;
return 0;
}
Output
7
7
g
Class Templates
Class templates like function templates, class templates are useful when a class
defines something that is independent of the data type. Can be useful for classes
like LinkedList, BinaryTree, Stack, Queue, Array, etc.
#include <iostream>
using namespace std;
public:
Array(T arr[], int s);
void print();
};
int main()
{
int arr[5] = { 1, 2, 3, 4, 5 };
Array<int> a(arr, 5);
a.print();
return 0;
}
Output
1 2 3 4 5