C++ Notes
C++ Notes
In these C++ tutorials, we are going to learn about the C++ programming language from the very basics to the industry level. This
course has been designed in a way to nurture the beginners setting their feet in this discipline. So tighten your belts, and enjoy the
ride!
Before starting, let me explain to you the difference between this and any other source for learning C++:
Programming can be understood as your instructions to the computer(machine) to solve real problems. The very basic principle of
creating machines was to make life simpler and machines, on our instructions, have been able to do the same. But the distance
between what we say and what the machine understands gets abridged by a programming language. This marks the importance of
learning a programming language.
A programming language helps us communicate with the computer. Analogous to us humans, who need some language, be it
English, Hindi, or Bangla, to talk to our people, computers too need a language to converse. Just to name a few, there is C++, C,
Python, Java, etc.
Now when we start listing the names of these programming languages, the question which instinctively arises is why C++. Despite
this being an 80s programming language, it never lost its sheen. C++ was an added version of C developed by Bjarne Stroustrup. It
is believed to be very close to the hardware making it comparatively easy for programmers to give the instructions directly to the
system without any intermediary. Another reason for C++ to be one of the most used languages is its object-orientedness. C++ is an
object-oriented programming language giving it the power to create real-world software systems. You don’t have to worry much
about these terms, which believe me, only sound complex and ain’t really! Just sit back and dive with me in this plethora of
knowledge.
Step 1: Click here and you will be redirected to the official download page of VS Code. Download the VS code according to your
operating system in use. I will be downloading it for Windows 10 as shown in the below animation.
Figure 1: Visual Studio Code Website
Step 2: Once the downloading is complete, install VS code on your system like any other application.
Installation of g++
g++ is a compiler that helps us convert our source code into a .exe file. Below is the process of downloading and installing g++:
Step 1: Go to Google and search "MinGW install" and click on the MinGW link, as shown in the image below.
Step 2: Click on the download button on the top right corner menu.
Step 3: After visiting the download page, click on the windows button as shown in the image below to start the downloading
Step 4: After the download - open the program and click "Continue" to start the installation process.
Figure 7: G++ Installation Step
Step 5: After downloading some packages, it will show you a screen, as shown in the image below. You have to mark both the
boxes as in the image below, and then click on installation on the top left corner menu. Finally, click apply changes, and it will start
downloading the required packages.
Step 6: After finishing step 5, close the program and open C:// drive. Furthermore, locate the MinGW folder. Go to its bin directory
and copy its file path, as shown in the image below.
Step 8: After that click on advanced system settings as shown in the image below
Figure 10: Step to Add g++ File Path
Step 9: After that click on "Environment Variables" as shown in the image below
Step 10: After that select path and click on edit as shown in the image below
Step 11: Then, click on new and paste the file path and click ok as shown in the image below
Figure 13: Adding g++ File Path
After adding the file path now, our g++ compiler is ready, and we can start coding now.
Following these steps will open your visual studio code with that folder as the context. After opening the VS Code, you have to install
some extensions. Go to the extension menu and search "C/C++," and it will show you this extension. C/C++, as well as the other
extensions we add, will make our life easy while learning C++. Click on the install button, and it will start installing the extension for
you, as shown in the image below.
Figure 15: Installing Extension
This extension will help us in writing code through features such as auto-complete or auto-dropdown suggestions. Let us install one
more extension, which will help us run our programs quickly. Go to the Extensions tab in the top left corner and search "Code
runner." After that, click on install.
Now we have to create our program file and start writing our code. To create a program file, you have to go to the File menu > then
click on the file button, as shown in the image below.
After clicking on the file button, it will ask you for the file name. Give the name of the file as "tutorial1.cpp" and press enter. Now the
code file will be created, and you can start writing your program.
In today's tutorial, we are not going to learn anything about what this code is all about. We will learn these things step by step in our
upcoming lectures. Now to execute this code, press the run button, as shown in the image above, and it will give you the output as
shown in the image below.
Figure 19: Program Output
Thank you friends for starting to learn C++ with me, hope you liked the tutorial. If you haven’t checked out the whole playlist yet,
move on to codewithharry.com or my YouTube channel to access it. I hope you enjoy them.
In the next tutorial, we’ll be talking more about the basic structures of a C++ program, see you there, till then keep coding.
int main(){
std::cout
std cout<<"Hello World";
return 0;
}
Basic Structure of a C++ Program | C++ Tutorials for
Beginners #2
In this series of C++ tutorials, we will visualize the basic structure of a C++ program. In
our last lesson, we discussed C++, and we had also learned about how to download
and install visual studio code and g++; If you haven't read the previous lecture, feel free
to navigate through the course content!
In our previous lecture, we had written and executed a small C++ program. Today we
are going to discuss that program in more detail.
As you can see in the image, this was the program that we had executed in our
previous lecture. Now we will discuss what each line of code in the program does.
1. Let's start with the 1st line of code "#include<iostream>" - this whole text is called
a header file.
In this line of code include is a keyword used to add libraries in our program.
"iostream" is the name of a library, added to our program. The iostream library helps
us to get input data and show output data. The iostream library also has many more
uses; it is not only limited to input and output but for now, we will not go into more detail
on this.
2. One more thing to consider here is that the 2nd line of code is blank; there is no code
written. The thing to consider here is that it doesn't matter how many lines you have left
empty in a C++ program, the compiler will ignore those lines and only check the ones
with the code.
3. Now onto the 3rd line of code "int main() {" - In this line of code, "int" is a return
type which is called integer and "main()" is a function, the brackets "()" denotes that it
is a function. The curly brace "{" indicates that it is an opening of a function, and the
curly brace "}" indicates that it is the closing of a function. Here I will give you an
example to better understand the functionality of "int main()." Imagine that you own a
coffee shop, and you have some employees who work for you. Let's name (Anna,
Blake, Charlie) as the three employees. The function of Anna is to take orders, the
function of Blake is to make coffee, and Charlie's function is to deliver coffee. Now
when Anna gets a coffee order, she will call Blake to make the coffee, and when the
coffee is ready, Blake will call Charlie to deliver the coffee. In this scenario, we can say
that Anna is the primary function from which all the other tasks will start, and coffee
is our return value (Something charlie finally gives to Blake). In this line of code,
"main" is a reserved keyword, and we cannot change it to some other keyword. This
was just an analogy, and you will understand this very well in upcoming tutorials.
4. Now let's talk about the 4th line of code 'std::cout<<" hello world";' - In this line of
code "std" is a namespace, "::" is the scope resolution operator and "cout<<" is a
function which is used to output data, "hello world" is our output string and ";" is used
to end a statement. The code "std::cout" tells the compiler that the "cout" identifier
resides in the std namespace. Main key points here are:
We can write as many statements as you want in a single line, but I recommend
you write one statement per line to keep the code neat and clean.
Anything which is written between double quotation " " is a string literal (More on
strings later).
5. Now let's talk about the 5th line of code "return 0" - In this line of code, the return
keyword will return 0 as an integer to our main function "int main()" as we have
discussed before. Returning 0 as a value to the main function means successful
termination of the program.
So that was the anatomy of a C++ program. I hope you understood the functions of
various parts in a C++ program
Variables & Comments in C++ in Hindi | C++ Tutorials
for Beginners #3
In this tutorial, we will learn about the variables and comments in the C++ language. In
our last lesson, we discussed the basic structure of a C++ program, where we
understood the working of the C++ code line by line. If you haven't read the previous
lecture, make sure to navigate through the course content section.
Variables in C++
Comments in C++
Before explaining the concept of variables and comments, I would like to clarify two
more ideas: low level and high level. To make it easy to understand, let's consider this
scenario - when we go to Google search engine and search for some queries, Google
displays us some websites according to our question. Google does this for us at a very
high level. We don't know what's happening at the low level until we look into Google
servers (at a low level) and further to the level where the data is in the form of 0s/1s.
The point I want to make here is that low level means nearest to the hardware, and a
high level means farther from the hardware with a lot of layers of abstraction.
Figure 1: C++ Sample Code
Variables in C++
Variables are containers to store our data. To make it easy to understand, I will give a
scenario: to store water, we use bottles, and to store sugar, we use a box. In this
scenario, the bottle and box are containers that are storing water and sugar; the same
is the case with variables; they are the containers for data types. As there are many
types of data types, for example, "int" is used for integers, the "float" is used for
floating-point numbers, "char" is used for character, and many more data types are
available, we will discuss them in upcoming lectures. The main point here is that these
variables store the values of these data types. Figure 1 shows an example of a
variable. "sum" is taken as an integer variable, which will store a value 6, and writing
sum after the "cout" statement will show us the value of "sum" on the output window.
Comments in C++
A comment is a human-readable text in the source code, which is ignored by the
compiler. There are two ways to write comments.
Single-Line Comments: 1st way is to use" //" before a single line of text to make it
unparsable by the compiler.
Multi-Line Comments: 2nd way is to use "/*" as the opening and "*/" as the closing of
the comment. We then write text in between them. If we write text without this, the
compiler will try to read the text and will end up giving an error. Figure 1 shows
examples of these comments.
Variable Scope
Data Types
Before explaining the concept of variable scope, I would like to clarify about variables a
little more. Variable can be defined as a container to hold data. Variables are of different
types, for example:
1. Int-> Int is used to store integer data e.g (-1, 2, 5,-9, 3, 100).
2. Float-> Float is used to store decimal numbers e.g (0.5, 1.05, 3.5, 10.5)
3. Char-> Char is used to store a single character e.g. ('a', 'b',' c', 'd')
4. Boolean-> Boolean is used to store "true" or "false."
5. Double-> Double is also used to store decimal numbers but has more precision
than float, e.g. (10.5895758440339...)
Here is an example to understand variables: int sum = 34; means that sum is an integer
variable that holds value '34' in memory.
Variable Scope
The scope of a variable is the region in the program where the existence of that
variable is valid. For example, consider this analogy - if one person travels to another
country illegally, we will not consider that country as its scope because he doesn't have
the necessary documents to stay in that country.
Local variables
Global variables
Local variables:
Local variables are declared inside the braces of any function and can be assessed
only from there.
Global variables:
Global variables are declared outside any function and can be accessed from
anywhere.
Data Types
Data types define the type of data that a variable can hold; for example, an integer
variable can hold integer data, a character can hold character data, etc.
Built-in
User-defined
Derived
Note: We will discuss the concepts of user-defined data types in another lecture. For
now, understanding that these are user-defined data types is enough.
Note: We will discuss the concept of derived data types in another lecture. For now,
understanding that these are derived data types is enough.
In this code, we have initialized different types of variables and then printed them on
screen. At line no 6 and 7, we initialized two integer variables a, and b, but they are
commented out for compiler to ignore them. At line no 8, we have again initialized two
integer variables a, and b, but this time they both are on the same line separated by a
comma. The main thing to note here is that variables can be initialized on separate
lines or in a single line. At line no 9, we have initialized a float variable pi and assigned
a decimal value 3.14 to it. At line no 10, we have initialized a character variable c and
assigned a character'd' to it. At line no 11, we have printed the value of a, and b. The
main thing to note here is that "/n" is used to print a new line. At line no 12, we have
printed the value of pi. Similarly, in line no 13, the value of c is printed. The output for
this program is shown in figure 2.
In this piece of code, we have initialized two "glo" variables. 1st variable is outside the
main function, and the 2nd variable is inside the main function. The value assigned to
the "glo" variable outside the main function is 6, and the value assigned to the "glo"
variable inside the main function is 9. One thing to note here is that in the main function,
we have again assigned a value 78 to the variable "glo" which will update the previous
value 9.
After initializing the "glo" variables, we had output the "glo" variables at two places in
our program the 1st place is inside the main function, and the 2nd place is inside the
sum function. The main thing to note here is that:
When the "cout" will run inside the sum function, it will check for "glo" variable
value inside the sum function. As we can see that there is no "log" variable
initialized inside the sum function, it will check for the "glo" variable outside of the
sum function scope, which we call a global scope. As we can see, that "glo"
function is initialized in the global scope with the value 6, so the sum function will
take that value.
When the "cout" will run inside the main function, it will check for "glo" variable
value inside the main function first, and as we can see that there is a "glo" variable
initialized inside the main function scope which is a local scope, it will use that
value.
As we can see that the output is "6781". The output 6 is from the cout of "glo" in sum
function, the output 78 is from the cout of "glo" in the main function, and the output 1 is
from the cout of "is_true" Boolean variable in the main function.
int main(){
int glo=9;
glo
glo=78;
glo
// int a = 14;
// int b = 15;
int a
a=14, bb=15;
float pi=3.14;
pi
char c ='d';
bool is_true = false;
sum();
cout<<glo
cout glo<< is_true
is_true;
// cout<<"This is tutorial 4.\nHere the value of a is "<<a<<".\nThe value of
// cout<<"\nThe value of pi is: "<<pi;
// cout<<"\nThe value of c is: "<<c;
return 0;
}
C++ Basic Input/Output & More | C++ Tutorials for Beginners #5
In this tutorial, we will visualize basic input and output in the C++ language. In our last lesson, we discussed the variable's scope and
data types. In this C++ tutorial, we are going to cover basic input and output:
Input stream
In the input stream, the direction of the flow of bytes occurs from the input device (for ex keyboard) to the main memory.
Output stream
In output stream, the direction of flow of bytes occurs from main memory to the output device (for ex-display)
In this piece of code, we have declared two integer variables "num1" and "num2". Firstly we used "cout" to print "Enter the value
of num1:" as it is on the screen, and then we used "cin" to take the input in "num1" at run time from the user.
Secondly, we used "cout" to print "Enter the value of num2:" as it is on the screen, and then we used "cin" to take the input in
"num2" at run time from the user.
In the end, we used "cout" to print "The sum is" as it is on the screen and also gave the literal "num1+num2" which will add the
values of both variables and print it on the screen.
The output of the following program is shown in figure 2.
We have executed our program two times, which can be seen in figure 2. In our 1st execution, we had input the value "54" for the
variable "num1" and value "4" for the variable "num2". This gives us the sum of both numbers as "58".
In our 2nd execution, we had input the value "5" for the variable "num1" and value "8" for the variable "num2". This gives us the
sum of both numbers as "13".
Important Points
1. The sign "<<" is called insertion operator
2. The sign ">>" is called extraction operator
3. "cout" keyword is used to print
4. "cin" keyword is used to take input at run time.
int main()
{
int num1, num2;
num1 num2
cout<<"Enter the value of num1:\n"; /* '<<' is called Insertion operator */
cout
cin>>num1
cin num1; /* '>>' is called Extraction operator */
return 0;
}
C++ Header files & Operators | C++ Tutorials for Beginners #6
In this C++ tutorial, we will talk about header files and operators. In our last lesson, we discussed the basic input and output. Lets
now cover header files and operators in C++ language:
Operators in C++
Operators are used for producing output by performing various types of calculations on two or more inputs. In this lecture, we will
see the operators in C++.
Arithmetic Operators
Arithmetic operators are used for performing mathematical operations like (+, -, *). The arithmetic operators are shown in Figure 1.
1. The function "a+b", will add a and b values and print them.
2. The function "a-b "will subtract a and b values and print them.
3. The function "a*b" will multiply a and b values and print them.
4. The function "a/b ", will divide a and b values and print them.
5. The function "a%b ", will take the modulus of a and b values and print them.
6. The function "a++" will first print the value of a and then increment it by 1.
7. The function "a--", will first print the value of a and then decrement it by 1.
8. The function "++a", will first increment it by one and then print its value.
9. The function "--a", will first decrement it by one and then print its value.
Assignment Operators
Assignment operators are used for assigning values to variables. For example: int a = 10, b = 5;
Comparison Operators
Comparison operators are used for comparing two values. Examples of comparison operators are shown in figure 3.
1. The function "(a==b)", will compare a and b values and check if they are equal. The output will be one if equal, and 0 if not.
2. The function "(a!=b)", will compare a and b values and check if "a" is not equal to "b". The output will be one if not equal and 0
if equal.
3. The function "(a>=b)", will compare a and b values and check if "a" is greater than or equal to "b". The output will be one if
greater or equal, and 0 if not.
4. The function "(a<=b)", will compare a and b values and check if "b" is greater than or equal to "a". The output will be one if
greater or equal, and 0 if not.
5. The function "(a>b)", will compare a and b values and check if "a" is greater than "b". The output will be one if greater and 0 if
not.
6. The function "(a<b)", will compare a and b values and check if "b" is greater than "a". The output will be one if greater and 0 if
not.
1. The function "((a==b)&& (a<b))" will first compare a and b values and check if they are equal or not; if they are equal, the next
expression will check whether "a" is smaller than "b". The output will be one if both expressions are true and 0 if not.
2. The function "((a==b) || (a<b))", will first compare a and b values and check if they are equal or not, even if they are not equal it
will still check the next expression ie whether "a" is smaller than "b" or not. The output will be one if any one of the expressions
is true and 0 if both are false.
3. The function "(!(a==b))", will first compare a and b values and check if they are equal or not. The output will be inversed ie if "a"
and "b" are equal; the output will be 0 and 1 otherwise.
That's it for this tutorial. In this lecture, we have covered some important operators in C++ language, but there are still some
operators left, which we will cover in upcoming tutorials.
int main(){
int a=4,
a b=5;
b
cout<<"Operators in C++:"<<endl
cout endl;
cout<<"Following
cout are the types of operators in C++"<<endl
endl;
// Arithmetic operators
cout<<"The value
cout of a + b is "<<a
a+b
b<<endl
endl;
cout<<"The value
cout of a - b is "<<a
a-b
b<<endl
endl;
cout<<"The
cout value of a * b is "<<a
a*b
b<<endl
endl;
cout<<"The
cout value of a / b is "<<a
a/b
b<<endl
endl;
cout<<"The
cout value of a % b is "<<a
a%b
b<<endl
endl;
cout<<"The
cout value of a++ is "<<a
a++<<endl
endl;
cout<<"The
cout value of a-- is "<<a
a--<<endl
endl;
cout<<"The
cout value of ++a is "<<++a
a<<endl
endl;
cout<<"The
cout value of --a is "<<--a
a<<endl
endl;
cout<<endl
cout endl;
As we have entered the value of the variable "a" as five and "b" as 6, it gives us the
sum 14, but for the global variable, it has given us the value 45.
Reference Variable
Reference variables can be defined as another name for an already existing variable.
These are also called an alias. For example, let us say we have a variable with the
name of "sum", but we also want to use the same variable with the name of "add", to
do that we will make a reference variable with the name of "add". The example code
for the reference variable is shown in figure 5.
As shown in figure 5, we initialized a variable "x" with the value "455". Then we
assigned the value of "x" to a reference variable "y". The ampersand "&" symbol is
used with the "y" variable to make it reference variable. Now the variable "y" will start
referring to the value of the variable "x". The output for variable "x" and "y" is shown in
figure 6.
Figure 6: Reference Variable Code Output
Typecasting
Typecasting can be defined as converting one data type into another. Example code for
type casting is shown in figure 7.
As shown in figure 7, we have initialized two variables, integer "a" and float "b". After
that, we converted an integer variable "a" into a float variable and float variable "b" into
an integer variable. In C++, there are two ways to typecast a variable, either using "
(float)a" or using "float(a)". The output for the above program is shown in figure 8.
Figure 8: Typecasting Program Output
int c = 45;
int main(){
In this C++ tutorial, the topics which we are going to cover today are given below:
Constants in C++
Manipulator in C++
Operator Precedence in C++
Constants in C++
Constants are unchangeable; when a constant variable is initialized in a program, its value cannot be changed afterwards. An
example program for constants is shown in figure 1.
As shown in figure 2, a constant float variable "a" is initialized with a value "3.11" but when we tried to update the value of "a" with a
value of "45.6" the compiler throw us an error that the constant variable is being reassigned a value. An error message can be seen
in figure 2.
Manipulator
In C++ programming, language manipulators are used in the formatting of output. The two most commonly used manipulators are:
"endl" and "setw".
As shown in figure 3, we have initialized three integer variables "a, b, c". First, we printed all the three variables and used "endl" to
print each variable in a new line. After that, we again printed the three variables and used "setw(4)," which will set there width to "4".
The output for the following program is shown in figure 4.
Operator associativity helps us to solve an expression; when two or more operators have the same precedence, the operator
associativity helps us to decide that we should solve the expression from "left-to-right" or from "right-to-left".
Operator precedence and operator associativity can be seen from here. An example program for operator precedence and operator
associativity is shown in figure 5.
As shown in figure 5, we initialized two integer variables and then wrote an expression "int c = a*5+b;" on which we have already
discussed. Then we have written another expression "int c = ((((a*5)+b)-45)+87);". The precedence of multiply is higher than
addition so the multiplication will be done first, but the precedence of addition and subtraction is same, so here we will check the
associativity which is "left-to-right" so the addition is performed first and then subtraction is performed.
Code as described/written in the video
#include<iostream>
#include<iomanip>
int main(){
// int a = 34;
// cout<<"The value of a was: "<<a;
// a = 45;
// cout<<"The value of a is: "<<a;
// Constants in C++
// const int a = 3;
// cout<<"The value of a was: "<<a<<endl;
// a = 45; // You will get an error because a is a constant
// cout<<"The value of a is: "<<a<<endl;
// Manipulators in C++
// int a =3, b=78, c=1233;
// cout<<"The value of a without setw is: "<<a<<endl;
// cout<<"The value of b without setw is: "<<b<<endl;
// cout<<"The value of c without setw is: "<<c<<endl;
In this C++ tutorial, the topics which we are going to cover today are given below:
1. Sequence Structure
Sequence structure refers to the sequence in which program execute instructions one
after another. An example diagram for the sequence structure is shown in figure 1.
Figure 1: Sequence Structure
2. Selection Structure
3. Loop Structure
Loop structure refers to the execution of an instruction in a loop until the condition gets
false. An example diagram for loop structure is shown in figure 3.
As shown in figure 4, we declared a variable “age” and used “cin" function to gets its
value from the user at run time. At line 10 we have used "if” statement and give a
condition “(age<18)” which means that if the age entered by the user is smaller than
"18” the output will be “you cannot come to my party” but if the age is not smaller
than “18” the compiler will move to the next condition.
At line 13 we have used “else if” statement and given another condition “age==18"
which means that if the age entered by the user is equal to "18” the output will be “you
are a kid and you will get a kid pass to the party” but if the age is not equal to the
“18” the compiler will move to the next condition.
At line 16 we have used “else" condition which means that if none of the above
condition is "true" the output will be "you can come to the party”.
As can be seen in figure 5, that when we entered the age "81" which was greater than
18, so it gives us the output "you can come to the party”. The main thing to note here
is that we can use as many “else if” statements as we want.
As shown in figure 4, we passed a variable “age” to the switch statement. The switch
statement will compare the value of variable “age" with all cases. For example, if the
entered value for variable "age” is “18”, the case with value “18” will be executed and
prints “you are 18”. The keyword “break" will let the compiler skips all other cases and
goes out of the switch case statement. An output of the following program is shown in
figure 6.
As shown in figure 7, we entered the value “18” for the variable “age", and it gives us
an output "you are 18” and “Done with switch case”. The main thing to note here is
that after running the “case 18” is skips all the other cases due to the “break” statement
and printed “Done with switch case” which was outside of the switch case statement.
int main(){
// cout<<"This is tutorial 9";
int age;
age
cout<< "Tell me your age"<<endl
cout endl;
cin>>age
cin age;
In this series of our C++ tutorials, we will visualize for loop, while loop, and do-while loop in C++ language in this lecture. In our last
lesson, we discussed the control structures, If-else statements, and switch statements in C++.
Loops in C++
Loops are block statements, which keeps on repeatedly executing until a specified condition is met. There are three types of loops in
C++
As shown in figure 1, we created for loop, and inside its condition, there are three statements separated by a semicolon. The
1st statement is called “initialization”, the 2nd statement is called “condition”, and the 3rd statement is called “updation". After that,
there is a loop body in which code is written, which needs to be repeated. Here is how our for loop will be executed:
As shown in figure 3, we created a while loop, and inside its condition, there is one statement. The statement is called "condition”.
Here is how our while loop will be executed:
As shown in figure 4, we created a do-while loop, and the syntax of the do-while loop is like write body with "do” keyword and at the
end of body write “while" keyword with the condition. Here is how our do-while loop will be executed:
Initialize integer variable “i” with value “1”
Go into loop body and execute the code
Check the condition if the value of the variable "i" is smaller or equal to "40”
If the condition is true - go into loop body and execute the code
Keep repeating this step until the condition gets false
In this C++ tutorial, the topics which we are going to cover today are given below:
Break Statements
We had already discussed a little bit about break statements in switch statements. Today we will see the working of break
statements in loops. Break statements in loops are used to terminate the loop. An example program for Break's statement is shown
in figure 1.
As shown in figure 1, this is how the break statement program will be executed:
As shown in figure 3, this is how the continue statement program will be executed:
int main(){
// for (int i = 0; i < 40; i++)
// {
// /* code */
// if(i==2){
// break;
// }
// cout<<i<<endl;
// }
for (int i = 0; i < 40; i
i++)
{
/* code */
if(i==2){
continue;
}
cout<<i<<endl
cout endl;
}
return 0;
}
Pointers in C++ | C++ Tutorials for Beginners #12
In this series of our C++ tutorials, we will visualize pointers in the C++ language in this lecture. In our last lesson, we discussed
break statements and continue statements in C++.
Pointers in C++
A pointer is a data type which holds the address of other data type. The “&” operator is called “address off" operator, and the "*”
operator is called “value at” dereference operator. An example program for pointers is shown in figure 1.
As shown in figure 1, at 1st line an integer variable “a” is initialized with the value “3". At the 2nd line, the address of integer variable
"a” is assigned to the integer pointer variable “b". At the 3rd line, the address of the integer pointer variable "b” is printed. The output
of the following program is shown in figure 2.
As shown in figure 2, the address of the integer pointer variable "b” is printed. The main thing to note here is that the address printed
by the variable “b" is the address of integer variable "a” because we had assigned the address of variable “a” to the integer pointer
variable “b". To clarify, we will print both variable "a" and variable "b" addresses, which are shown in figure 3.
As shown in figure 3, now we printed both variable “a” and variable “b” addresses. The output for the following program is shown in
figure 4.
As shown in figure 4, both variables "a” and “b” have the same addresses, but in actual, this is the address of the variable "a”, the
variable “b" is just pointing to the address of the variable "a”.
To see the value of variable “a" using a pointer variable, we can use the "*" dereference operator. An example of the dereference
operator program is shown in figure 5.
As shown in figure 5, the value at address “b” is printed. The main thing to note here is that the value printed by the pointer variable
“b” will be the value of variable “a” because the pointer variable “b" is pointing to the address of the variable "a”. The output for the
following program is shown in figure 6.
Pointer to Pointer
Pointer to Pointer is a simple concept, in which we store the address of one Pointer to another pointer. An example program for
Pointer to Pointer is shown in figure 7.
As shown in figure 7, at the 1st line, the address of the pointer variable "b” is assigned to the pointer variable “c”. At 2nd line, the
address of the pointer variable "b” is printed. At the 3rd line, the address of the pointer variable "c” is printed. At line 4th, the value at
the pointer variable "c” is printed. At line 5th, the pointer variable "c” will be dereferenced two times, and it will print the value at
pointer variable "b”. The output of the following program is shown in figure 2. The output for the following program is shown in figure
8.
int main(){
// What is a pointer? ----> Data type which holds the address of other data types
int a
a=3;
int* b;
b
b = &a;
// Pointer to pointer
int** c = &b;
cout<<"The address of b is "<<&b<<endl
cout endl;
cout<<"The address of b is "<<c<<endl
cout endl;
cout<<"The value at address c is "<<*c<<endl
cout endl;
cout<<"The value at address value_at(value_at(c)) is "<<**c<<endl
cout endl;
return 0;
}
Arrays & Pointers Arithmetic in C++ | C++ Tutorials for Beginners #13
In this tutorial, we will discuss arrays and pointer arithmetic in C++
int marks
marks[] = {23, 45, 56, 89};
cout<<marks
cout marks[0]<<endl
endl;
cout<<marks
cout marks[1]<<endl
endl;
cout<<marks
cout marks[2]<<endl
endl;
cout<<marks
cout marks[3]<<endl
endl;
As shown in the code snippet, we initialized an array of size 4 in which we have stored marks of 4 students and then printed them
one by one. The main point to note here is that array store data in continuous block form in the memory, and array indexes start from
0. Output for the following program is shown in figure 1.
int mathMarks
mathMarks[4];
mathMarks[0] =
mathMarks 2278;
mathMarks[1] =
mathMarks 738;
mathMarks[2] =
mathMarks 378;
mathMarks[3] =
mathMarks 578;
As shown in code snippet 2, we have declared an array of size 4 and then assigned values one by one to each index of the array.
Output for the following program is shown in figure 2.
Figure 2: Array Program 2 Output
To change the value at the specific index of an array, we can simply assign the value to that index. For example: “marks[2] = 333”
can place the value “333” at the index “2” of the array. We can use loops to print the values of an array, instead of printing them one
by one. An example program to print the value of the array with "for" loop is shown in code snippet 3.
As shown in code snippet 3, we initialized an integer variable “i" with the value 0 and set the running condition of the loop to the
length of an array. In the loop body, each index number and the value at each number is being printed. Output for the following
program is shown in figure 3.
An example program for storing the starting address of an array in the pointer is shown in code snippet 4.
int* p = marks
marks;
cout<<"The value of marks[0] is "<<*p<<endl
cout endl;
As shown in code snippet 7, we have assigned the address of array “marks” to the pointer variable “*p” and then printed the pointer
“*p”. The main thing to note here is that the value at the pointer “*p” is the starting address of the array “marks”. The output for the
following program is shown in figure 4.
int* p = marks
marks;
cout<<"The value of *p is "<<*p<<endl
cout endl;
cout<<"The value of *(p+1) is "<<*(p+1)<<endl
cout endl;
cout<<"The value of *(p+2) is "<<*(p+2)<<endl
cout endl;
cout<<"The
cout value of *(p+3) is "<<*(p+3)<<endl
endl;
As shown in code snippet 5, 1st we have printed the value at pointer “*p”; 2nd we have printed the value at pointer “*(p+1)”; 3rd we
have printed the value at pointer “*(p+2)”; 4th we have printed the value at pointer “*(p+3)". This program will output the values at "0,
1, 2, 3" indices of an array "marks". The output of the following program is shown in figure 5.
int main(){
// Array Example
int marks
marks[] = {23, 45, 56, 89};
int mathMarks
mathMarks[4];
mathMarks[0] = 2278;
mathMarks
mathMarks[1] = 738;
mathMarks
mathMarks[2] = 378;
mathMarks
mathMarks[3] = 578;
mathMarks
Structures in C++
The structure is a user-defined data type that is available in C++. Structures are used to
combine different types of data types, just like an array is used to combine the same
type of data types. An example program for creating a structure is shown in Code
Snippet 1.
struct employee
{
/* data */
int eId
eId;
char favChar
favChar;
float salary;
salary
};
As shown in Code Snippet 1, we have created a structure with the name “employee”, in
which we have declared three variables of different data types (eId, favchar, salary). As
we have created a structure now we can create instances of our structure employee.
An example program for creating instances of structure employees is shown in Code
Snippet 2.
int main() {
struct employee harry
harry;
harry.
harry eId = 1;
harry.favChar = 'c';
harry
harry.salary = 120000000;
harry
cout<<"The value is "<<harry
cout harry.eId
eId<<endl
endl;
cout<<"The value is "<<harry
cout harry.favChar
favChar<<endl
endl;
cout<<"The value is "<<harry
cout harry.salary
salary<<endl
endl;
return 0;
}
As shown in Code Snippet 2, 1st we have created a structure variable “harry” of type
“employee”, 2nd we have assigned values to (eId, favchar, salary) fields of the structure
employee and at the end we have printed the value of “salary”.
Another way to create structure variables without using the keyword “struct” and the
name of the struct is shown in Code Snippet 3.
As shown in Code Snippet 3, we have used a keyword “typedef” before struct and after
the closing bracket of structure, we have written “ep”. Now we can create structure
variables without using the keyword “struct” and name of the struct. An example is
shown in Code Snippet 4.
int main(){
harry;
ep harry
struct employee shubham
shubham;
struct employee rohanDas
rohanDas;
harry.eId = 1;
harry
harry.favChar = 'c';
harry
harry.salary = 120000000;
harry
cout<<"The value is "<<harry
cout harry.eId
eId<<endl
endl;
cout<<"The value is "<<harry
cout harry.favChar
favChar<<endl
endl;
cout<<"The value is "<<harry
cout harry.salary
salary<<endl
endl;
return 0;
}
Unions in C++
Unions are similar to structures but they provide better memory management then
structures. Unions use shared memory so only 1 variable can be used at a time. An
example program to create unions is shown in Code Snippet 5.
union money
{
/* data */
int rice;
rice //4
char car
car; //1
float pounds;
pounds //4
};
We can only use 1 variable at a time otherwise the compiler will give us a garbage
value
The compiler chooses the data type which has maximum memory for the
allocation.
An example program for creating an instance of union money is shown in Code Snippet
6.
int main(){
union money m1;
m1
m1.rice = 34;
m1
cout<<m1
cout m1.rice
rice;
return 0;
}
As shown in Code Snippet 6, 1st we have created a union variable “m1” of type
“money”, 2nd we have assigned values to (rice) fields of the union money, and in the
end, we have printed the value of “rice”. The main thing to note here is that once we
have assigned a value to the union field “rice”, now we cannot use other fields of the
union otherwise we will get garbage value. The output for the following program is
shown in figure 1.
Enums in C++
Enums are user-defined types which consist of named constants. Enums are used to
make the program more readable. An example program for enums is shown in Code
Snippet 8.
int main(){
enum Meal{ breakfast,
breakfast lunch,
lunch dinner};
dinner
Meal m1 = lunch
lunch;
cout<<
cout m1;
m1
return 0;
}
As shown in Code Snippet 7, 1st we have created an enum “Meal” in which we have
stored three named constants (breakfast, lunch, dinner). 2nd we have assigned the
value of “lunch” to the variable “m1” and at the end, we have printed “m1”. The main
thing to note here is that (breakfast, lunch, dinner) are constants; the value for
“breakfast” is “0”, the value for “lunch” is “1” and the value for “dinner” is “2”. The output
for the following program is shown in figure 2.
union money
{
/* data */
int rice
rice; //4
char car
car; //1
float pounds
pounds; //4
};
int main(){
enum Meal{ breakfast
breakfast, lunch
lunch, dinner
dinner};
Meal m1 = lunch
lunch;
cout<<(m1
cout m1==2);
// cout<<breakfast;
Functions & Function Prototypes in C++ | C++ Tutorials for Beginners #15
In this tutorial, we will discuss functions and functions prototype in C++
Functions in C++
Functions are the main part of top-down structured programming. We break the code into small pieces and make functions of that
code. Functions help us to reuse the code easily. An example program for the function is shown in Code Snippet 1.
As shown in Code Snippet 1, we created an integer function with the name of sum, which takes two parameters “int a” and “int b”. In
the function, body addition is performed on the values of variable “a” and variable “b” and the result is stored in variable “c”. In the
end, the value of variable “c” is returned to the function. We have seen how this function works now we will see how to pass values
to the function parameters. An example program for passing the values to the function is shown in Code Snippet 2.
int main(){
int num1, num2;
num1 num2
cout<<"Enter first number"<<endl
cout endl;
cin>>num1
cin num1;
cout<<"Enter second number"<<endl
cout endl;
cin>>num2
cin num2;
cout<<"The sum is "<<sum(num1
cout num1, num2
num2);
return 0;
}
As shown in Code Snippet 2, we have declared two integer variables “num1” and “num2”, we will take their input at run time. In the
end, we called the “sum” function and passed both variables “num1” and “num2” into sum function. “sum” function will perform the
addition and returns the value at the same location from where it was called. The output of the following program is shown in figure
1.
// Function prototype
int sum(int a
a, int b
b);
As shown in Code Snippet 3, we have made a function prototype of the function “sum”, this function prototype will tell the compiler
that the function “sum” is declared somewhere in the program which takes two integer parameters and returns an integer value.
Some examples of acceptable and not acceptable prototypes are shown below:
Formal Parameters
The variables which are declared in the function are called a formal parameter. For example, as shown in Code Snippet 1, the
variables “a” and “b” are the formal parameters.
Actual Parameters
The values which are passed to the function are called actual parameters. For example, as shown in Code Snippet 2, the variables
“num1” and “num2” are the actual parameters.
The function doesn't need to have parameters or it should return some value. An example of the void function is shown in Code
Snippet 4.
void g(){
cout<<"\nHello,
cout Good Morning";
}
As shown in Code Snippet 4, void as a return type means that this function will not return anything, and this function has no
parameters. Whenever we will call this function it will print “Hello, Good Morning”
// Function prototype
// type function-name (arguments);
// int sum(int a, int b); //--> Acceptable
// int sum(int a, b); //--> Not Acceptable
int sum(int, int); //--> Acceptable
// void g(void); //--> Acceptable
void g(); //--> Acceptable
int main(){
int num1,
num1 num2;
num2
cout<<"Enter first number"<<endl
cout endl;
cin>>num1
cin num1;
cout<<"Enter second number"<<endl
cout endl;
cin>>num2
cin num2;
// num1 and num2 are actual parameters
cout<<"The sum is "<<sum(num1
cout num1, num2
num2);
g();
return 0;
}
int sum(int a
a, int b
b){
// Formal Parameters a and b will be taking values from actual parameters num1 and num2.
Call by Value & Call by Reference in C++ | C++ Tutorials
for Beginners #16
In this tutorial, we will discuss call by value and call by reference in C++
void swap(int a
a, int b
b){ //temp a b
int temp = aa; //4 4 5
a = b
b; //4 5 5
b = temp;
temp //4 5 4
}
int main(){
int x =4, y
y=5;
cout<<"The
cout value of x is "<<x<<" and the value of y is "<<y<<endl;
endl
swap(x, y
y);
cout<<"The
cout value of x is "<<x<<" and the value of y is "<<y<<endl;
endl
return 0;
}
Code Snippet 2: Passing Values to Swap Function
As shown in Code Snippet 2, we have initialized two integer variables “a” and “b” and
printed their values. Then we called a “swap” function and passed values of variables
“a” and “b” and again printed the values of variables “a” and “b”. The output for the
following program is shown in figure 1.
As shown in figure 3, the values of “a” and “b” are the same for both times they are
printed. So the main point here is that when the call by value method is used it doesn’t
change the actual values because copies of actual values are sent to the function.
int main(){
int x =4, y
y=5;
cout<<"The value of x is "<<x<<" and the value of y is "<<y<<endl
cout endl;
swapPointer(&x, &y); //This will swap a and b using pointer reference
cout<<"The value of x is "<<x<<" and the value of y is "<<y<<endl
cout endl;
return 0;
}
As shown in Code Snippet 4, we have initialized two integer variables “a” and “b” and
printed their values. Then we called a “swap” function and passed addresses of
variables “a” and “b” and again printed the values of variables “a” and “b”. The output
for the following program is shown in figure 2.
As shown in figure 2, the values of “a” and “b” are swapped when the swap function is
called. So the main point here is that when the call by pointer method is used it
changes the actual values because addresses of actual values are sent to the function.
As shown in Code Snippet 5, we created a swap function that is taking reference of “int
&a” and “int &b” as parameters. In function body values of variables, “a” and “b” are
swapped. An example program is shown in Code Snippet 6, which calls the swap
function and passes values to it.
int main(){
int x =4, y
y=5;
cout<<"The value of x is "<<x<<" and the value of y is "<<y<<endl
cout endl;
swapReferenceVar(x, y
y); //This will swap a and b using reference variables
cout<<"The value of x is "<<x<<" and the value of y is "<<y<<endl
cout endl;
return 0;
}
As shown in Code Snippet 6, we have initialized two integer variables “a” and “b” and
printed their values. Then we called a “swap” function and passed variables “a” and “b”
and again printed the values of variables “a” and “b”. The output for the following
program is shown in figure 3.
As shown in figure 3, the values of “a” and “b” are swapped when the swap function is
called. So the main point here is that when the call by reference method is used it
changes the actual values because references of actual values are sent to the function.
Code as described/written in the video
#include<iostream>
using namespace std;
std
int sum(int a,
a int b){
b
int c = a + b
b;
return c;
c
}
As shown in Code Snippet 1, 1st inline keyword is used to make the function inline.
2nd a product function is created which has two arguments and returns the product of
them. Now we will call the product function multiple times in our main program which is
shown in Code Snippet 2.
int main(){
int a
a, b
b;
cout<<"Enter
cout the value of a and b"<<endl
endl;
cin>>a>>b;
cin
cout<<"The product of a and
cout b is "<<product(a,b)<<endl
endl;
cout<<"The product of a and
cout b is "<<product(a,b)<<endl
endl;
cout<<"The product of a and
cout b is "<<product(a,b)<<endl
endl;
cout<<"The product of a and
cout b is "<<product(a,b)<<endl
endl;
cout<<"The product of a and
cout b is "<<product(a,b)<<endl
endl;
cout<<"The product of a and
cout b is "<<product(a,b)<<endl
endl;
cout<<"The product of a and
cout b is "<<product(a,b)<<endl
endl;
cout<<"The product of a and
cout b is "<<product(a,b)<<endl
endl;
return 0;
}
As shown in Code Snippet 2, we called the product function multiple times. The main
thing to note here is that the function will not run instead of it the function code will be
copied at the place where the function is being called. This will increase the execution
time of the program because the compiler doesn’t have to copy the values and get the
return value again and again from the compiler. The output of the following program is
shown in figure 1.
int main(){
int money = 100000;
cout<<"If
cout you have "<<money
money<<" Rs in your bank account, you will recive "<<mon
cout<<"For VIP: If you have "<<money
cout money<<" Rs in your bank account, you will reci
return 0;
}
// }
int main(){
int aa, b
b;
// cout<<"Enter the value of a and b"<<endl;
// cin>>a>>b;
// cout<<"The product of a and b is "<<product(a,b)<<endl;
int money = 100000;
cout<<"If you have "<<money
cout money<<" Rs in your bank account, you will recive "<<m
cout<<"For VIP: If you have "<<money
cout money<<" Rs in your bank account you will re
Recursions & Recursive Functions in C++ | C++ Tutorials
for Beginners #18
In this tutorial, we will discuss recursion and recursive functions in C++
4 * factorial( 4-1 )
4 * 3 * factorial( 3-1 )
4* 3 * 2 * factorial( 2-1 )
4*3*2*1
An example to pass the value to the recursive factorial function is shown in Code
Snippet 2.
int main(){
int a;
a
cout<<"Enter
cout a number"<<endl
endl;
cin>>
cin a;
cout<<"The factorial of "<<a<< " is "<<factorial(a)<<endl
cout endl;
return 0;
}
As shown in Code Snippet 2, we created an integer variable “a”, which takes input at
the runtime and that value is passed to the factorial function. The output for the
following program is shown in figure 1.
As shown in figure 1, we input the value “4” and it gives us the factorial of it which is
“24”. Another example of a recursive function for the Fibonacci series is shown in Code
Snippet 3.
As shown in Code Snippet 3, we created a “fib” function which takes one argument. In
the function body, there is a base case which checks that if the value of variable “n” is
smaller than “2”, if the condition is “true” return “1”. And there is a recursive condition
that divides the bigger value to smaller values and at the end returns a Fibonacci
number. An example to pass the value to the Fibonacci function is shown in Code
Snippet 4.
int main(){
int a;
a
cout<<"Enter
cout a number"<<endl
endl;
cin>>a;
cin
cout<<"The term in fibonacci sequence at position "<<a<< " is "<<fib(a)<<endl
cout
return 0;
}
As shown in Code Snippet 4, we created an integer variable “a”, which takes input at
the runtime and that value is passed to the Fibonacci function. The output for the
following program is shown in figure 2.
As shown in figure 2, 1st we input the value “5” and it gives us the Fibonacci number at
that place which is “8”. 2nd we input the value “6” and it gives us the Fibonacci number
at that place which is “13”.
One thing to note here is that recursive functions are not always the best option. They
perform well in some problems but not in every problem.
// fib(5)
// fib(4) + fib(3)
// fib(2) + fib(3) + fib(2) + fib(3)
int factorial(int n
n){
if (n<=1){
return 1;
}
return n * factorial(n-1);
}
As shown in Code Snippet 1, we have created two “sum” functions, the 1st “sum” function takes two arguments “int a”,
“int b” and return the sum of those two variables; and the 2nd sum function is taking three arguments “int a”, “int b”, “int
c” and return the sum of those three variables. Function call for these “sum” function is shown in Code Snippet 2.
int main(){
cout<<"The
cout sum of 3 and 6 is "<<sum(3,6)<<endl
endl;
cout<<"The
cout sum of 3, 7 and 6 is "<<sum(3, 7, 6)<<endl
endl;
return 0;
}
As shown in Code Snippet 2, we passed two arguments in the first function call and three arguments in the second
function call. The output of the following program is shown in figure 1.
// Rectangular box
int volume (int l
l, int b
b, int h
h){
return (l*b*h);
}
As shown in Code Snippet 3, we have created three “volume” functions, the 1st “volume” function calculates the volume
of the cylinder and has two arguments “double r” and “int h”; the 2nd “volume” function calculates the volume of the cube
and has one argument “int a”; the 3rd “volume” function calculates the volume of the rectangular box and has three
arguments “int l”, “int b” and “int h”. The function call for these “volumes” function is shown in Code Snippet 4.
int main(){
cout<<"The volume of cuboid of 3, 7 and 6 is "<<volume(3, 7, 6)<<endl
cout endl;
cout<<"The
cout volume of cylinder of radius 3 and height 6 is "<<volume(3, 6)<<endl;
endl
cout<<"The
cout volume of cube of side 3 is "<<volume(3)<<endl
endl;
return 0;
}
As shown in Code Snippet 4, we passed three arguments in the first function call, two arguments in the second function
call, and one argument in the third function call. The output of the following program is shown in figure 2.
As shown in figure 2, all three “volume” functions run fine and give us the required output.
int sum(float a
a, int b
b){
cout<<"Using function with 2 arguments"<<endl
cout endl;
return a
a+b;
}
// Rectangular box
int volume (int l
l, int b
b, int h
h){
← Previous Next →
C++ language was designed with the main intention of adding object-oriented
programming to C language
As the size of the program increases readability, maintainability, and bug-free
nature of the program decrease.
This was the major problem with languages like C which relied upon functions or
procedure (hence the name procedural programming language)
As a result, the possibility of not addressing the problem adequately was high
Also, data was almost neglected, data security was easily compromised
Using classes solves this problem by modeling program as a real-world scenario
Object-Oriented Programming
Works on the concept of classes and object
A class is a template to create objects
Treats data as a critical element
Decomposes the problem in objects and builds data and functions around the
objects
Classes in C++
Classes are user-defined data-types and are a template for creating objects. Classes
consist of variables and functions which are also called class members.
An example program to demonstrate classes, public and private access modifiers are
shown in Code Snippet 1.
class Employee
{
private:
int a, b, c
a b c;
public:
int d, e;
d e
void setData(int a1
a1, int b1
b1, int c1
c1); // Declaration
void getData(){
cout<<"The value
cout of a is "<<a<<endl
endl;
cout<<"The value
cout of b is "<<b<<endl
endl;
cout<<"The value
cout of c is "<<c<<endl
endl;
cout<<"The value
cout of d is "<<d<<endl
endl;
cout<<"The value
cout of e is "<<e<<endl
endl;
}
};
As shown in Code Snippet 1, 1st we created an “employee” class, 2nd three integer
variables “int a”, “int b”, and “int c” were declared under the private access modifier,
3rd two integer variables “int d” and “int e” was declared under the public access
modifiers, 4th “setData” function was declared, 5th “getData” function was defined and
values of all the variables are printed. 6th “setData” function was defined outside the
“employee” class by using a scope resolution operator; “setData” function is used to
assign values to the private member of the class. An example to create the object of the
class and use its class members is shown in Code Snippet 2.
int main(){
Employee harry;
harry
harry.d = 34;
harry
harry.e = 89;
harry
harry.setData(1,2,4);
harry
harry.getData();
harry
return 0;
}
As shown in Code Snippet 2, 1st we created an object “harry” of the class “employee”;
2nd we assigned values to “int d” and “int e” which are public class members. If we try to
assign values to the private class member’s compiler will throw an error. 3rd we passed
the values to the function “setData” and at the end, we called “getData” function which
will print the values of all the variables. The output for the following program is shown in
figure 1.
As shown in figure 1, all the values of our data members are printed.
class Employee
{
private:
int a, b, c
a b c;
public:
int d, e;
d e
void setData(int a1
a1, int b1
b1, int c1
c1); // Declaration
void getData(){
cout<<"The value
cout of a is "<<a<<endl
endl;
cout<<"The value
cout of b is "<<b<<endl
endl;
cout<<"The value
cout of c is "<<c<<endl
endl;
cout<<"The value of d is "<<d<<endl
cout endl;
cout<<"The value of e is "<<e<<endl
cout endl;
}
};
class Employee{
// Class definition
} harry
harry, rohan
rohan, lovish
lovish;
class binary
{
private:
string s;
s
void chk_bin(void);
public:
void read(void);
void ones_compliment(void);
void display(void);
};
void binary::read(void)
binary
{
cout << "Enter a binary number" << endl;
endl
cin >> ss;
}
As shown in Code Snippet 3, we have created a “read” function. This function will take input from the user at runtime.
void binary
binary::chk_bin(void)
{
for (int i = 0; i < s
s.length(); i
i++)
{
if (s.at(i) != '0' && s
s.at(i) != '1')
{
cout << "Incorrect binary format" << endl
endl;
exit(0);
}
}
}
As shown in Code Snippet 4 we have created a “chk_bin” function. This ”for” loop in the function will run till the length of
the string and “if” condition in the body of the loop will check the whole string that if there are any values in the string
other than “1” and “0”. If there are values other than “1” and “0” this function will output “Incorrect binary format”.
void binary
binary::ones_compliment(void)
{
chk_bin();
for (int i = 0; i < s
s.length(); i
i++)
{
if (s.at(i) == '0')
{
s.at(i) = '1';
s
}
else
{
s.at(i) = '0';
s
}
}
}
As shown in Code Snippet 5, in the body of the “ones_compliment” function; the “chk_bin” function is called, and as we
have discussed above that if one member function is called inside the other member function of the same class it is
called nesting of a member function. The “for” loop inside the “ones_compliment” functions runs till the length of the
string and the “if” condition inside the loop replaces the number “0” with “1” and “1” with “0”.
void binary
binary::display(void)
{
cout<<"Displaying your binary number"<<endl
cout endl;
for (int i = 0; i < s
s.length(); i
i++)
{
cout << s
s.at(i);
}
cout<<endl
cout endl;
}
As shown in Code Snippet 6, the “for” loop inside display function runs till the length of the string and prints each value
of the sting.
int main()
{
binary b;
b
b.read();
b
// b.chk_bin();
b.display();
b
b.ones_compliment();
b
b.display();
b
return 0;
}
As shown in Code Snippet 7, we created an object “b” of the binary data type, and the functions “read”, “display”,
“ones_compliment”, and “display” are called. The main thing to note here is that the function ”chk_bin” is the private
access modifier of the class so we cannot access it directly by using the object, it can be only accessed inside the class
or by the member function of the class.
#include <iostream>
#include <string>
using namespace std
std;
class binary
{
← Previous Next →
The memory is only allocated to the variables of the class when the object is created.
The memory is not allocated to the variables when the class is declared. At the same
time, single variables can have different values for different objects, so every object has
an individual copy of all the variables of the class. But the memory is allocated to the
function only once when the class is declared. So the objects don’t have individual
copies of functions only one copy is shared among each object.
Arrays in Classes
Arrays are used to store multiple values of the same type. An array is very helpful when
multiple variables are required, instead of making multiple variables one array can be
used which can store multiple values. Array stores data in sequential order. An example
program to demonstrate the use of arrays in classes is shown below.
class Shop
{
int itemId
itemId[100];
int itemPrice[100];
itemPrice
int counter;
counter
public:
void initCounter(void) { counter = 0; }
void setPrice(void);
void displayPrice(void);
};
As shown in Code Snippet 1, we created a shop class which has, “itemId[100]” and
“itemPrice” as integer array variable and “counter” variable as private class members;
and “initCounter” void function, “setPrice” void function, and “displayPrice” void function
as public class members. The definitions of these functions are shown below.
As shown in Code Snippet 2, we have created a “setPrice” function. This function will
take input for “itemId” and “ItemPrice” from the user at runtime. The value of the counter
will be incremented by one every time this function will run.
As shown in Code Snippet 3, the “for” loop inside the “displayPrice” function runs till the
length of the counter and prints values of the array “itemId” and “ItemPrice”.
int main()
{
dukaan;
Shop dukaan
dukaan.initCounter();
dukaan
dukaan.setPrice();
dukaan
dukaan.setPrice();
dukaan
dukaan.setPrice();
dukaan
dukaan.displayPrice();
dukaan
return 0;
}
As shown in Code Snippet 4, we created an object “dukaan” of the shop data type, and
the functions “initCounter” is called. The function “setPrice” is called three times. Loops
can also be used to call the function multiple times. The “displayPrice” function is also
called in the main function. The output of the following program is shown in figure 1.
Figure 1: Program Output
As shown in figure 1, for the item 1 we entered the ID “1001” and price “12”; for the item
2 we entered the ID “1002” and price “23”; for the item 3 we entered the ID “1003” and
price “34”. The Output of the program has displayed the ID and the price of each item.
class Shop
{
int itemId
itemId[100];
int itemPrice[100];
itemPrice
int counter;
counter
public:
void initCounter(void) { counter = 0; }
void setPrice(void);
void displayPrice(void);
};
class Employee
{
int id
id;
static int count
count;
public:
void setData(void)
{
cout << "Enter the id" << endl
endl;
cin >> id
id;
count++;
count
}
void getData(void)
{
cout << "The id of this employee is " << id << " and this is employee number " << count << endl
endl;
}
As shown in Code Snippet 1, we created an employee class that has integer “id” variable and “count” static integer variable as
private class members; and “setData” void function, “getData” void function, and “getCount” static void function as public class
members. These functions are explained below.
We have defined a “setData” function. This function will take input for “id” from the user at runtime and increment in the count. The
value of the counter will be incremented by one every time this function will run.
We have defined a “getData” function. This function will print the values of the variables “id” and “count”.
We have defined a static “getCount” function. This function will print the value of the variable count”. The main thing to note here is
that “getCount” function is static, so if we try to access any data members or member functions which are not static the compiler will
throw an error.
// Count is the static data member of class Employee
int Employee
Employee::count
count; // Default value is 0
int main()
{
Employee harry, rohan, lovish
harry rohan lovish;
// harry.id = 1;
// harry.count=1; // cannot do this as id and count are private
harry.setData();
harry
harry.getData();
harry
Employee::getCount();
rohan.setData();
rohan
rohan.getData();
rohan
Employee::getCount();
lovish.setData();
lovish
lovish.getData();
lovish
Employee::getCount();
return 0;
}
As shown in figures 1 and 2, for the “harry” object we entered the ID “1”; for the “rohan” object we entered the ID “2”; and for the
“lovish” object we entered the ID “3”. The Output of the program has displayed the ID and the count of each employee.
Code as described/written in the video
#include <iostream> Copy
class Employee
{
int id
id;
static int count
count;
public:
void setData(void)
{
cout << "Enter the id" << endl
endl;
cin >> id
id;
count++;
count
}
void getData(void)
{
cout << "The id of this employee is " << id << " and this is employee number " << count << endl
endl;
}
class Employee
{
int id
id;
int salary;
salary
public:
void setId(void)
{
salary = 122;
cout << "Enter the id of employee" << endl
endl;
cin >> id
id;
}
void getId(void)
{
cout << "The id of this employee is " << id << endl
endl;
}
};
Code Snippet 1: Employee Class
As shown in Code Snippet 1, we created an employee class that has integer “id”
variable and “salary” integer variable as private class members; and “setId” void
function, “getId” void function as public class members. These functions are explained
below.
We have defined a “setId” function. In this function, the “salary” variable is assigned by
the value “122” and the function will take input for “id” from the user at runtime. We
have defined a “getId” function. This function will print the values of the variables “id”.
int main()
{
Employee fb[4];
fb
for (int i = 0; i < 4; i
i++)
{
fb[i].setId();
fb
fb[i].getId();
fb
}
return 0;
}
As shown in Code Snippet 2, we created an array “fb” of size “4” which is of employee
data-type. The “for” loop is used to run “setId” and “getId” functions till the size of an
array. The main thing to note here is that the objects can also be created individually
but it is more convenient to use an array if too many objects are to be created. The
output of the following program is shown in figure 1.
As shown in figure 1. As we input the Id for an employee it gives us the output of the
employee Id.
Passing Object as Function Argument
Objects can be passed as function arguments. This is useful when we want to assign
the values of a passed object to the current object. An example program to
demonstrate the concept of passing an object as a function argument is shown below.
class complex{
int a
a;
int b;
b
public:
void setData(int v1
v1, int v2
v2){
a = v1;
v1
b = v2
v2;
}
void printNumber(){
cout<<"Your
cout complex number is "<<a<<" + "<<b<<"i"<<endl;
endl
}
};
As shown in Code Snippet 3, we created a complex class that has integer “a” variable
and “b” integer variable as private class members; and “setData” void function,
“setDataBySum” void function, and “printNumber” void function as public class
members. These functions are explained below.
We have defined a “setData” function. In this function the values are assigned to the
variables “a” and “b” because they are private data members of the class and values
cannot be assigned directly. We have defined a “setDataBySum” function. In this
function, the values of two objects are added and then assigned to the variables “a” and
“b”. We have defined a “printNumber” function. In this function, the values of the
variable “a” and “b” are being printed.
int main(){
complex c1, c2, c3
c1 c2 c3;
c1.setData(1,
c1 2);
c1.printNumber();
c1
c2.setData(3, 4);
c2
c2.printNumber();
c2
c3.setDataBySum(
c3 c1,
c1 c2);
c2
c3.printNumber();
c3
return 0;
}
class Employee
{
int id
id;
int salary;
salary
public:
void setId(void)
{
salary = 122;
cout << "Enter the id of employee" << endl
endl;
cin >> id
id;
}
void getId(void)
{
cout << "The id of this employee is " << id << endl
endl;
}
};
int main()
{
// Employee harry, rohan, lovish, shruti;
class complex{
int a
a;
int b;
b
public:
void setData(int v1
v1, int v2
v2){
a = v1
v1;
b = v2
v2;
}
void printNumber(){
cout<<"Your complex number is "<<a<<" + "<<b<<"i"<<endl
cout endl;
}
};
int main(){
complex c1, c2, c3
c1 c2 c3;
Friend Functions in C++ | C++ Tutorials for Beginners #26
In this tutorial, we will discuss friend function in C++
class Complex{
int a
a, bb;
friend Complex sumComplex(Complex o1,
o1 Complex o2);
o2
public:
void setNumber(int n1
n1, int n2
n2){
a = n1
n1;
b = n2
n2;
}
// Below line means that non member - sumComplex funtion is allowed to do anything with my private parts
void printNumber(){
cout<<"Your number is "<<a<<" + "<<b<<"i"<<endl
cout endl;
}
};
As shown in Code Snippet 1, we created a complex class that has integer “a” variable and “b” integer variable as private
class members; and “setNumber” void function, “printNumber” void function as public class members. The
“sumComplex” friend function prototype is written as well in the complex class. These functions are explained below.
We have defined a “setNumber” function. In this function the values are assigned to the variables “a” and “b” because
they are private data members of the class and values cannot be assigned directly. We have defined a “printNumber”
function. In this function, the values of the variable “a” and “b” are being printed. We have defined a “sumComplex”
friend function. In this function, the object “o3” is created which calls the “setNumber” function and passes the values of
two objects after performing addition on them.
int main(){
Complex c1,
c1 c2,
c2 sum;
sum
c1.setNumber(1, 4);
c1
c1.printNumber();
c1
c2.setNumber(5, 8);
c2
c2.printNumber();
c2
sum = sumComplex(c1
c1, c2
c2);
sum.printNumber();
sum
return 0;
}
// 1 + 4i
// 5 + 8i
// -------
// 6 + 12i
class Complex{
int a
a, bb;
friend Complex sumComplex(Complex o1,
o1 Complex o2);
o2
public:
void setNumber(int n1,
n1 int n2){
n2
a = n1
n1;
b = n2
n2;
}
// Below line means that non member - sumComplex funtion is allowed to do anything with my private par
void printNumber(){
cout<<"Your number is "<<a<<" + "<<b<<"i"<<endl
cout endl;
}
};
← Previous Next →
class Complex
{
int a
a, b
b;
// Individually declaring functions as friends
friend int Calculator ::sumRealComplex(Complex
Complex, Complex);
Complex
friend int Calculator ::sumCompComplex(Complex
Complex, Complex);
Complex
public:
void setNumber(int n1
n1, int n2
n2)
{
a = n1
n1;
b = n2
n2;a
}
void printNumber()
{
cout << "Your number is " << a << " + " << b << "i" << endl
endl;
}
};
// Forward declaration
class Complex;
class Calculator
{
public:
int add(int a,
a int b b)
{
return (a + b
b);
}
int sumRealComplex(Complex
Complex, Complex
Complex);
int sumCompComplex(Complex, Complex);
Complex Complex
};
As shown in code snippet 2, a complex class is declared at the top which is known as
forward declaration. Forward declaration hints to the compiler that this class is declared
somewhere forward in the code. After that calculator class is defined this consists of
three public member functions, “add”, “sumRealComplex”, and “sumCompComplex”.
The “add” function will add the values of “a” and “b” and return the value. The
“sumRealComplex” and “sumCompComplex” are taking two objects of the complex
class. The code for the complex class is shown below.
class Complex
{
int a
a, b
b;
// Individually declaring functions as friends
// friend int Calculator ::sumRealComplex(Complex, Complex);
// friend int Calculator ::sumCompComplex(Complex, Complex);
public:
void setNumber(int n1,
n1 int n2)
n2
{
a = n1;
n1
b = n2
n2;a
}
void printNumber()
{
cout << "Your number is " << a << " + " << b << "i" << endl;
endl
}
};
int main()
{
Complex o1,
o1 o2;
o2
o1.setNumber(1, 4);
o1
o2.setNumber(5,
o2 7);
calc;
Calculator calc
int res = calc.sumRealComplex(
calc o1,
o1 o2);
o2
cout << "The sum of real part of o1 and o2 is " << res << endl
endl;
int resc = calc.sumCompComplex(
calc o1,
o1 o2);
o2
cout << "The sum of complex part of o1 and o2 is " << resc << endl
endl;
return 0;
}
As shown in code snippet 4, 1st two objects “o1” and “o2” of the “complex” data type are
declared. 2nd “setNumber” function is called with the “o1” and “o2” objects and the
values are passed. 3rd object “calc” of the calculator data type is declared.
4th “sumRealComplex” function is called by the “calc” object and the object “o1” and
“o2” are passed to it. 5th “sumCompComplex” function is called by the “calc” object and
the object “o1” and “o2” are passed to it. The output of the following program is shown
in figure 1.
As shown in figure 1, the sum of the real part is shown which is “6” and the sum of the
complex part is shown which is “11”.
More on C++ Friend Functions (Examples & Explanation)
| C++ Tutorials for Beginners #28
In this tutorial, we will discuss more on friend functions in C++ with examples
class Y;
class X{
int data
data;
public:
void setValue(int value
value){
data = value
value;
}
friend void add(X, YY);
};
class Y{
int num
num;
public:
void setValue(int value
value){
num = value
value;
}
friend void add(X, YY);
};
1st class “Y” is declared at the top which is known as forward declaration to let the
compiler know that this class is defined somewhere in the program.
2nd class “X” is defined which consists of private data member “data” and public
member function “setValue” which assigns the value to the private data member
“data”. At the end friend function “add” is declared.
3rd class “Y” is defined which consists of private data member “num” and public
member function “setValue” which assigns the value to the private data member
“num”. At the end friend function “add” is declared.
4th function “add” is defined which add the value of the objects of class “X” and “Y”
and print it.
int main(){
a1;
X a1
a1.setValue(3);
a1
Y b1;
b1
b1.setValue(15);
b1
add(a1
a1, b1
b1);
return 0;
}
h
5th function “add” is called and the objects “a1” and “b1” are passed to it. The
function “add” will add the values of both objects and print them.
class c2;
class c1{
int val1
val1;
friend void exchange(c1 & , c2 &);
public:
void indata(int a
a){
val1 = a
a;
}
void display(void){
cout<< val1 <<endl
cout endl;
}
};
class c2{
int val2
val2;
friend void exchange(c1 &, c2 &);
public:
void indata(int a
a){
val2 = a
a;
}
void display(void){
cout<< val2 <<endl
cout endl;
int main(){
oc1;
c1 oc1
c2 oc2;
oc2
oc1.indata(34);
oc1
oc2.indata(67);
oc2
exchange(oc1,
oc1 oc2);
oc2
cout<<"The
cout value of c1 after exchanging becomes: ";
oc1.display();
oc1
cout<<"The
cout value of c2 after exchanging becomes: ";
oc2.display();
oc2
return 0;
}
Constructors in C++
A constructor is a special member function with the same name as the class. The
constructor doesn’t have a return type. Constructors are used to initialize the objects of
its class. Constructors are automatically invoked whenever an object is created.
class Complex
{
int a
a, b
b;
public:
// Creating a Constructor
// Constructor is a special member function with the same name as of the cla
//It is used to initialize the objects of its class
//It is automatically invoked whenever an object is created
void printNumber()
{
cout << "Your number is " << a << " + " << b << "i" << endl
endl;
}
};
1st “complex” class is defined which consists of private data members “a” and “b”.
2nd default constructor of the “complex” class is declared.
3rd function “printNumber” is defined which will print the values of the data
members “a” and “b”.
4th default constructor is defined which will assign the values to the data members
“a” and “b”. The main things to note here are that whenever a new object will be
created this constructor will run and if the parameters are not passed to the
constructor it is called a default constructor.
return 0;
}
1st objects “c1”, “c2”, and “c3” of the complex data type are created. The main
thing to note here is that when we are creating objects the constructor will run for
each object and will assign the values.
2nd function “printNumber” is called by the objects “c1”, “c2”, and “c3”.
#include<iostream>
using namespace std;
std
class Complex
{
int a
a, b
b;
public:
Complex(int, int); // Constructor declaration
void printNumber()
{
cout << "Your number is " << a << " + " << b << "i" << endl;
endl
}
};
Complex ::Complex(int x,
x int y)
y // ----> This is a parameterized constructor as it
{
a = x;
x
b = y
y;
// cout<<"Hello world";
}
1st “complex” class is defined which consists of private data members “a” and “b”.
2nd parameterized constructor of the “complex” class is declared which takes two
parameters.
3rd function “printNumber” is defined which will print the values of the data
members “a” and “b”.
4th parameterized constructor is defined which takes two parameters and assigns
the values to the data members “a” and “b”. The main things to note here are that
whenever a new object will be created this constructor will run.
int main(){
// Implicit call
Complex a(4, 6);
a.printNumber();
a
// Explicit call
Complex b = Complex(5, 7);
b.printNumber();
b
return 0;
}
1st parameterized constructor is called implicitly with the object “a” and the values
“4” and “6” are passed
2nd function “printNumber” is called which will print the values of data members
3rd parameterized constructor is called explicitly with the object “b” and the values
“5” and “7” are passed
h
4th function “printNumber” is called again which will print the values of data
members
#include<iostream>
using namespace std;
std
class Point{
int x
x, y
y;
public:
Point(int aa, int b
b){
x = a
a;
y = b
b;
}
void displayPoint(){
cout<<"The point is ("<<x<<", "<<y<<")"<<endl
cout endl;
}
};
1st “point” class is defined which consists of private data members “x” and “y”.
2nd parameterized constructor of the “point” class is defined which takes two
parameters and assigns the values to the private data members of the class.
3rd function “displayPoint” is defined which will print the values of the data
members “x” and “y”.
1st parameterized constructor is called implicitly with the object “p” and the values
“1” and “1” are passed
2nd function “displayPoint” is called which will print the values of data members
3rd parameterized constructor is called implicitly with the object “q” and the values
“4” and “6” are passed
4th function “displayPoint” is called which will print the values of data members
#include <iostream>
using namespace std;
std
class Complex
{
int a,
a b;
b
public:
Complex(){
a = 0;
b =0;
}
Complex(int x,
x int y)
y
{
a = x;
x
b = y
y;
}
Complex(int x){
x
a = x
x;
b = 0;
}
1st we created a “complex” class which consists of private data members “a” and
“b”.
2nd default constructor of the “complex” class is declared which has no parameters
and assigns “0” to the data members “a” and “b”.
3rd parameterized constructor of the “complex” class is declared which takes two
parameters and assigns values to the data members “a” and “b”.
4th parameterized constructor of the “complex” class is declared which takes one
parameter and assigns values to the data members “a” and “b”.
5th function “printNumber” is defined which will print the values of the data
members “a” and “b”.
int main()
{
Complex c1(4, 6);
c1.printNumber();
c1
Complex c2(5);
c2.printNumber();
c2
Complex c3;
c3
c3.printNumber();
c3
return 0;
}
1st parameterized constructor is called with the object “c1” and the values “4” and
“6” are passed. The main thing to note here is that this will run the constructor with
two parameters.
2nd function “printNumber” is called which will print the values of data members
3rd parameterized constructor is called with the object “c2” and the value “5” is
passed. The main thing to note here is that this will run the constructor with one
parameter.
4th function “printNumber” is called which will print the values of data members
5th default constructor is called with the object “c3”. The main thing to note here is
that this will run the constructor with no parameters.
6th function “printNumber” is called which will print the values of data members
As shown in figure 1, all the values which were passed and assigned through
parameterized constructors and the values which were assigned through the default
constructor are printed.
Constructors With Default Arguments In C++ | C++ Tutorials for Beginners #32
In this tutorial, we will discuss constructors with default arguments in C++
#include<iostream>
using namespace std;
std
class Simple{
int data1;
data1
int data2
data2;
int data3;
data3
public:
Simple(int a
a, int b
b=9, int c
c=8){
data1 = aa;
data2 = bb;
data3 = cc;
}
void printData();
};
1st we created a “simple” class which consists of private data members “data1”, “data2” and “data3”.
2nd parameterized constructor of the “simple” class is defined which takes three parameters and assigns values to the data
members “a” and “b”. The main thing to note here is that the value “9” and “8” are the default values for the variables “b” and
“c”.
3rd function “printData” is defined which prints the values of the data members “data1”, “data2”, and “data3”.
int main(){
Simple s(12, 13);
s.printData();
s
return 0;
}
1st parameterized constructor is called with the object “s” of the data type “simple” and the values “12” and “13” are passed. The
main thing to note here is that the value of the parameter “c” will be automatically set by the default value.
2nd function “printData” is called which will print the values of data members.
#include<iostream>
using namespace std
std;
class BankDeposit{
int principal
principal;
int years;
years
float interestRate;
interestRate
float returnValue;
returnValue
public:
BankDeposit(){}
BankDeposit(int p
p, int y
y, float r
r); // r can be a value like 0.04
BankDeposit(int p
p, int y,
y int rr); // r can be a value like 14
void show();
};
BankDeposit :: BankDeposit(int p
p, int y
y, float r
r)
{
principal = p
p;
years = y;
y
interestRate = r
r;
returnValue = principal;
principal
for (int i = 0; i < y
y; ii++)
{
returnValue = returnValue * (1+interestRate
interestRate);
}
}
BankDeposit :: BankDeposit(int p
p, int y
y, int r
r)
{
principal = p
p;
years = y;
y
interestRate = float(r)/100;
returnValue = principal;
principal
for (int i = 0; i < yy; ii++)
{
returnValue = returnValue * (1+interestRate
interestRate);
}
}
1st the constructor “BankDeposit” is defined in which the value of the parameter “p”
is assigned to the data member “principal”; the value of the parameter “y” is
assigned to the data member “year”; the value of the parameter “r” is assigned to
the data member “interestRate”. At the end “for” loop is defined which will run till
the length of the variable “y” and add “1” in the “interestRate”; then multiply the
value with the “returnValue”. The main thing to note here is that in this constructor
the data type of the parameter “r” is float.
d
2nd another constructor “BankDeposit” is defined in which the value of the
parameter “p” is assigned to the data member “principal”; the value of the
parameter “y” is assigned to the data member “year”; the value of the parameter “r”
is converted to “float” and divided by “100” then assigned to the data member
“interestRate”. At the end “for” loop is defined which will run till the length of the
variable “y” and add “1” in the “interestRate”; then multiply the value with the
“returnValue”. The main thing to note here is that in this constructor the data type
of the parameter “r” is float.
3rd the function “show” is defined which will print the values of the data members
“principal”, “year”, and “returnValue”.
int main(){
BankDeposit bd1,
bd1 bd2,
bd2 bd3;
bd3
int p
p, y y;
float r;
r
int R;
R
cout<<"Enter
cout the value of p y and r"<<endl;
endl
cin>>p>>y>>r;
cin
bd1 = BankDeposit(p, y,
y r);
r
bd1.show();
bd1
1st the object “bd1”, “bd2”, and “bd3” of the data type “BankDeposit” are created.
2nd the integer variables “p” and “y” are declared; the float variable “r” is declared,
and the integer variable “R” is declared.
3rd the values for the variables “p”, “y”, and”r” are taken from the user on the
runtime.
4th parameterized constructor “BankDeposit” is called with the object “bd1” and the
variables “p”, “y”, and “r” are passed. The main thing to note here is that this will
run the constructor with float parameters “r”.
5th function “show” is called which will print the values of data members
6th the values for the variables “p”, “y”, and ”R” are taken from the user on the
runtime.
7th parameterized constructor “BankDeposit” is called with the object “bd2” and the
variables “p”, “y”, and “R” are passed. The main thing to note here is that this will
run the constructor with integer parameters “R”.
8th function “show” is called which will print the values of data members.
As shown in figure 1, the first time the values “100”, “1”, and “0.05” are entered and it
gives us the return value of “105”. The second time the values “100”, “1”, and “5” are
entered and it gives us the return value of “105”. So the main thing to note here is that
the compiler figures out the run time by seeing the data type and runs the relevant
constructor.
Copy Constructor in C++ | C++ Tutorials for Beginners
#34
In this tutorial, we will discuss copy constructor in C++
#include<iostream>
using namespace std;
std
class Number{
int a
a;
public:
Number(){
a = 0;
}
Number(int num
num){
a = num
num;
}
// When no copy constructor is found, compiler supplies its own copy const
Number(Number &obj
obj){
cout<<"Copy constructor called!!!"<<endl
cout endl;
a = obj
obj.a;
}
void display(){
cout<<"The
cout number for this object is "<< a <<endl
endl;
}
};
1st we created a “number” class which consists of private data member “a”.
2nd default constructor of the “number” class is defined which has no parameters
and assign “0” to the data members “a”.
3rd parameterized constructor of the “number” class is defined which takes one
parameter and assigns values to the data members “a”.
4th copy constructor of the “number” class is defined which takes its own reference
object as a parameter and assigns values to the data members “a”.
5th function “display” is defined which will print the values of the data members “a”.
int main(){
x, y
Number x y, z(45), z2
z2;
x.display();
x
y.display();
y
z.display();
z
z2 = z
z; // Copy constructor not called
z2.display();
z2
Number z3 = z;
z // Copy constructor invoked
z3.display();
z3
return 0;
}
Code Snippet 2: Main Program
1st objects “x”, “y”, “z”, and “z1” are created of the “number” data type. The main
thing to note here is that the object “z” has a value “45”.
2nd function “display” is called by the objects “x”, “y”, and “z”.
3rd copy constructor is invoked and the object “z” is passed to “z1”
4th function “display” is called by the object “z1”
5th the value of “z” is assigned to “z1”. The main thing to note here is that it will not
invoke a copy constructor because the object “z” is already created.
6th function “display” is called by the object “z2”
7th the value of “z” is assigned to “z3”. The main thing to note here is that it will
invoke a copy constructor because the object “z3” is being created.
8th function “display” is called by the object “z3”
As shown in figure 1, all the values which were passed and assigned through copy
constructors are printed.
Destructor in C++ in Hindi | C++ Tutorials for Beginners
#35
In this tutorial, we will discuss Destructor in C++
Destructor in C++
A destructor is a type of function which is called when the object is destroyed.
Destructor never takes an argument nor does it return any value. An example program
to demonstrate the concept of destructors in C++ is shown below.
#include<iostream>
using namespace std;
std
class num{
public:
num(){
count++;
count
cout<<"This
cout is the time when constructor is called for object number"<
}
~num(){
cout<<"This
cout is the time when my destructor is called for object numbe
count--;
count
}
};
int main(){
cout<<"We
cout are inside our main function"<<endl;
endl
cout<<"Creating first object n1"<<endl
cout endl;
num n1;
n1
{
cout<<"Entering
cout this block"<<endl;
endl
cout<<"Creating
cout two more objects"<<endl
endl;
num n2,
n2 n3;
n3
cout<<"Exiting
cout this block"<<endl
endl;
}
cout<<"Back
cout to main"<<endl
endl;
return 0;
}
1st object “n1” is created of the “num” data type. The main thing to note here is that
when the object “n1” is created the constructor will run.
2nd inside the block two objects “n2” and “n3” are created of the “num” data type.
The main things to note here are that when the objects “n2” and “n3” are created
the constructor will run for both objects and when the block ends the destructor will
run for both objects “n2” and “n3”.
3rd when the program ends the destructor for the object “n1” will run.
As shown in figure 1, first the constructor for the object “n1” was called; second the
constructor for the objects “n2” and “n3” was called; third the destructor was called for
the objects “n2” and “n3”; at the end destructor for the object “n1” was called.
Inheritance & Its Different Types with Examples in C++ |
C++ Tutorials for Beginners #36
In this tutorial, we will discuss inheritance in C++
Single Inheritance
Multiple Inheritance
Hierarchical Inheritance
Multilevel Inheritance
Hybrid Inheritance
Single inheritance is a type of inheritance in which a derived class is inherited with only
one base class. For example, we have two classes “employee” and “programmer”. If
the “programmer” class is inherited from the “employee” class which means that the
“programmer” class can now implement the functionalities of the “employee” class.
Multiple inheritances are a type of inheritance in which one derived class is inherited
with more than one base class. For example, we have three classes “employee”,
“assistant” and “programmer”. If the “programmer” class is inherited from the
“employee” and “assistant” class which means that the “programmer” class can now
implement the functionalities of the “employee” and “assistant” class.
Hierarchical Inheritance
After writing the class keyword we have to write the derived class name and then
put a “:” sign.
After “:” sign we have to write the visibility mode and then write the base class
name.
Note:
// Base Class
class Employee
{
public:
int id;
id
float salary;
salary
Employee(int inpId)
inpId
{
id = inpId
inpId;
salary = 34.0;
}
Employee() {}
};
1st we created an “employee” class which consists of public data member’s integer
“id” and float “salary”.
2nd the “employee” class consists of a parameterized constructor that takes an
integer “inpid” parameter and assigns its value to the data member “id”. The value
of variable “salary” is set to “34”.
3rd the “employee” class also consists of default constructor.
4th we created a “programmer” class that is inheriting “employee” class. The main
thing to note here is that the “visibility-mode” is “public”.
5th the “programmer” class consists of public data member’s integer
“languageCode”.
6th the “programmer” class consists of a parameterized constructor that takes an
integer “inpid” parameter and assigns its value to the data member “id”. The value
of variable “languageCode” is set to “9”.
h
7th “programmer” class consists of a function “getData” which will print the value of
the variable “id”.
int main()
{
Employee harry(1), rohan(2);
cout << harry.
harry salary << endl;
endl
cout << rohan
rohan.salary << endl
endl;
Programmer skillF(10);
cout << skillF
skillF.languageCode
languageCode<<endl
endl;
cout << skillF.
skillF id<<
id endl;
endl
skillF.getData();
skillF
return 0;
}
1st objects “harry” and “rohan” is created of the “employee” data type. Object
“harry” is passed with the value “1” and the object “rohan” is passed with the value
“2”.
2nd the “salary” of both objects “rohan” and “harry” are printed.
3rd object “skillF” is created of the “programmer” data type. Object “skillF” is
passed with the value “10”.
4th the “languageCode” and “id” of both object “skillF” is printed.
5th the function “getData” is called by the “skillF” object. This will print the “id”.
class Base
{
int data1
data1; // private by default and is not inheritable
public:
int data2;
data2
void setData();
int getData1();
int getData2();
};
int Base::getData1()
{
return data1;
data1
}
int Base::getData2()
{
return data2;
data2
}
1st we created a “base” class which consists of private data member’s integer
“data1” and public data member integer “data2”.
2nd the “base” class consists of three member functions “setData”, “getData1”, and
“getData2”.
3rd the function “setData” will assign the values “10” and “20” to the data members
“data1” and “data2”.
4th the function “getData1” will return the value of the data member “data1”.
5th the function “getData2” will return the value of the data member “data2”.
The derived class will inherit the base class which is shown below.
class Derived : public Base
{ // Class is being derived publically
int data3
data3;
public:
void process();
void display();
};
1st we created a “derived” class which is inheriting the base class publically. The
“derived” class consists of private data member’s integer “data3”.
2nd the “derived” class consists of two public member functions “process” and
“display”.
3rd the function “process” will multiply the values “data2” and “data1”; and store the
values in the variable “data3”.
4th the function “display” will print the values of the data member “data1”, “data2”,
and “data3”.
The main program is shown in code snippet 3.
int main()
{
Derived der;
der
der.setData();
der
der.process();
der
der.display();
der
return 0;
}
1. If the class is inherited in public mode then its private members cannot be inherited
in child class.
2. If the class is inherited in public mode then its protected members are protected
and can be accessed in child class.
3. If the class is inherited in public mode then its public members are public and can
be accessed inside child class and outside the class.
4. If the class is inherited in private mode then its private members cannot be
inherited in child class.
5. If the class is inherited in private mode then its protected members are private and
cannot be accessed in child class.
6. If the class is inherited in private mode then its public members are private and
cannot be accessed in child class.
7. If the class is inherited in protected mode then its private members cannot be
inherited in child class.
8. If the class is inherited in protected mode then its protected members are
protected and can be accessed in child class.
9. If the class is inherited in protected mode then its public members are protected
and can be accessed in child class.
An example program to demonstrate the concept of protected access modifiers is
shown below.
#include<iostream>
using namespace std;
std
class Base{
protected:
int a;
a
private:
int b;
b
};
};
int main(){
Base b;
b
Derived d;
d
// cout<<d.a; // Will not work since a is protected in both base as well as de
return 0;
}
1st we created a “Base” class which consists of protected data member integer “a”
and private data member integer “b”.
d
2nd we created a “Derived” class which is inheriting the “Base” class in protected
mode.
3rd the object “b” of the data type “Base” is created.
4th the object “d” of the data type “Derived” is created.
5th if we try to print the value of the data member “a” by using the object “d”; the
program will throw an error because the data member “a” is protected and the
derived class is inherited in the protected mode. So the data member “a” can only
be accessed in the “derived” but not outside the class.
Multilevel Inheritance Deep Dive with Code Example in
C++ | C++ Tutorials for Beginners #40
In this tutorial, we will discuss multilevel inheritance in C++
#include <iostream>
using namespace std
std;
class Student
{
protected:
int roll_number;
roll_number
public:
void set_roll_number(int);
void get_roll_number(void);
};
1st we created a “student” class which consists of protected data member integer
“roll_number”.
2nd the “student” class consists of a public function “set_roll_number” and
“get_roll_number”
3rd the function “set_roll_number” will set the value of the data member
“roll_number”.
4th the function “get_roll_number” will print the value of the data member
“roll_number”.
The code for the “exam” class is shown below which is inheriting the “student” class
class Exam : public Student
{
protected:
float maths
maths;
float physics;
physics
public:
void set_marks(float, float);
void get_marks(void);
};
1st we created an “exam” class that is inheriting “student” class in public mode.
2nd the “exam” class consists of protected data members float “math” and float
“physics”.
3rd the “exam” class consists of public member functions “set_marks” and
“get_marks”.
4th the function “set_marks” will set the value of the data members “math” and
“physics”.
5th the function “get_marks” will print the value of the data members “math” and
“physics”.
The code for the “result” class is shown below which is inheriting the “exam” class
class Result : public Exam
{
float percentage
percentage;
public:
void display_results()
{
get_roll_number();
get_marks();
cout << "Your result is " << (maths + physics
physics) / 2 << "%" << endl
endl;
}
};
1st we created a “Result” class which is inheriting the “Exam” class in public mode.
2nd the “Result” class consists of private data member’s float “percentage”.
3rd the “exam” class consists of the public member function “display_results”.
4th the function “display_results” will call the “get_roll_number” and “get_marks”
functions, and add the values of “math” and “physics” variables then divide that
value with “2” to get a percentage and prints it.
It can be clearly seen that the class “Exam” is inheriting class “student” and class
“Results” is inheriting class “Exam”; which is an example of multilevel inheritance. The
code main program is shown below.
int main()
{
Result harry;
harry
harry.set_roll_number(420);
harry
harry.set_marks(94.0, 90.0);
harry
harry.display_results();
harry
return 0;
}
After writing the class keyword we have to write the derived class name and then
put a “:” sign.
After “:” sign we have to write the visibility mode and then write the base class
name and again we have to write the visibility mode and write another base class
name.
public:
void set_base1int(int a
a)
{
base1int = a
a;
}
};
class Base2{
protected:
int base2int;
base2int
public:
void set_base2int(int a
a)
{
base2int = a
a;
}
};
class Base3{
protected:
int base3int;
base3int
Code Snippet 2: Base Classes
1st we created a “Base1” class which consists of protected data member integer
“base1int”.
2nd the “Base1” class consists of a public function “set_base1int”. This function will
set the value of the data member “base1int”.
3rd we created a “Base2” class which consists of protected data member integer
“base2int”.
4th the “Base2” class consists of a public function “set_base2int”. This function will
set the value of the data member “base2int”.
5th we created a “Base3” class which consists of protected data member integer
“base3int”.
2nd the “Base3” class consists of a public function “set_base3int”. This function will
set the value of the data member “base3int”.
The code for the “Derived” class is shown below. “Derived” class will inherit all the base
classes.
1st we created a “Derived” class which is inheriting “Base1”, “Base2”, and “Base3”
classes in public mode.
2nd the “Derived” class consists of the public member function “show”.
4th the function “show” will first print the values of “base1int”, “base2int”, and
“base3int” individually and then print the sum of all three values.
It can be clearly seen that the class “Derived” is inheriting class “Base1”, “Base2”, and
“Base3”. This is an example of multiple inheritances. The code main program is shown
below.
int main()
{
Derived harry;
harry
harry.set_base1int(25);
harry
harry.set_base2int(5);
harry
harry.set_base3int(15);
harry
harry.show();
harry
return 0;
}
Questions
You have to create 2 classes:
return 0;
}
Ambiguity Resolution in Inheritance in C++ | C++
Tutorials for Beginners #43
In this tutorial, we will discuss ambiguity resolution in inheritance in C++
class Base1{
public:
void greet(){
cout<<"How
cout are you?"<<endl
endl;
}
};
class Base2{
public:
void greet()
{
cout << "Kaise ho?" << endl
endl;
}
};
int main(){
// Ambibuity 1
Base1 base1obj;
base1obj
base2obj;
Base2 base2obj
base1obj.greet();
base1obj
base2obj.greet();
base2obj
Derived d;
d
d.greet();
d
return 0;
}
The main thing to note here is that when the function “greet” is called by the object “d” it
will run the “greet” function of the “Base2” class because we had specified it using
scope resolution operator “::” to get rid ambiguity. The output for the following program
is shown in figure 1.
Figure 1: Output
class B{
public:
void say(){
cout<<"Hello
cout world"<<endl;
endl
}
};
class D: public B{
int a
a;
// D's new say() method will override base class's say() method
public:
void say()
{
cout << "Hello my beautiful people" << endl;
endl
}
};
1. We have created a “B” class which consists of public member function “say”. The
function “say” will print “hello world”
2. We have created a “D” class that is inheriting the “B” class. The “D” class consists
of the public member function “say”. The function “say” will print “Hello my beautiful
people”
The main thing to note here is that both “B” and “D” classes have the same function
“say”, So if the class “D” will call the function “say” it will override the base class “say”
method because compiler by default run the method which is already written in its own
body. But if the function “say” was not present in the class “D” then the compiler will run
the method of the class “B”.
int main(){
// Ambibuity 2
b;
B b
b.say();
b
D d;
d
d.say();
d
return 0;
}
Figure 2: Output
Virtual Base Class in C++ | C++ Tutorials for Beginners #44
In this tutorial, we will discuss virtual base class in C++
As shown in figure 1,
The main thing to note here is that the data members and member functions of class “A” will be inherited twice in class “D” because
class “B” and “C” are the parent classes of class “D” and they both are being derived from class “A”.
So when the class “D” will try to access the data member or member function of class “A” it will cause ambiguity for the compiler and
the compiler will throw an error. To solve this ambiguity we will make class “A” as a virtual base class. To make a virtual base class
“virtual” keyword is used.
When one class is made virtual then only one copy of its data member and member function is passed to the classes inheriting it. So
in our example when we will make class “A” a virtual class then only one copy of the data member and member function will be
passed to the classes “B” and “C” which will be shared between all classes. This will help to solve the ambiguity.
The syntax of the virtual base class is shown in the code snippet below,
#include <iostream>
using namespace std
std;
class A {
public:
void say()
{
cout << "Hello world"<<endl
endl;
}
};
class B : public virtual A {
};
class C : public virtual A {
};
class D : public B, public C {
};
As shown in figure 1,
So when the class “Result” will try to access the data member or member function of
class “Student” it will cause ambiguity for the compiler and the compiler will throw an
error. To solve this ambiguity we will make class “Student” as a virtual base class. To
make a virtual base class “virtual” keyword is used.
When one class is made virtual then only one copy of its data member and member
function is passed to the classes inheriting it. So in our example when we will make
class “Student” a virtual class then only one copy of data member and member function
will be passed to the classes “Test” and “Sports” which will be shared between all
classes. This will help to solve the ambiguity.
class Student{
protected:
int roll_no;
roll_no
public:
void set_number(int a
a){
roll_no = a
a;
}
void print_number(void){
cout<<"Your roll no is "<< roll_no
cout roll_no<<endl
endl;
}
};
void print_marks(void){
int main(){
harry;
Result harry
harry.set_number(4200);
harry
harry.set_marks(78.9, 99.5);
harry
harry.set_score(9);
harry
harry.display();
harry
return 0;
}
In multiple inheritances, base classes are constructed in the order in which they appear in the class deceleration. For example if
there are three classes “A”, “B”, and “C”, and the class “C” is inheriting classes “A” and “B”. If the class “A” is written before
class “B” then the constructor of class “A” will be executed first. But if the class “B” is written before class “A” then the
constructor of class “B” will be executed first.
In multilevel inheritance, the constructors are executed in the order of inheritance. For example if there are three classes “A”,
“B”, and “C”, and the class “B” is inheriting classes “A” and the class “C” is inheriting classes “B”. Then the constructor will run
according to the order of inheritance such as the constructor of class “A” will be called first then the constructor of class “B” will
be called and at the end constructor of class “C” will be called.
Special Syntax
C++ supports a special syntax for passing arguments to multiple base classes
The constructor of the derived class receives all the arguments at once and then will pass the call to the respective base
classes
The body is called after the constructors is finished executing
Syntax Example:
Derived-Constructor (arg1
Derived arg1, arg2
arg2, arg3…
arg3….): Base 1-Constructor (arg1
arg1,arg2
arg2), Base 2-Constructor(arg3
arg3,arg4
arg4)
{
….
} Base 1-Constructor (arg1
arg1,arg2
arg2)
The constructors for virtual base classes are invoked before a non-virtual base class
If there are multiple virtual base classes, they are invoked in the order declared
Any non-virtual base class are then constructed before the derived class constructor is executed
Solution to Exercise on Cpp Inheritance | C++ Tutorials for Beginners #47
A solution to Exercise on Inheritance in C++
As I have given you an exercise on inheritance to solve in the previous tutorial. In this tutorial, we will see the solution to that
exercise. So the question was to make three classes “SimpleCalculator”, “ScientificCalculator” and “HybridCalculator”.
In “SimpleCalculator” class you have to take input of 2 numbers and perform function (+, -, *, /)
In “ScientificCalculator” class you have to take input of 2 numbers and perform any 4 scientific operations
You have to inherit both “SimpleCalculator” and “ScientificCalculator” classes with the “HybridCalculator” class. You have to
make an object of the “HybridCalculator” class and display the results of “SimpleCalculator” and “ScientificCalculator” classes.
class SimpleCalculator {
int a
a, bb;
public:
void getDataSimple()
{
cout<<"Enter the value of a"<<endl
cout endl;
cin>>a;
cin
cout<<"Enter the value of b"<<endl;
cout endl
cin>>b;
cin
}
void performOperationsSimple(){
cout<<"The value of a + b is:
cout "<<a + b<<endl
b endl;
cout<<"The value of a - b is:
cout "<<a - b<<endl
b endl;
cout<<"The value of a * b is:
cout "<<a * b<<endl
b endl;
cout<<"The value of a / b is:
cout "<<a / b<<endl
b endl;
}
};
1. We created a class “SimpleCalculator” which contains two private data members “a” and “b”
2. The class “SimpleCalculator” contains two member functions “getDataSimple” and “performOperationsSimple”
3. The function “getDataSimple” will take 2 numbers as input
4. The function “performOperationsSimple” will perform the operations “+, -, *, /”
class ScientificCalculator{
int a
a, b
b;
public:
void getDataScientific()
{
cout << "Enter the value of a" << endl
endl;
cin >> a
a;
cout << "Enter the value of b" << endl;
endl
cin >> b
b;
}
void performOperationsScientific()
{
cout << "The value of cos(a) is: " << cos(a) << endl;
endl
cout << "The value of sin(a) is: " << sin(a) << endl;
endl
cout << "The value of exp(a) is: " << exp(a) << endl;
endl
cout << "The value of tan(a) is: " << tan(a) << endl;
endl
}
};
1. We created a class “ScientificCalculator” which contains two private data members “a” and “b”
2. The class “ScientificCalculator” contains two member functions “getDataScientific” and “performOperationsScientific”
3. The function “getDataScientific” will take 2 numbers as input
4. The function “performOperationsScientific” will perform the operations “cos, sin, exp, tan”
};
As shown in code snippet 3, we created a “HybridCalculator” class which is inheriting the “SimpleCalculator” class and
“ScientificCalculator” class.
int main()
{
HybridCalculator calc;
calc
calc.getDataScientific();
calc
calc.performOperationsScientific();
calc
calc.getDataSimple();
calc
calc.performOperationsSimple();
calc
return 0;
}
/*
Case1:
class B: public A{
// Order of execution of constructor -> first A() then B()
};
Case2:
class A: public B, public C{
// Order of execution of constructor -> B() then C() and A()
};
Case3:
class A: public B, virtual public C{
// Order of execution of constructor -> C() then B() and A()
};
*/
class Base1{
int data1
data1;
public:
Base1(int i
i){
data1 = i
i;
cout<<"Base1 class constructor called"<<endl
cout endl;
}
void printDataBase1(void){
cout<<"The value of data1 is "<<data1
cout data1<<endl
endl;
}
};
class Base2{
int data2
data2;
public:
Base2(int i
i){
data2 = i
i;
cout << "Base2 class constructor called" << endl
endl;
}
void printDataBase2(void){
cout << "The value of data2 is " << data2 << endl
endl;
}
};
1. We have created a “Base1” class which consists of private data member “data1”
and parameterized constructor which takes only one argument and set the value of
data member “data1”. The “Base1” class also contains the member function
“printDataBase1” which will print the value of data member “data1”.
2. We have created a “Base2” class which consists of private data member “data2”
and parameterized constructor which takes only one argument and set the value of
data member “data2”. The “Base2” class also contains the member function
“printDataBase2” which will print the value of data member “data2”.
3. We have created a “Derived” class that is inheriting base classes “Base1” and
“Base2”. The “Derived” class consists of private data members “derived1” and
“derived2”. The “Derived” class contains parameterized constructor which calls the
“Base1” and “Base2” class constructors to pass the values, it also assigns the
values to the data members “derived1” and “derived2”. The “Derived” class also
contains member functions “printDataDerived”. The function “printDataDerived” will
print the values of the data member “derived1” and “derived2”.
The main thing to note here is that the constructors will be executed in the order in
which the classes are being inherited. As in the example program above the “Base2”
class is being inherited first and then “Base1” class is being inherited, so the
constructor of “Base2” class will be executed first. The main program of the following
example code is shown below.
int main(){
Derived harry(1, 2, 3, 4);
harry.printDataBase1();
harry
harry.printDataBase2();
harry
harry.printDataDerived();
harry
return 0;
}
/*
Syntax for initialization list in constructor:
constructor (argument-list) : initilization-section
{
assignment + other code;
}
public:
Test(int i, int j
i j) : a(i), b(j)
{
cout << "Constructor executed"<<endl
endl;
cout << "Value of a is "<<a<<endl
endl;
cout << "Value of b is "<<b<<endl
endl;
}
};
int main()
{
Test t(4, 6);
return 0;
}
1. We have created a “test” class that consists of private data member “a” and “b”
and parameterized constructor which takes two arguments and sets the value of
data member “a” and “b” by using the initialization list. The constructor will also
print the value of data member “a” and “b”.
2. In the main program object “t” is created of the “test” data type and the values (4,
6) are passed.
The main thing to note here is that if we use the code shown below to initialize data
members the compiler will throw an error because the data member “a” is being
initialized first and the “b” is being initialized second so we have to assign the value to
“a” data member first.
Test(int i
i, int j
j) : b(j), a(i+b)
But if we use the code shown below to initialize data members the compiler will not
throw an error because the data member “a” is being initialized first and we are
assigning the value to the data member “a” first.
Test(int i
i, int j
j) : a(i), b(a + j
j)
Pointers in C++
Pointers are variables that are used to store the address. Pointers are created using “*”. An example program of pointers is shown
below
#include<iostream>
using namespace std;
std
int main(){
// Basic Example
int a = 4;
int* ptr = &a;
cout<<"The value of a is "<<*(ptr
cout ptr)<<endl
endl;
return 0;
}
As shown in figure 1, we get the output value “4” because pointer “ptr” is pointing to the variable “a” and the value of the variable “a”
is “4” that is why we get the output “4”.
New Keyword
Another example program for pointers and the use of a “new” keyword is shown below.
#include<iostream>
using namespace std;
std
int main(){
return 0;
}
As shown in figure 2, we get the output value “40.78” because pointer “p” is pointing to an address whose value is “40.78”.
Another example program for pointers array and the use of a “new” keyword with an array is shown below.
#include<iostream>
using namespace std;
std
int main(){
return 0;
}
1. We created an integer pointer “arr” and dynamically created an array of size three which is assigned to the pointer “arr”
2. The values “10”, “20”, and “30” are assigned to the ”1”, “2”, and “3” indexes of an array
3. And printed the value at the array indexes “1”, “2”, and “3”
As shown in figure 3, we get the output values “10”, “20”, and “30”.
Delete Keyword
Another example program for pointers array and the use of the “delete” keyword with an array is shown below.
#include<iostream>
using namespace std;
std
int main(){
return 0;
}
1. We created an integer pointer “arr” and dynamically created an array of size three which is assigned to the pointer “arr”
2. The values “10”, “20”, and “30” are assigned to the ”1”, “2”, and “3” indexes of an array
3. Before printing the values we used the “delete” keyword
4. And printed the value at the array indexes “1”, “2”, and “3”
As shown in figure 2, we get the garbage value in the output instead of “10”, “20”, and “30” because we have used “delete” keyword
before printing the values due to which the space used by an array gets free and we get the garbage value in return.
Pointers to Objects and Arrow Operator in CPP | C++
Tutorials for Beginners #51
In this tutorial, we will discuss pointers to objects and arrow operator in C++
#include<iostream>
using namespace std;
std
class Complex{
int real,
real imaginary;
imaginary
public:
void getData(){
cout<<"The real part is "<< real
cout real<<endl
endl;
cout<<"The
cout imaginary part is "<< imaginary<<
imaginary endl;
endl
}
};
int main(){
Complex *ptr = new Complex;
Complex
(*ptr
ptr).setData(1, 54); is exactly same as
(*ptr).getData();
ptr is as good as
return 0;
}
1. We created a class “Complex”, which contains two private data members “real”
and “imaginary”.
2. The class “complex” contains two member functions “getdata” and “setdata”
3. The Function “setdata” will take two parameters and assign the values of
parameters to the private data members “real” and “imaginary”
4. The Function “getdata” will print the values of private data members “real” and
“imaginary”
5. In the main program object is created dynamically by using the “new” keyword and
its address is assigned to the pointer “ptr”
6. The member function “setdata” is called using the pointer “ptr” and the values “1,
54” are passed.
7. The member function “getdata” is called using the pointer “ptr” and it will print the
values of data members.
The main thing to note here is that we called the member function with pointers instead
of object but still it will give same result because pointer is pointing to the address of
that object.
class Complex{
int real
real, imaginary
imaginary;
public:
void getData(){
cout<<"The real part is "<< real
cout real<<endl
endl;
cout<<"The imaginary part is "<< imaginary
cout imaginary<<endl
endl;
}
};
int main(){
Complex *ptr = new Complex
Complex;
ptr->setData(1, 54);
ptr
ptr->getData();
ptr
// Array of Objects
Complex *ptr1 = new Complex
Complex[4];
ptr1->setData(1, 4);
ptr1
Code Snippet 2: Pointer to Objects with Arrow Operator Example Program 2
1. We created a class “Complex”, which contains two private data members “real”
and “imaginary”.
2. The class “complex” contains two member functions “getdata” and “setdata”
3. The Function “setdata” will take two parameters and assign the values of
parameters to the private data members “real” and “imaginary”
4. The Function “getdata” will print the values of private data members “real” and
“imaginary”
5. In the main program object is created dynamically by using the “new” keyword and
its address is assigned to the pointer “ptr”
6. The member function “setdata” is called using the pointer “ptr” with the arrow
operator “->” and the values “1, 54” are passed.
7. The member function “getdata” is called using the pointer “ptr” with the arrow
operator “->” and it will print the values of data members.
8. Array of objects is created dynamically by using the “new” keyword and its address
is assigned to the pointer “ptr1”
9. The member function “setdata” is called using the pointer “ptr1” with the arrow
operator “->” and the values “1, 4” are passed.
10. The member function “getdata” is called using the pointer “ptr1” with the arrow
operator “->” and it will print the values of data members.
The main thing to note here is that we called the member function with pointers by
using arrow operator “->” instead of the dot operator “.” but still it will give the same
results.
Array of objects can be defined as an array that’s each element is an object of the
class. In this tutorial, we will use the pointer to store the address of an array of objects.
An example program is shown below to demonstrate the concept of an array of objects
using pointers.
#include<iostream>
using namespace std;
std
class ShopItem
{
int id;
id
float price;
price
public:
void setData(int aa, float b
b){
id = a;
a
price = b
b;
}
void getData(void){
cout<<"Code
cout of this item is "<< id<<
id endl;
endl
cout<<"Price of this item is "<<price
cout price<<endl
endl;
}
};
int main(){
int size = 3;
ShopItem *ptr = new ShopItem [size];
size
ShopItem *ptrTemp = ptr
ptr;
int p,
p i;i
float qq;
for (i = 0; i < size;
size i++)
i
{
cout<<"Enter
cout Id and price of item "<< i+1<<
i endl;
endl
cin>>p>>q;
cin
// (*ptr).setData(p, q);
ptr->setData(p, q
ptr q);
ptr++;
ptr
}
return 0;
}
1. We created an integer variable “size” and assigned the value “3” to it.
2. Array of objects of size “3” is created dynamically by using the “new” keyword and
its address is assigned to the pointer “ptr”
3. The address of pointer “ptr” is assigned to another pointer “ptrTemp”
4. Two integer variables “p” and “i” are declared and one float variable ”q” is declared
5. We created a “for” loop which will run till the size of array and will take input for “id”
and “price” from user at run time. In this “for” loop “setdata” function is called using
pointer “ptr”; the function will set the values of “id” and “price” which user will enter.
The value of the pointer “ptr” is incremented by 1 in every iteration of loop.
6. We created another “for” loop which will run till the size of array and will print the
number of the item. In this “for” loop “getdata” function is called using pointer “ptr”;
the function will print the values of “id” and “price”. The value of the pointer
“ptrTemp” is incremented by 1 in every iteration of loop.
The main thing to note here is that in the first “for” loop we are incrementing the value of
the pointer “ptr” because it is pointing to the address of array of objects and when loop
will run every time the function “setdata” will be called by the different object. If we don’t
increment the value of the pointer “ptr” the each time function “setdata” will be called by
the same object. Likewise in the second loop we are incrementing the pointer “ptrTemp”
so that the function “getdata” could be called by each object in the array.
#include<iostream>
using namespace std;
std
class A{
int a;
a
public:
void setData(int a
a){
this->a = a
a;
}
void getData(){
cout<<"The
cout value of a is "<<a<<endl
endl;
}
};
int main(){
A a;
a
a.setData(4);
a
a.getData();
a
return 0;
}
“this” pointer can be used to return a reference to the invoking object. An example
program is shown below.
class A{
int aa;
public:
A & setData(int aa){
this->a = a
a;
return *this;
}
void getData(){
cout<<"The
cout value of a is "<<a<<endl
endl;
}
};
int main(){
a;
A a
a.setData(4).getData();
a
return 0;
}
1. In the function “setData” the reference of the object is returned using “this” pointer.
2. In the main program by using a single object we have made a chain of the function
calls. The main thing to note here is that the function “setData” is returning an
object on which we have used the “getData” function. so we don’t need to call the
function “getData” explicitly.
Polymorphism in C++ | C++ Tutorials for Beginners #54
In this tutorial, we will discuss polymorphism in C++
Polymorphism in C++
“Poly” means several and “morphism” means form. So we can say that polymorphism is
something that has several forms or we can say it as one name and multiple forms.
There are two types of polymorphism:
Compile-time polymorphism
Run time polymorphism
1. Function Overloading
This is a feature that lets us create more than one function and the functions have the
same names but their parameters need to be different. If function overloading is done in
the program and function calls are made the compiler already knows that which
functions to execute.
2. Operator Overloading
This is a feature that lets us define operators working for some specific tasks. For
example, we can overload the operator “+” and define its functionality to add two
strings. Operator loading is also an example of compile-time polymorphism because the
compiler already knows at the compile time which operator has to perform the task.
3. Virtual Function
A function that is in the parent class but redefined in the child class is called a virtual
function. “virtual” keyword is used to declare a virtual function.
Pointers to Derived Classes in C++ | C++ Tutorials for
Beginners #55
In this tutorial, we will discuss pointer to derived class in C++
#include<iostream>
using namespace std;
std
class BaseClass{
public:
int var_base;
var_base
void display(){
cout<<"Dispalying
cout Base class variable var_base "<<var_base<<
var_base endl;
endl
}
};
int main(){
BaseClass * base_class_pointer
base_class_pointer;
BaseClass obj_base;
obj_base
DerivedClass obj_derived;
obj_derived
base_class_pointer = &obj_derived
obj_derived; // Pointing base class pointer to derived c
base_class_pointer->var_base = 34;
base_class_pointer
// base_class_pointer->var_derived= 134; // Will throw an error
base_class_pointer->display();
base_class_pointer
base_class_pointer->var_base = 3400;
base_class_pointer
base_class_pointer->display();
base_class_pointer
DerivedClass * derived_class_pointer
derived_class_pointer;
derived_class_pointer = &obj_derived
obj_derived;
derived_class_pointer->var_base = 9448;
derived_class_pointer
derived_class_pointer->var_derived = 98;
derived_class_pointer
derived_class_pointer->display();
derived_class_pointer
return 0;
}
#include<iostream>
using namespace std;
std
class BaseClass{
public:
int var_base=1;
var_base
virtual void display(){
cout<<"1 Dispalying Base class variable var_base "<<var_base
cout var_base<<endl
endl;
}
};
1. We created a class “BaseClass” which contains public data member “var_base” which has the value “1” and member function
“display”. The member function “display” will print the value of data member “var_base”
2. We created another class “DerivedClass” which is inheriting “BaseClass” and contains data member “var_derived” which has
the value “2” and member function “display”. The member function “display” will print the values of data members “var_base”
and “var_derived”
int main(){
BaseClass * base_class_pointer
base_class_pointer;
BaseClass obj_base;
obj_base
DerivedClass obj_derived;
obj_derived
base_class_pointer = &obj_derived
obj_derived;
base_class_pointer->display();
base_class_pointer
return 0;
}
The main thing to note here is that if we don’t use the “virtual” keyword with the “display” function of the base class then beside of
the point that we have pointed our base call pointer to derived class object still the compiler would have called the “display” function
of the base class because this is its default behavior as we have seen in the previous tutorial.
But we have used the “virtual” keyword with the “display” function of the base class to make is virtual function so when the display
function is called by using the base class pointer the display function of the derived class will run because the base class pointer is
pointing to the derived class object.
class CWH{
protected:
string title;
title
float rating
rating;
public:
CWH(string s
s, float r
r){
title = ss;
rating = rr;
}
virtual void display(){}
};
1. We created a class “CHW” which contains protected data members “title” which has a “string” data type and “rating” which has
a “float” data type.
2. The class “CWH” has a parameterized constructor which takes two parameters “s” and “r” and assign their values to the data
members “title” and “rating”
3. The class “CHW” has a virtual function void “display” which does nothing
1. We created a class “CHWVideo” which is inheriting the “CWH” class and contains private data members “videoLength” which
has a “float” data type.
2. The class “CWHVideo” has a parameterized constructor which takes three parameters “s”, “r” and “vl”. The constructor of the
base class is called in the derived class and the values of the variables “s” and “r” are passed to it. The value of the parameter
“vl” will be assigned to the data members “videoLength”
3. The class “CHWVideo” has a function void “display” which will print the values of the data members “title”, “rating” and
“videoLength”
1. We created a class “CHWText” which is inheriting the “CWH” class and contains private data members “words” which has an
“int” data type.
2. The class “CWHText” has a parameterized constructor which takes three parameters “s”, “r” and “wc”. The constructor of the
base class is called in the derived class and the values of the variables “s” and “r” are passed to it. The value of the parameter
“wc” will be assigned to the data members “words”
3. The class “CHWText” has a function void “display” which will print the values of the data members “title”, “rating” and “words”
int main(){
string title;
title
float rating, vlen;
rating vlen
int words;
words
CWH* tuts
CWH tuts[2];
tuts[0] = &djVideo
tuts djVideo;
tuts[1] = &djText
tuts djText;
tuts[0]->display();
tuts
tuts[1]->display();
tuts
return 0;
1. We created a string variable “title”, float variables “rating”, “vlen” and integer variable “words”
2. For the code with harry video class, we have assigned “Django tutorial” to the string “title”, “4.56” to the float “vlen” and “4.89” to
the float “rating”.
3. An object “djVideo” is created of the data type “CWHVideo” and the variables “title”, “rating” and “vlen” are passed to it.
4. For the code with harry text class, we have assigned “Django tutorial text” to the string “title”, “433” to the integer “words” and
“4.19” to the float “rating”.
5. An object “djText” is created of the data type “CWHText” and the variables “title”, “rating” and “words” are passed to it.
6. Two pointers array “tuts” is created of the “CWH” type
7. The address of the “djVideo” is assigned to “tuts[0]” and the address of the “djText” is assigned to “tuts[1]”
8. The function “display” is called using pointers “tuts[0]” and “tuts[1]”
The main thing to note here is that if we don’t use the “virtual” keyword with the “display” function of the base class then the “display”
function of the base class will run.
But we have used the “virtual” keyword with the “display” function of the base class to make is a virtual function so when the
display function is called by using the base class pointer the display function of the derived class will run because the base class
pointer is pointing to the derived class object.
To demonstrate the concept of abstract class and pure virtual function an example
program is shown below.
class CWH{
protected:
string title;
title
float rating
rating;
public:
CWH(string ss, float r
r){
title = s;s
rating = r r;
}
virtual void display()=0;
};
1. We created a class “CHW” which contains protected data members “title” which
has “string” data type and “rating” which has “float” data type.
2. The class “CWH” has a parameterized constructor which takes two parameters “s”
and “r” and assign their values to the data members “title” and “rating”
3. The class “CHW” has a pure virtual function void “display” which is declared by 0.
The main thing to note here is that as the “display” function is a pure virtual
function it is compulsory to redefine it in the derived classes.
CWH* tuts
CWH tuts[2];
tuts[0] = &djVideo
tuts djVideo;
tuts[1] = &djText
tuts djText;
tuts[0]->display();
tuts
tuts[1]->display();
tuts
return 0;
1. We created a string variable “title”, float variables “rating”, “vlen” and integer
variable “words”
2. For the code with harry video class we have assigned “Django tutorial” to the string
“title”, “4.56” to the float “vlen” and “4.89” to the float “rating”.
3. An object “djVideo” is created of the data type “CWHVideo” and the variables
“title”, “rating” and “vlen” are passed to it.
4. For the code with harry text class we have assigned “Django tutorial text” to the
string “title”, “433” to the integer “words” and “4.19” to the float “rating”.
5. An object “djText” is created of the data type “CWHText” and the variables “title”,
“rating” and “words” are passed to it.
6. Two pointers array “tuts” is created of the “CWH” type
7. The address of the “djVideo” is assigned to “tuts[0]” and the address of the “djText”
is assigned to “tuts[1]”
8. The function “display” is called using pointers “tuts[0]” and “tuts[1]”
The main thing to note here is that if we don’t override the pure virtual function in the
derived class the compiler will throw an error as shown in figure 1.
The file is a patent of data which is stored in the disk. Anything written inside the file is called a patent, for example: “#include” is a
patent. The text file is the combination of multiple types of characters, for example, semicolon “;” is a character.
The computer read these characters in the file with the help of the ASCII code. Every character is mapped on some decimal number.
For example, ASCII code for the character “A” is “65” which is a decimal number. These decimal numbers are converted into a
binary number to make them readable for the computer because the computer can only understand the language of “0” and “1”.
The reason that computers can only understand binary numbers is that a computer is made up of switches and switches only
perform two operations “true” or “false”.
Read File
Write File
An image is shown below to show the process of file read and write.
As shown in figure 1,
1. The user can provide input to the C++ program by using keyboard through “cin>>” keyword
2. The user can get output from the C++ program on the monitor through “cout<<” keyword
3. The user can write on the file
4. The user can read the file
File I/O in C++: Reading and Writing Files | C++ Tutorials for Beginners #60
In this tutorial, we will discuss File I/O in C++: Reading and Writing Files
fstreambase
ifstream --> derived from fstreambase
ofstream --> derived from fstreambase
In order to work with files in C++, you will have to open it. Primarily, there are 2 ways to open a file:
An example program is shown below to demonstrate the concept of reading and writing files
#include<iostream>
#include<fstream>
int main(){
string st = "Harry bhai";
// Opening files using constructor and writing it
ofstream out("sample60.txt"); // Write operation
out<<st
out st;
return 0;
}
int main(){
st2;
string st2
// Opening files using constructor and reading it
ifstream in("sample60b.txt"); // Read operation
in>>st2
in st2;
getline(in
in, st2
st2);
cout<<st2
cout st2;
return 0;
}
Before jumping on to the main thing, we’ll first give ourselves a quick revision of the
things we had learned previously.
We had learned about the three most useful classes when we talk about File I/O,
namely,
1. fstreambase
2. ifstream
3. ofstream.
All the above three classes can be used in a program by first including the header file,
fstream.
We learnt reading from a file using ifstream. Below snippet will help you recollect the
same.
string st;
st
// Opening files using constructor and reading it
ifstream in("this.txt"); // Read operation
in>>st
in st;
We learnt reading from a file using ofstream. Below snippet will help you recollect the
same.
string st = "Harry bhai";
// Opening files using constructor and writing it
ofstream out("this.txt"); // Write operation
out<<st
out st;
Let me make these codes functional in the same program for you to easily understand
the workflow.
Suppose we have a file named sample60.txt in the same directory, we can easily call
the file infinite number of times in the same program only by maintaining different
connections for different purposes, using
<object_name>.close();
object_name
Now, let’s move on to our systems. Open your editors as well. Don’t forget to include
the header file, <fstream>.
Follow these steps below to first write into the empty file:
1. Create a text file “sample60.txt” in the same directory as that of the program.
2. Create a string variable name.
3. Create an object hout(name it whatever you wish) using ofstream passing the text
file, sample60.txt into it. This establishes a connection between your program and
the text file.
4. Take input from the user using cin into the name string.(You can write manually as
well)
5. Pass this name string to the object hout. The string name gets written in the text
file.
6. Disconnect the file with the program since we are done writing to it
using hout.close().
Since the file has been disconnected from the program, we can connect it again for any
other purpose in the same program independently.
Follow these steps below to read from the file we just wrote into:
1. Create a string variable content.
2. Create an object hin(name it whatever you wish) using ifstream passing the text
file, sample60.txt into it. This establishes a new connection between your program
and the text file.
3. Fill in the string using the object hin. (Use getline, which we talked about in the last
video, to take into input the whole line from the text file.)
4. Give output to the user, the string we filled in with the content in the text file.
5. Disconnect the file with the program since we are done reading from it
using hin.close().
#include<iostream>
#include<fstream>
int main(){
Thank you, friends for being with me throughout, hope you liked the tutorial. If you
haven’t checked out the whole playlist yet, move on to codewithharry.com or my
YouTube channel to access it. I hope you enjoy them.
In the next tutorial, we’ll be covering the use of open() and eof() functions, see you
there, till then keep coding.
File I/O in C++: open() and eof() functions | C++
Tutorials for Beginners #62
In this tutorial, we are going to learn about the member functions open and eof of the
objects we learnt about previously.
I remember teaching you all about the two methods to open a text file in our C++
program, first one using a constructor which we discussed in the last tutorial, and the
second one, using the member function open, which is to be dealt with today.
The member function open is used to connect the text file to the C++ program when
passed into it.
1. Unlike what we did earlier passing the text file in the object while creating it, we’ll
first just declare an object out(any name you wish) of the type ofstream and use its
open method to open the text file in the program.
2. We’ll pass some string lines to the text file using the out operation.
3. We’ll now close the file using the close function. Now closing is explicitly used to
make the system know that we are done with the file. It is always good to use this.
This was all about writing to a file. We’ll now move to the eof function’s vitality in File
I/O.
#include <iostream>
#include <fstream>
int main()
{
//connecting the object out to the text file using the member function open()
out.open("sample60.txt");
out
The member function eof(End-of-file) returns a boolean true if the file reaches the end
of it and false if not.
1. We’ll first declare an object in(any name you wish) of the type ifstream and use its
open method similar to what we did above, to open the text file in the program.
2. And now, we’ll declare the string variable st to store the content we’ll receive from
the text file sample60.txt.
3. Now since we not only want the first or some two or three strings present in
the text file, but the whole of it, and we have no idea of what the length of the file
is, we’ll use a while loop.
4. We’ll run the while loop until the file reaches the end of it, and that gets checked by
using eof() , which returns 1 or true if the file reaches the end. Till then a 0 or false.
5. We’ll use getline to store the whole line in the string variable st. Don’t forget to
include the header file <string>.
6. This program now successfully prints the whole content of the text file.
#include <iostream>
#include <fstream>
#include <string>
int main()
{
// declaring an object of the type ifstream
ifstream in;
in
//declaring string variable st
string st;
st
//opening the text file into in
in.open("sample60.txt");
in
// giving output the string lines by storing in st until the file reaches the
while (in
in.eof()==0)
{
// using getline to fill the whole line in st
getline(in,
in st);
st
cout<<st
cout st<<endl
endl;
}
return 0;
}
So, this was all about File I/O in C++. Learning to detect the eof and opening files in a
C++ program in two ways, writing to it and reading from the same, was all a big deal,
and you successfully completed them all. Cheers.
Thank you, friends, for being with me throughout, hope you liked the tutorial. If you
haven’t checked out the whole playlist yet, move on to codewithharry.com or my
YouTube channel to access it. I hope you enjoy them.
In the next tutorial, we’ll be starting a topic, a must for competitive programmers, C++
templates, see you there, till then keep coding.
C++ Templates: Must for Competitive Programming |
C++ Tutorials for Beginners #63
It has been quite a journey till here, and I feel grateful to have you all with me in the
same. We have covered a lot in C++ and there is yet a great deal left. But we’ll make
everything ahead a cakewalk together.
Today we have in the box, the most important topic for all you enthusiastic
programmers, C++ templates. We’ll follow the below-mentioned roadmap:
A template is believed to escalate the potential of C++ several fold by giving it the
ability to define data types as parameters making it useful to reduce repetitions of the
same declaration of classes for different data types. Declaring classes for every other
data type(which if counted is way too much) in the very first place violates the DRY(
Don’t Repeat Yourself) rule of programming and on the other doesn't completely utilise
the potential of C++.
It is very analogous to when we said classes are the templates for objects, here
templates itself are the templates of the classes. That is, what classes are for objects,
templates are for classes.
Why templates?
1. DRY Rule:
To understand the reason behind using templates, we will have to understand the effort
behind declaring classes for different data types. Suppose we want to have a vector for
each of the three(can be more) data types, int, float and char. Then we’ll obviously write
the whole thing again and again making it awfully difficult. This is where the saviour
comes, the templates. It helps parametrizing the data type and declaring it once in the
source code suffice. Very similar to what we do in functions. It is because of this, also
called, ‘parameterized classes’.
1. Generic Programming:
We had to copy the same thing again and again for different data types, but a template
solves it all. Refer to the syntax section for how.
Below is the template for a vector of int data type, and it goes similarly for float char
double, etc.
class vector {
int *arr
arr;
int size
size;
public:
};
Syntax:
Now we can easily use this template to declare umpteen number of classes in our main
scope. Be it int, float, or arr vector.
#include <iostream>
using namespace std
std;
};
int main() {
vector<int> myVec1();
vector
vector<float> myVec2();
vector
return 0;
}
Templates are believed to be very useful for people who pursue competitive
programming. It makes their work several folds easier. It gives them an edge over
others. It is a must because it saves you a lot of time while programming. And I believe
you ain’t want to miss this opportunity to learn, right?
So, get to the playlist as soon as you can. Save yourselves some time and get over
your competitors.
Thank you, friends, for being with me throughout, hope you liked the tutorial. And If you
haven’t checked out the whole playlist yet, it’s never too late, move on
to codewithharry.com or my YouTube channel to access it. I hope you enjoy
them. Templates are an inevitable part of this process of learning C++. You just cannot
afford to miss this. In the next tutorial, we’ll be writing a program using templates for
your better understanding, see you there, till then keep coding.
Writing our First C++ Template in VS Code | C++
Tutorials for Beginners #64
In the last tutorial, we learnt about what a template is, why a template is used in
programming and what its syntax is. Let's give ourselves a quick revision of everything
about templates.
Long story short, a template does the same thing to a class, what a class does to the
objects. It parametrizes the data type hence making it easy for us to use different
classes without having to write the whole thing again and again, violating the DRY rule.
Templates furthermore give our program a generic view, where declaring one template
suffices the task.
Today, we’ll learn to make a program using templates to give you a better
understanding about its uses. I'll make the process effortless for you to learn, so, you
stay calm and keep learning.
Now suppose we have two integer vectors and we want to calculate their Dot Product.
This part should not be troublesome since we have learnt pretty well the use of classes
and constructors. We had learnt to write the code like the one mentioned below.
#include <iostream>
using namespace std
std;
class vector
{
public:
int *arr
arr;
int size;
size
vector(int mm)
{
size = m
m;
arr = new int[size
size];
}
int dotProduct(vector &v){
int d=0;
d
for (int i = 0; i < size
size; i
i++)
{
d+=this->arr
d arr[i]*v.arr
arr[i];
}
return d;
d
}
};
int main()
{
So, this was all about creating a class and an embedded function to calculate the dot
product of two integer vectors. But this program would obviously fail to calculate the dot
products for some different data types. It would demand an entirely different class. But
we’ll save ourselves the effort and the time by declaring a template. Let’s see how:
Understanding the changes, we made in the above program to generalise it for all
data types:
1. First and foremost, we defined a template with class T where T acts as a variable
data type.
2. We then changed the data type of arr to T, changed its constructor to T from int,
changed everything except the size of the vector, to a variable T. The function then
returned T. This has now changed the class from specific to general.
3. We then very easily added a parameter, while defining the vectors, of its data type.
And the compiler itself transformed the class accordingly. Here we passed a float
and the code handled it very efficiently.
4. The output we received was:
6.82
D:\MyData\Business\code playground\C++
PS D playground\C course>
course
#include <iostream>
using namespace std
std;
int main()
Imagine how tough it would have been without these templates, you'd have made
different classes for different data types handling them clumsily increasing your efforts
and proportionally your chances of making errors. So, this is a life saviour.
Thank you, friends for being with me throughout, hope you liked the tutorial. If you
haven’t checked out the whole playlist yet, move on to codewithharry.com or my
YouTube channel to access it. I hope you enjoy them. In the next tutorial, we’ll be
learning about further uses of a template and multiple parameters, see you there, till
then keep coding.
C++ Templates: Templates with Multiple Parameters |
C++ Tutorials for Beginners #65
In the last tutorial, we had ample understanding of a template and its uses. We had
created a template which would calculate the Dot Product of two vectors of any data
type just by declaring a simple template parameterizing the data type we usually
hardcoded in the classes. This already made our task easier but here we are, with our
next tutorial focusing on how to handle multiple parameters in a template.
To give you a short overview of how templates work with multiple parameters, you can
think of it as a function where you have that power to pass different parameters of the
same or different data types. A simple template with two parameters would look
something like this. The only effort it demands is the declaration of parameters. We’ll
get through it thoroughly by making a real program, so, let’s go.
#include<iostream>
using namespace std;
std
/*
template<class T1, class T2>
class nameOfClass{
//body
}
*/
int main(){
//body of main
}
class myClass{
public:
int data1;
data1
char data2;
data2
void display(){
cout<<this->
cout data1<<" "<<this->data2
data1 data2;
}
};
Refer to changes we have done below to parametrize both our data types using a
single template:
1. We have declared data1 and data2 with data types T1 and T2 respectively.
2. We have applied the constructor filling the values we receive from the main into
data1 and data2.
3. Finally, we have displayed both of them.
template<class T1, class T2>
class myClass{
public:
data1;
T1 data1
data2;
T2 data2
myClass(T1 a,
a T2 b){
b
data1 = a
a;
data2 = b
b;
}
void display(){
cout<<this->data1
cout data1<<" "<<this->data2
data2;
}
};
Let me now show you how this template works for different parameters. I’ll pass
different data types from the main and see if it's flexible enough.
int main()
{
myClass<int,
myClass char> obj(1, 'c');
obj.display();
obj
}
And the output received was this, which is correct. Let’s feed another one.
1 c
PS D:
D \MyData\Business\code playground\C++
playground\C course>
course
Figure 1: Output of code snippet 3.
int main()
{
myClass<int,
myClass float> obj(1,1.8 );
obj.display();
obj
}
1 1.8
PS D:
D \MyData\Business\code playground\C++
playground\C course>
course
And this was all about templates with multiple parameters, just don’t miss out the
commas while defining the parameters in a template. And you can have 2, 3 or more of
them according to your needs. Could you believe how luxurious it has become to work
with customized data types? It is now you, who’ll decide what the data type of some
variable in a class should be. It is no longer pre-specified. It has given you some
unimaginable power which, if you realise, can save you a lot of energy and time.
C++ Templates: Class Templates with Default Parameters
| C++ Tutorials for Beginners #66
So far, we have already covered the C++ templates with single parameters. In the last
tutorial, we learnt about templates with multiple parameters, when it comes to handling
different data types of two or more containers.
Today, we’ll be learning a very easy yet powerful attribute of templates, its ability to
have default parameters. Its ability to have default specifications about the data type,
when it receives no arguments from the main.
So, let's start by making a program manifesting the use of default parameters in a C++
template. Refer to the code snippet below and follow the steps:
Since we are done defining the templates and class, we can very easily move to the
main where we’ll see how these work. Understanding code snippet 2:
1. Firstly, we’ll create an object, let's name it h, of the class Harry. And we’ll pass into
it three values, an int, a float and a char, suppose 4, 6.4 and c respectively. Now
since we have not specified the data types of the values we have just entered, the
default data types, int, float and char would be considered.
2. We’ll then display the values, which you’ll be seeing when we run the same.
3. And then we’ll create another object g, of the class Harry but this time, with the
data types of our choice. Let’s specify them to be float, char and char.
4. We can then pass some values into it, suppose 1.6, o, and c and call the display
function again.
5. These objects are sufficient to give us the main concept behind using a default
parameter and the variety of classes we could make via this one template.
int main()
{
Harry<>
Harry h(4, 6.4, 'c');
h.display();
h
cout << endl
endl;
Harry<float, char, char> g(1.6, 'o', 'c');
Harry
g.display();
g
return 0;
}
We’ll now refer to the output the above codes combinedly gave. As you can see below,
it worked all fine. Had we not specified the default parameters; the above program
would have thrown an error. Thanks to this feature of C++ templates.
The value of a is 4
The value of b is 6.4
The value of c is c
Today, we’ll be interested in knowing what a function template does. So. let’s get
ourselves on our editors.
Suppose we want to have a function which calculates the average of two integers. So,
this must be very easy for you to formulate. Look for the snippet below.
1. We have declared a float function named funcAverage which will have two integers
as its parameters, a and b.
2. We stored its average in a float variable avg and returned the same to the main.
3. Later we called this function by value, and stored the returned float in a float
variable a and printed the same.
4. So this was the small effort we had to make to get a function which calculates the
average of two integers.
#include<iostream>
using namespace std;
std
float funcAverage(int a
a, int b
b){
float avg
avg= (a+b)/2.0;
return avg
avg;
}
int main(){
float a;
a
a = funcAverage(5,2);
printf("The average of these numbers is %f",a);
return 0;
}
But the effort we made here defining a single function for two integers increases several
folds when we demand for a similar function for two floats, or one float and one integer
or many more data type combinations. We just cannot repeat the procedure and violate
our DRY rule. We’ll use function templates very similar to what we did when we had to
avoid defining more classes.
See what are the subtle changes we had to make, to make this function generic.
We’ll first declare a template with two data type parameters T1 and T2. And replace the
data types we mentioned in the function with them. And that’s it. Our function has
become general for all sorts of data types. Refer to the snippet below.
template<class T1, class T2>
float funcAverage(T1 a,
a T2 b){
b
float avg
avg= (a+b)/2.0;
return avg;
avg
}
Let’s call this function by passing into it two sorts of data types combination, first, two
integers and then one integer and one float. And see if the outputs are correct.
int main(){
float a;
a
a = funcAverage(5,2);
printf("The average of these numbers is %f",a);
return 0;
}
int main(){
float a;
a
a = funcAverage(5,2.8);
printf("The average of these numbers is %f",a);
return 0;
}
Code snippet: Calling the function by passing one integer and one float
So, this is how we utilize this powerful tool to avoid writing such overloaded codes. And
this was all about function templates with single or multiple parameters. We covered
them all in this tutorial.
Member Function Templates & Overloading Template
Functions in C++ | C++ Tutorials for Beginners #68
So, since we have finished learning about the two template categories, we can now
swiftly dive deep into if it's possible for a template function to get overloaded, and if yes,
then how.
Before starting to know what an overloaded template function is, we’ll learn how to
declare a template function outside a using the scope resolution operator, ‘::’.
First, we’ll revise how to write a function inside the class by just following the snippet
given below.
This was an unchallenging task. But when we need the function to be declared outside
the class, we follow the code snippet 2.
template <class T>
class Harry
{
public:
data;
T data
Harry(T a
a)
{
data = a
a;
}
void display()
{
cout << data
data;
}
};
Here, we first write the function declaration in the class itself. Then move to the outside
and use the scope resolution operator before the function and after the name of the
class Harry along with the data type T. We must specify the function data type, which is
void here. And it must be preceded by the template declaration for class T.
And write the display code inside the function and this will behave as expected. See the
output below the snippet.
So to check if it's working all fine, we’ll call this function from the main.
int main()
{
Harry<int>
Harry h(5.7);
cout << h
h.data << endl
endl;
h.display();
h
return 0;
}
5
5
PS D:\ MyData\Business
D: MyData Business\code playground\
playground C++ course>
course
1. We made two void functions, one specified and one generic using a template.
2. The first one receives an integer and prints the integer with a different prefix.
3. The generic one receives the value as well as the data type and prints the value
with a different prefix.
4. Now, we’ll wish to see the output of the following functions, by calling them from
the main. Refer to the main program below the snippet below.
#include <iostream>
using namespace std
std;
void func(int a
a){
cout<<"I
cout am first func() "<<a<<endl
endl;
}
template<class T>
void func(T a
a){
cout<<"I am templatised func() "<<a<<endl
cout endl;
}
And now when we call the function func, we’ll be interested to know which one among
the two it calls. So here since we’ve entered a value with an integer parameter, it finds
its exact match in the overloading and calls that itself. That is, it gives its exact match
the highest priority. Refer to the output below the snippet:
int main()
{
func(4); //Exact match takes the highest priority
return 0;
}
I am first func() 4
PS D:
D \MyData\Business\code playground\C++
playground\C course>
course
If we hadn’t created the first function with int data type, the call would have gone to the
templatised func only because a template function is an exact match for every kind of
data type.
The C++ Standard Template Library (STL) | C++ Tutorials
for Beginners #69
We have been waiting so long to start this, but creating a base is as important as any
other phase. So, today we’ll be starting the most awaited topic, the STL( Standard
Template Library).
There is a reason why I’ve been saying that this topic is a must for all the competitive
programmers out there,so let’s deal with that first.
An STL is a library of generic functions and classes which saves you time and energy
which you would have spent constructing for your use. This helps you reuse these well
tested classes and functions umpteenth number of times according to your own
convenience.
To put this simply, STL is used because it is not a good idea to reinvent something
which is already built and can be used to innovate things further. Suppose you go to a
company who builds cars, they will not ask you to start from scratch, but to start from
where it is left. This is the basic idea behind using STL.
COMPONENTS OF STL:
1. Containers
2. Algorithm
3. Iterators
Containers:
Container is an object which stores data. We have different containers having their own
benefits. These are the implemented template classes for our use, which can be used
just by including this library. You can even customise these template classes.
Algorithms:
Algorithms are a set of instructions which manipulates the input data to arrive at some
desired result. In STL, we have already written algorithms, for example, to sort some
data structure, or search some element in an array. These algorithms use template
functions.
Iterators:
Iterators are objects which refer to an element in a container. And we handle them very
much similarly to a pointer. Their basic job is to connect algorithms to the container and
play a vital role in manipulation of the data.
Suppose we have a container of integers, and we want to sort them in ascending order.
We will have pointers which will help moving elements to places by pointing to it,
following a well-constructed algorithm. So, here a container gets sorted by following an
algorithm by the use of pointers. This is how they work in accordance with each other.
Containers in C++ STL | C++ Tutorials for Beginners #70
In the last tutorial, we had briefed about the three components of STL, namely,
Containers, objects which store data, Algorithms, set of procedures to process data,
and Iterators, objects which point to some element in a container. Today, in this tutorial,
we will be interested in discussing more about containers.
1. Sequence Containers
2. Associative Containers
3. Derived Containers
When we talked about containers, we said containers are objects which store data, but
what are its three types all about? We’ll discuss that too.
Sequence Containers
A sequence container stores that data in a linear fashion. Refer to the illustration
below to understand what storing something in a linear fashion means.
Sequence containers include Vector, List, Dequeue etc. These are some of the most
used sequence containers.
Associative Containers
Derived Containers
As the name suggests, these containers are derived from either the sequence or the
associative containers. They often provide you with some better methods to deal with
your data. They deal with real life modelling. Some examples of derived containers
are Stack, Queue, Priority Queue, etc. The following illustration give you the idea of
how a stack works.
Figure 3: A stack, works on the first in first out [FIFO] method
Now since we have got the basic idea of all the three types of containers, a question
which might arise is when to use which. So, let’s deal with that,
In Lists, we have,
vector<
vector data_type>
data_type vector_name;
vector_name
And suppose we want to have a vector of integers; the following program would do the
needful:
#include<iostream>
#include<vector>
int main(){
vector<int> vec1
vector vec1;
return 0;
}
One benefit of using vectors, is that we can insert as many elements we want in a
vector, without having to put some size parameter as in an array. In an array of 10
elements, for adding the 11th one, we’ll have to make an array again.
Vectors provide certain methods to be used to access and utilise the elements of a
vector, first one being, the push_back method. To access all the methods and member
functions in detail, you can visit this site , std::vector - C++ Reference. This will be very
handy and useful to you. I’ll show you how some of them work in a program. Refer to
the code snippet 3.
push_back() and size():
#include<iostream>
#include<vector>
using namespace std;
std
void display(vector
vector<int> &v){
for (int i = 0; i < v v.size(); ii++)
{
cout<<v[i]<<" ";
cout
}
cout<<endl
cout endl;
}
int main(){
vector<int> vec1
vector vec1;
int element
element, size
size;
cout<<"Enter the size of your vector"<<endl
cout endl;
cin>>size
cin size;
for (int i = 0; i < size
size; i
i++)
{
cout<<"Enter an element to add to this vector: ";
cout
cin>>element
cin element;
vec1.push_back(element
vec1 element);
}
display(vec1);
vec1
return 0;
}
Code Snippet 3: A program to demonstrate the use of push_back and size
methods
Similarly, we can even build float vectors, and we can even templatise the display
function.
pop_back():
This method of vectors, deletes the last element of the vector. Refer to the code snippet
and the following output below.
display(vec1);
vec1
vec1.pop_back();
vec1
display(vec1
vec1);
So, now you can see how this method deleted the last element 7 from the vector.
Enter the size of your vector
3
Enter an element to add to this vector
vector: 5
Enter an element to add to this vector
vector: 3
Enter an element to add to this vector
vector: 7
5 3 7
5 3
D:\MyData\Business\code playground\C++
PS D playground\C course>
course
This method of vectors inserts an element to the position the iterator is pointing to. Now
how to evoke that iterator? Refer to the snippet and the output below:
We can generate an iterator using the scope resolution iterator by the following syntax:
Using begin () points the iterator to the starting of the vector. We can now increment
the pointer according to our choice and insert any element at that position.
display(vec1
vec1);
vector<int> :: iterator iter = vec1
vector vec1.begin();
vec1.insert(iter
vec1 iter,566);
display(vec1
vec1);
Similarly, v.at(i) can be used instead of v[i]. They will work the same.
We have different ways to declare a vector. I’ll list some of them through the snippet
below.
vector<int>
vector vec1;
vec1 //zero length integer vector
vector<char> vec2(4); //4-element character vector
vector
vector<char>
vector vec3(vec2);//4-element
vec2 character vector from vec2
vector<int> vec4(6,3); //6-element vector of 3s
vector
So this was all the basics of a vector, and enough for you to get started using it. With
this I’ll finish today's tutorial. I’ll recommend you all to visit my DSA playlist, Data
Structures and Algorithms Course in Hindi to get acquainted with all the data structures
and more.
List In C++ STL | C++ Tutorials for Beginners #72
Before this tutorial, we covered templates, STL, and the last video was an efficient
introduction to the vectors. Today, we’ll learn about Lists in C++ STL.
A List is a bi-directional linear storage of elements. Few key features as to why a list
should be used is,
An array stores the elements in a contiguous manner in which inserting some element
calls for a shift of other elements, which is time taking. But in a list, we can simply
change the address the pointer is pointing to. I’ll show you how these work via an
illustration.
Let's move on to our editors and write some code using lists and its methods.
#include<iostream>
#include<list>
void display(list<int>
list &lst){
lst
list<int> :: iterator it;
list it
for (it = lst.begin();
lst it != lst.end();
lst it++)
it
{
cout<<*
cout it<<"
it ";
}
int main(){
list<int> list1
list list1; //empty list of 0 length
list1.push_back(5);
list1
list1.push_back(7);
list1
list1.push_back(1);
list1
list1.push_back(9);
list1
list1.push_back(12);
list1
display(list1
list1);
5 7 1 9 12
PS D:
D \MyData\Business\code playground\C++
playground\C course>
course
We can also enter elements in a list using the iterator and its dereferencer. See the
snippet below.
int main(){
display(list2
list2);
return 0;
}
45 6 9
PS D:
D \MyData\Business\code playground\C++
playground\C course>
course
We can use pop_back() to delete one element from the back of the list everytime we
call this method and pop_front() to delete elements from the front. These commands
decrease the size of the list by 1. Let me show you how these work by using them for
list1 we made.
list1.pop_back();
list1
display(list1
list1);
list1.pop_front();
list1
display(list1);
list1
5 7 1 9
7 1 9
PS D:
D \MyData\Business\code playground\C++
playground\C course>
course
Using remove():
We can remove an element from a list by passing it in the list remove method. It will
delete all the occurrences of that element. The remove method receives one value as a
parameter and removes all the elements which match this parameter. Refer to the use
of remove in the below snippet.
int main(){
list<int>
list list1;
list1 //empty list of 0 length
list1.push_back(5);
list1
list1.push_back(7);
list1
list1.push_back(1);
list1
list1.push_back(9);
list1
list1.push_back(9);
list1
list1.push_back(12);
list1
list1.remove(9);
list1
display(list1);
list1
return 0;
}
Code Snippet 5: Deleting elements in list using remove()
5 7 1 12
PS D:
D \MyData\Business\code playground\C++
playground\C course>
course
Using sort():
We can sort a list in ascending order using its sort method. Look for the demo below.
display(list1);
list1
list1.sort();
list1
display(list1);
list1
5 7 1 9 12
1 5 7 9 12
PS D:
D \MyData\Business\code playground\C++
playground\C course>
course
I consider this much to be enough for lists. There are still a lot of them, but you will
require no more, and even if you feel like exploring more, move onto std::list - C++
Reference and read about all the lists methods. This was all from my side. For more
information on linked lists, visit my DSA playlist, Data Structures and Algorithms Course
in Hindi.
Map In C++ STL | C++ Tutorials for Beginners #73
So far, we have learned about vectors and lists in C++ STL, and today we will be
learning about maps in C++ STL. It is important to clarify that whatever I have taught
and whatever I will be teaching in the coming tutorials about STL isn’t everything. And it
is definitely not all. These are just the most important STL containers we will use. You
have already seen how to explore more about STL from C++ - Containers.
We will now discuss maps, and because it is impractical to have every method on our
fingers, I’d ask you all to also refer to the following website std::map - C++ Reference
A map in C++ STL is an associative container which stores key value pairs. To
elaborate, a map stores a key of some data type and its corresponding values of some
data type. For example: a teacher wants to store the marks of students which in future
can be accessed by their names. Here, keys are the student names, and their marks
are the corresponding values. Refer to the illustration below:
We can now shift to our editors and see how maps can be used in C++. Don’t forget to
include the header file <map>.
map <data_type_of_key
data_type_of_key, data_type_of_value>
data_type_of_value variable_name;
variable_name
And we can now write the program for storing the key value pairs of students' names
and students’ marks keeping in mind the illustration above. Refer to the snippet below.
1. Include the header file map and string( if using string methods).
2. Let's create a map in which the key is a string (names) and the values are integers
(marks), and we'll call it marksMap.
3. And to assign some key a value, we use the index method. Here the index of a
map element will be the students’ name and the value will be the marks.
4. Make some 4-5 elements.
5. Identify the iterator of this map by using the scope resolution operator.
6. Loop through the map elements using two map methods; begin() to point at the
beginning of the map, and end() to point next to the last element of the map.
7. While we loop through the map, we use the dereference operator * to fetch the
element present where the pointer is pointing to. And since a map stores element
in a key value pair, we can use its first and second method to access the keys and
the values respectively. .first accesses the first value of a pair that is our map key
here, and .second accesses the second value of the pair that is our map values
here.
8. There is one thing to keep in mind: Maps always sort these pairs by the key
elements. You can review the output of the following snippet to see how these
pairs are sorted.
#include<iostream>
#include<map>
#include<string>
int main(){
map<string
map string,int> :: iterator iter;
iter
for (iter = marksMap
marksMap.begin(); iter != marksMap
marksMap.end(); iter
iter++)
{
cout<<(*iter
cout iter).first
first<<" "<<(*iter
iter).second
second<<"\n";
}
return 0;
}
As you can see, the map pairs got sorted according to its key.
Aditya 65
Atul 58
Kishlay 78
Rohit 57
Sachin 53
D:\MyData\Business\code playground\C++
PS D playground\C course>
course
We have one more method to insert elements in a map. We can use .insert()
We will insert some elements into our map in snippet 2 by using the insert method.
We can see the output to check if the above two pairs got inserted into the map or not.
Aditya 65
Akshat 46
Atul 58
Kishlay 78
Rohan 89
Rohit 57
Sachin 53
D:\MyData\Business\code playground\C++
PS D playground\C course>
course
And I’d ask you all to explore more of these methods from the links I gave you above
and start writing codes using them. This is the best way to learn. For example, you can
use the size() method to get the size of the map container , empty() method to check if
the map container is empty or not, and it returns a boolean. Therefore, this shouldn't be
a big deal for you.
Function Objects (Functors) In C++ STL | C++ Tutorials
for Beginners #74
In the last tutorial we completed learning about some of the most commonly used
containers, vector, list, map and their methods. Today we’ll start with function objects in
C++ STL.
That is, we can then use a function as an object. The question that might have been
raised in your mind would be, why to substitute a function with an object? The
answer is to make them all usable in an Object-Oriented Programming paradigm. Now
what does that mean? We’ll try decoding the purpose of using functions as an object
via a program. So, hold onto your editors.
Be sure to include the header file < functional> before you do anything else.
And let’s create an array of some 6 elements.
Suppose we want to sort this array in ascending order. So we’ll include a header
file <algorithm> and write the syntax of the sort object which is,
And let’s just sort from the beginning to the 5th element.
And run a loop to see the resultant array.
#include<iostream>
#include<functional>
#include<algorithm>
int main(){
return 0;
}
Output of the above program is given below. And you’ll notice that the last element
remained untouched.
1
2
4
54
73
7
PS D:
D \MyData\Business\code playground\C++
playground\C course>
course
But what if we wanted to sort the same array in descending order, since the sort
function can default sort in ascending order only? So, here comes our
saviour, functional objects. Our sort function also takes a third parameter which is a
functor ( functional object).
Among all the different functors we have, the one to help this sort function to sort
the array in descending order, is the greater<int>().
sort( arr
arr, arr
arr+6, greater
greater< int >( ));
And that’s it. Our array will now get sorted in descending order.
It would be unnecessarily lengthy to review all the functors, as my role was to introduce
them to you and show you how they are used.
In addition, I invite you all to explore the other function objects on the site Function
objects. You should go through them lightly because a lot of them would be
overwhelming to you as a beginner. We use most of these functors for our STL
algorithms, so you might want to check all those algorithms on Functions in <algorithm>
- C++ Reference. You can go through them at your own pace. Incorporate them into
your programs. Take advantage of them and use them how you see fit.