cpp_tutorial
cpp_tutorial
What is C++?
C++ is a middle-level programming language developed by Bjarne Stroustrup starting in
1979 at Bell Labs. C++ runs on a variety of platforms, such as Windows, Mac OS, and the
various versions of UNIX. C++ is an extension of the C programming language with object-
oriented programming concepts. Or, we can say, "C++ is a superset of C programming
with additional implementation of object-oriented concepts".
#include <iostream>
using namespace std;
i
C++ Tutorial
#include <iostream>
using namespace std;
int main() {
cout << "Hello, World!"; // prints Hello, World!
return 0;
}
There are many C++ compilers available that you can use to compile and run the above-
mentioned program:
Apple C++. Xcode
Bloodshed Dev-C++
Clang C++
Cygwin (GNU C++)
Mentor Graphics
MINGW - "Minimalist GNU for Windows"
GNU CC source
IBM C++
Intel C++
Microsoft Visual C++
Oracle C++
HP C++
Features of C++
The following are the features of C++ programming language −
C language compatibility: C++ provides backward compatibility with C; it
supports all features of C language.
ii
C++ Tutorial
iii
C++ Tutorial
C++ Practice
After completing the C++ tutorial, you can go through these sections to practice the
concepts that you have learned:
C++ Interview Questions
C++ Online Quiz
iv
C++ Tutorial
v
C++ Tutorial
C++ <forward_list>
C++ <list>
C++ <map>
C++ <multimap>
C++ <queue>
C++ <priority_queue>
C++ <set>
C++ <stack>
C++ <unordered_map>
C++ <unordered_set>
C++ <vector>
C++ <algorithm>
C++ <iterator>
C++ Revision
For a quick revision of C++ programming, go through these links −
C++ Quick Guide
C++ Cheat Sheet
C++ STL Cheat Sheet
vi
C++ Tutorial
Structures
Class and objects
Inheritance
Polymorphism
C++ Standard Template Library
vii
C++ Tutorial
Table of Contents
About the Tutorial .......................................................................................................................................... i
11. C++ Numeric Data Types ............................................................................. Error! Bookmark not defined.
12. C++ Character (char) Data Type ................................................................... Error! Bookmark not defined.
13. C++ Boolean (bool) Data Type ..................................................................... Error! Bookmark not defined.
14. C++ Variables and Types .............................................................................. Error! Bookmark not defined.
16. C++ Declare Multiple Variables ................................................................... Error! Bookmark not defined.
viii
C++ Tutorial
25. C++ Date and Time ...................................................................................... Error! Bookmark not defined.
26. C++ decision making statements ................................................................. Error! Bookmark not defined.
31. C++ nested switch statements ..................................................................... Error! Bookmark not defined.
ix
C++ Tutorial
47. Multiple Function Parameters in C++ .......................................................... Error! Bookmark not defined.
48. C++ Recursion (Recursive Function) ............................................................. Error! Bookmark not defined.
55. C++ Passing Arrays to Functions .................................................................. Error! Bookmark not defined.
56. Return Array from Functions in C++ ............................................................ Error! Bookmark not defined.
63. C++ Classes and Objects .............................................................................. Error! Bookmark not defined.
64. C++ Class Member Functions ....................................................................... Error! Bookmark not defined.
65. C++ Class Access Modifiers .......................................................................... Error! Bookmark not defined.
66. Static Members of a C++ Class ..................................................................... Error! Bookmark not defined.
x
C++ Tutorial
67. Static Data Members in C++ ........................................................................ Error! Bookmark not defined.
68. C++ - Static Member Function ..................................................................... Error! Bookmark not defined.
73. C++ Class Constructor and Destructor ......................................................... Error! Bookmark not defined.
78. C++ - Constructor with Default Arguments .................................................. Error! Bookmark not defined.
80. C++ - Constructor Initialization List .............................................................. Error! Bookmark not defined.
81. Dynamic Initialization Using Constructors in C++......................................... Error! Bookmark not defined.
85. C++ Overloading (Operator and Function) ................................................... Error! Bookmark not defined.
89. Interfaces in C++ (Abstract Classes) ............................................................. Error! Bookmark not defined.
xi
C++ Tutorial
90. C++ Files and Streams .................................................................................. Error! Bookmark not defined.
91. C++ Reading From File ................................................................................. Error! Bookmark not defined.
xii
C++ Tutorial
C++ Basics
xiii
1. C++ Overview: Introduction to C++ Programming
C++ Tutorial
Language
Object-Oriented Programming
C++ fully supports object-oriented programming, including the five pillars of object-
oriented development −
Classes and Objects
Encapsulation
Data hiding
Inheritance
Polymorphism
Standard Libraries
Standard C++ consists of three important parts −
The core language giving all the building blocks including variables, data types, and
literals, etc.
The C++ Standard Library giving a rich set of functions manipulating files, strings,
etc.
The Standard Template Library (STL) giving a rich set of methods manipulating
data structures, etc.
14
C++ Tutorial
Learning C++
The most important thing while learning C++ is to focus on concepts.
The purpose of learning a programming language is to become a better programmer; that
is, to become more effective at designing and implementing new systems and at
maintaining old ones.
C++ supports a variety of programming styles. You can write in the style of Fortran, C,
Smalltalk, etc., in any language. Each style can achieve its aims effectively while
maintaining runtime and space efficiency.
Uses of C++
The uses of C++ are as follows:
C++ is used by hundreds of thousands of programmers in essentially every
application domain.
C++ is being highly used to write device drivers and other software that rely on
direct manipulation of hardware under realtime constraints.
C++ is widely used for teaching and research because it is clean enough for
successful teaching of basic concepts.
Anyone who has used either an Apple Macintosh or a PC running Windows has
indirectly used C++ because the primary user interfaces of these systems are
written in C++.
#include <iostream>
using namespace std;
int main() {
cout << "Hello, World!"; // prints Hello, World!
return 0;
}
Hello, World!
Advantages of C++
C++ programming language has many advantages over other languages. Some of these
advantages are listed as follows −
Rich Standard Library: C++ language provides the users with a rich and useful
Standard Template Library (STL). This library has a lot of in-built methods and data
structure templates to make coding in this language efficient and quick.
15
C++ Tutorial
Disadvantages of C++
C++ programming language also has some disadvantages, which are listed below:
Error Detection: C++ provides the facility of low-level design and is very close to
the hardware of the system. Hence, this may lead the user to carry out small errors
that are difficult to observe and detect.
Large Syntax: C++ has a very lengthy code base, and many programmers find it
difficult to write such a lengthy syntax. This has drawn backlash from the user-
base of languages like Python, Go, etc., which are easier to code and simpler to
execute.
Learning Curve: As compared to Python and Go, C++ has a very steep learning
curve. Users feel that the initial building phase is very tough to learn, and there
are many concepts that beginners find difficult to understand.
16
C++ Tutorial
17
2. C++ Environment Setup C++ Tutorial
Text Editor
This will be used to type your program. Examples of few editors include Windows Notepad,
OS Edit Command, Brief, Epsilon, EMACS, and vim or vi.
Name and version of text editor can vary on different operating systems. For example,
Notepad will be used on Windows and vim or vi can be used on windows as well as Linux,
or UNIX.
The files you create with your editor are called source files and for C++, they typically
are named with the extension .cpp, .cp, or .c.
A text editor should be in place to start your C++ programming.
C++ Compiler
This is an actual C++ compiler, which will be used to compile your source code into final
executable program.
Most C++ compilers don't care what extension you give to your source code, but if you
don't specify otherwise, many will use .cpp by default.
Most frequently used and free available compiler is GNU C/C++ compiler, otherwise you
can have compilers either from HP or Solaris if you have the respective Operating Systems.
UNIX/Linux Installation
If you are using Linux or UNIX then check whether GCC is installed on your system by
entering the following command from the command line −
$ g++ -v
If you have installed GCC, then it should print a message such as the following −
18
C++ Tutorial
If GCC is not installed, then you will have to install it yourself using the detailed instructions
available at https://gcc.gnu.org/install/
Mac OS X Installation
If you use Mac OS X, the easiest way to obtain GCC is to download the Xcode development
environment from Apple's website and follow the simple installation instructions.
Xcode is currently available at developer.apple.com/technologies/tools/.
Windows Installation
To install GCC at Windows, you need to install MinGW. To install MinGW, go to the MinGW
homepage, www.mingw.org, and follow the link to the MinGW download page. Download
the latest version of the MinGW installation program which should be named MinGW-
<version>.exe.
While installing MinGW, at a minimum, you must install gcc-core, gcc-g++, binutils, and
the MinGW runtime, but you may wish to install more.
Add the bin subdirectory of your MinGW installation to your PATH environment variable
so that you can specify these tools on the command line by their simple names.
When the installation is complete, you will be able to run gcc, g++, ar, ranlib, dlltool, and
several other GNU tools from the Windows command line.
19
3. C++ Basic Syntax C++ Tutorial
Example
Let us look at a simple code that would print the words Hello World.
#include <iostream>
using namespace std;
Example Explanation
20
C++ Tutorial
$ g++ hello.cpp
$ ./a.out
Hello World
Make sure that g++ is in your path and that you are running it in the directory containing
file hello.cpp.
You can compile C/C++ programs using makefile. For more details, you can check
our 'Makefile Tutorial'.
x = y;
y = y + 1;
21
C++ Tutorial
add(x, y);
A block is a set of logically connected statements that are surrounded by opening and
closing braces. For example −
{
cout << "Hello World"; // prints Hello World
return 0;
}
C++ does not recognize the end of the line as a terminator. For this reason, it does not
matter where you put a statement in a line. For example −
x = y;
y = y + 1;
add(x, y);
is the same as
x = y; y = y + 1; add(x, y);
C++ Identifiers
A C++ identifier is a name used to identify a variable, function, class, module, or any other
user-defined item. An identifier starts with a letter A to Z or a to z or an underscore (_)
followed by zero or more letters, underscores, and digits (0 to 9).
C++ does not allow punctuation characters such as @, $, and % within identifiers. C++
is a case-sensitive programming language. Thus, Manpower and manpower are two
different identifiers in C++.
Here are some examples of acceptable identifiers −
C++ Keywords
The following list shows the reserved words in C++. These reserved words may not be
used as constant or variable or any other identifier names.
22
C++ Tutorial
Trigraphs
A few characters have an alternative representation called a trigraph sequence. A trigraph
is a three-character sequence that represents a single character and the sequence always
starts with two question marks.
Trigraphs are expanded anywhere they appear, including within string literals and
character literals, in comments, and in preprocessor directives.
Following are most frequently used trigraph sequences −
Trigraph Replacement
23
C++ Tutorial
??= #
??/ \
??' ^
??( [
??) ]
??! |
??< {
??> }
??- ~
All the compilers do not support trigraphs and they are not advised to be used because of
their confusing nature.
Whitespace in C++
A line containing only whitespace, possibly with a comment, is known as a blank line, and
C++ compiler totally ignores it.
Whitespace is the term used in C++ to describe blanks, tabs, newline characters and
comments. Whitespace separates one part of a statement from another and enables the
compiler to identify where one element in a statement, such as int, ends and the next
element begins.
Statement 1
int age;
In the above statement, there must be at least one whitespace character (usually a space)
between int and age for the compiler to be able to distinguish them.
Statement 2
fruit = apples + oranges; // Get the total fruit
In the above statement 2, no whitespace characters are necessary between fruit and =,
or between = and apples, although you are free to include some if you wish for readability
purpose.
24
C++ Tutorial
Example
This example demonstrates the C++ program based on an object-oriented approach.
#include <iostream>
using namespace std;
class Numbers {
private:
int a;
int b;
public:
// Function to set values
void setValues(int x, int y) {
a = x;
b = y;
}
int main() {
// Create an object of Numbers class
Numbers num;
// Set values
num.setValues(10, 20);
25
C++ Tutorial
return 0;
}
1. Class Declaration
A class is a template for an object, or we can say a class is a factory to produce an object.
It is a kind of custom data type, where you construct a structure for an object.
A class declaration has the following parts:
Access modifiers: C++ supports three types of access
modifiers: private, public, and protected. Accessibilities of the data members
and member functions are defined by the access modifiers.
Data members and member functions: The variables used in the class
declaration are known as data members, and the member functions are those
functions that work on the data members.
Example
As per the above example, the following part of the declaration of a class –
class Numbers {
private:
int a;
int b;
public:
// Function to set values
void setValues(int x, int y) {
a = x;
26
C++ Tutorial
b = y;
}
The following are the data members which are defined under the private access modifier
i.e., these data members can be used by the member functions within the class –
private:
int a;
int b;
2. Object Creation
In the above example, the following statement is the object creation statement −
Numbers num;
27
4. Comments in C++ C++ Tutorial
C++ Comments
Program comments are explanatory statements that you can include in the C++ code.
These comments help anyone reading the source code. All programming languages allow
different forms of comments.
// Text to be commented
Example
In the following example, we are creating single-line comments −
#include <iostream>
using namespace std;
int main() {
// this is a single line comment
cout << "Hello world!" << endl;
// for a new line, we have to use new comment sections
cout << "This is second line.";
return 0;
}
Output
The output of the code is −
Hello world!
28
C++ Tutorial
/* This is a comment */
/*
C++ comments can also
span multiple lines
*/
Example
In the following example, we are creating multi-line comments −
#include <iostream>
using namespace std;
int main() {
/* Printing hello world!*/
cout << "Hello World!" << endl;
/*
This is a multi-line comment
Printing another message
Using cout
*/
cout << "Tutorials Point";
return 0;
}
Output
The output of the code is −
Hello World!
Tutorials Point
29
C++ Tutorial
#include <iostream>
using namespace std;
int main() {
cout << "This line" /*what is this*/ << " contains a comment" << endl;
return 0;
}
Output
The output of the code is −
Example
The following example explains the usage of single-line comments within statements −
#include <iostream>
using namespace std;
int main() {
cout << "This line" // what is this
<< " contains a comment" << endl;
return 0;
}
Output
The output of the code is −
Nesting Comments
Within a /* and */ comment, // characters have no special meaning. Within
a // comment, /* and */ have no special meaning. Thus, you can "nest" one kind of
comment within the other kind.
Example
30
C++ Tutorial
The following example explains the usage of comments within comments using nesting −
#include <iostream>
using namespace std;
int main() {
/* Comment out printing of Hello World:
*/
cout << "New, Hello World!";
return 0;
}
Output
The output of the code is −
Purpose of Comments
Comments are used for various purposes in C++. Some of the main areas of application
of comments are as follows −
To represent a short and concise step in the program for users to understand
better.
To explain a step in a detailed way that is not expressed explicitly in the code.
To leave different hints for users to grab in the code itself.
To leave comments for fun or recreation.
To temporarily disable part of the code for debugging purposes.
To add metadata to the code for future purposes.
To create documentation for the code, for example, in Github pages.
31
5. C++ "Hello, World!" Program C++ Tutorial
Printing "Hello, World!" is the first program in C++. Here, this prints "Hello, World" on
the console (output screen). To start learning C++, it is the first step to print sometime
on the screen.
int main() {
cout << "Hello, World!";
return 0;
}
Output
This program will print "Hello, World!" on the output screen. The output will be −
Hello, World!
32
C++ Tutorial
#include <iostream>
int main() {
cout << "Hello, World!";
return 0;
}
return 0;
33
C++ Tutorial
==========
End of ebook preview
If you liked what you saw…
Buy it from our store @ https://www.tutorialspoint.com/index.htm
34