0% found this document useful (0 votes)
5 views136 pages

Programming Masru

C++ is a versatile, high-performance programming language developed as an extension of C, offering control over system resources and memory. It is widely used in various applications, including operating systems and embedded systems, and features object-oriented programming for code reusability. This document serves as an introductory tutorial covering the basics of C++, including syntax, variables, data types, user input, and fundamental programming concepts.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
5 views136 pages

Programming Masru

C++ is a versatile, high-performance programming language developed as an extension of C, offering control over system resources and memory. It is widely used in various applications, including operating systems and embedded systems, and features object-oriented programming for code reusability. This document serves as an introductory tutorial covering the basics of C++, including syntax, variables, data types, user input, and fundamental programming concepts.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 136

C++ Introduction

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

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

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

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

Why Use C++


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

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

C++ is an object-oriented programming language which gives a clear structure


to programs and allows code to be reused, lowering development costs.

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

C++ is fun and easy to learn!

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


C++ or vice versa

Get Started
This tutorial will teach you the basics of C++.
It is not necessary to have any prior programming experience.

C++ Getting Started

C++ Get Started


To start using C++, you need two things:

 A text editor, like Notepad, to write C++ code


 A compiler, like GCC, to translate the C++ code into a language that the
computer will understand

There are many text editors and compilers to choose from. In this tutorial, we
will use an IDE (see below).

C++ Install IDE


An IDE (Integrated Development Environment) is used to edit AND compile the
code.

Popular IDE's include Code::Blocks, Eclipse, and Visual Studio. These are all free,
and they can be used to both edit and debug C++ code.

Note: Web-based IDE's can work as well, but functionality is limited.

We will use Code::Blocks in our tutorial, which we believe is a good place to


start.

You can find the latest version of Codeblocks


at http://www.codeblocks.org/downloads/26. Download the mingw-setup.exe file,
which will install the text editor with a compiler.

C++ Quickstart
Let's create our first C++ file.

Open Codeblocks and go to File > New > Empty File.


Write the following C++ code and save the file as myfirstprogram.cpp (File >
Save File as):

myfirstprogram.cpp
#include <iostream>
using namespace std;

int main() {
cout << "Hello World!";
return 0;
}

Don't worry if you don't understand the code above - we will discuss it in detail
in later chapters. For now, focus on how to run the code.

In Codeblocks, it should look like this:

Then, go to Build > Build and Run to run (execute) the program. The result
will look something to this:

Hello World!
Process returned 0 (0x0) execution time : 0.011 s
Press any key to continue.

Congratulations! You have now written and executed your first C++ program.
C++ Syntax

Let's break up the following code to understand it better:

Example
#include <iostream>
using namespace std;

int main() {
cout << "Hello World!";
return 0;
}

Example explained
Line 1: #include <iostream> is a header file library that lets us work with input
and output objects, such as cout (used in line 5). Header files add functionality
to C++ programs.

Line 2: using namespace std means that we can use names for objects and
variables from the standard library.

Don't worry if you don't understand how #include <iostream> and using
namespace std works. Just think of it as something that (almost) always appears
in your program.

Line 3: A blank line. C++ ignores white space.

Line 4: Another thing that always appear in a C++ program, is int main(). This
is called a function. Any code inside its curly brackets {} will be executed.

Line 5: cout (pronounced "see-out") is an object used together with


the insertion operator (<<) to output/print text. In our example it will output
"Hello World".

Note: Every C++ statement ends with a semicolon ;.

Note: The body of int main() could also been written as:
int main () { cout << "Hello World! "; return 0; }
Remember: The compiler ignores white spaces. However, multiple lines makes
the code more readable.

Line 6: return 0 ends the main function.

Line 7: Do not forget to add the closing curly bracket } to actually end the main
function.

Omitting Namespace

You might see some C++ programs that runs without the standard namespace
library. The using namespace std line can be omitted and replaced with
the std keyword, followed by the :: operator for some objects:

Example
#include <iostream>

int main() {
std::cout << "Hello World!";
return 0;

C++ Output (Print Text)

C++ Output (Print Text)

The cout object, together with the << operator, is used to output values/print
text:

Example
#include <iostream>
using namespace std;

int main() {
cout << "Hello World!";
return 0;
}
You can add as many cout objects as you want. However, note that it does not
insert a new line at the end of the output:

Example
#include <iostream>
using namespace std;

int main() {
cout << "Hello World!";
cout << "I am learning C++";
return 0;
}

C++ Output (Print Text)

The cout object, together with the << operator, is used to output values/print
text:

Example
#include <iostream>
using namespace std;

int main() {
cout << "Hello World!";
return 0;
}

You can add as many cout objects as you want. However, note that it does not
insert a new line at the end of the output:

Example
#include <iostream>
using namespace std;

int main() {
cout << "Hello World!";
cout << "I am learning C++";
return 0;
}

New Lines

To insert a new line, you can use the \n character:

Example
#include <iostream>
using namespace std;

int main() {
cout << "Hello World! \n";
cout << "I am learning C++";
return 0;
}

Tip: Two \n characters after each other will create a blank line:

Example
#include <iostream>
using namespace std;

int main() {
cout << "Hello World! \n\n";
cout << "I am learning C++";
return 0;
}

C++ Comments

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

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

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

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


Example
// This is a comment
cout << "Hello World!";

This example uses a single-line comment at the end of a line of code:

Example
cout << "Hello World!"; // This is a comment

C++ Multi-line Comments

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

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

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

C++ Variables

Variables are containers for storing data values.

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

 int - stores integers (whole numbers), without decimals, such as 123 or -


123
 double - stores floating point numbers, with decimals, such as 19.99 or -
19.99
 char - stores single characters, such as 'a' or 'B'. Char values are
surrounded by single quotes
 string - stores text, such as "Hello World". String values are surrounded
by double quotes
 bool - stores values with two states: true or false
Declaring (Creating) Variables

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

Syntax
type variable = value;

Where type is one of C++ types (such as int), and variable is the name of the
variable (such as x or myName). The equal sign is used to assign values to the
variable.

To create a variable that should store a number, look at the following example:

Example

Create a variable called myNum of type int and assign it the value 15:

int myNum = 15;


cout << myNum;

You can also declare a variable without assigning the value, and assign the
value later:

Example
int myNum;
myNum = 15;
cout << myNum;

Note that if you assign a new value to an existing variable, it will overwrite the
previous value:

Example
int myNum = 15; // myNum is 15
myNum = 10; // Now myNum is 10
cout << myNum; // Outputs 10

Other Types

A demonstration of other data types:


Example
int myNum = 5; // Integer (whole number without
decimals)
double myFloatNum = 5.99; // Floating point number (with
decimals)
char myLetter = 'D'; // Character
string myText = "Hello"; // String (text)
bool myBoolean = true; // Boolean (true or false)

You will learn more about the individual types in the Data Types chapter.

Declare Many Variables

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

Example
int x = 5, y = 6, z = 50;
cout << x + y + z;

C++ Identifiers

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

These unique names are called identifiers.

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

Note: It is recommended to use descriptive names in order to create


understandable and maintainable code:

Example
// Good
int minutesPerHour = 60;

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


int m = 60;

The general rules for constructing names for variables (unique identifiers) are:

 Names can contain letters, digits and underscores


 Names must begin with a letter or an underscore (_)
 Names are case sensitive (myVar and myvar are different variables)
 Names cannot contain whitespaces or special characters like !, #, %, etc.
 Reserved words (like C++ keywords, such as int) cannot be used as
names

C++ Constants

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

Example
const int myNum = 15; // myNum will always be 15
myNum = 10; // error: assignment of read-only variable 'myNum'

You should always declare the variable as constant when you have values that
are unlikely to change:

Example
const int minutesPerHour = 60;
const float PI = 3.14;

C++ User Input

C++ User Input

You have already learned that cout is used to output (print) values. Now we will
use cin to get user input.
cin is a predefined variable that reads data from the keyboard with the
extraction operator (>>).

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

Example
int x;
cout << "Type a number: "; // Type a number and press enter
cin >> x; // Get user input from the keyboard
cout << "Your number is: " << x; // Display the input value

Good To Know
cout is pronounced "see-out". Used for output, and uses the insertion operator
(<<)

cin is pronounced "see-in". Used for input, and uses the extraction operator (>>)

Creating a Simple Calculator

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

Example
int x, y;
int sum;
cout << "Type a number: ";
cin >> x;
cout << "Type another number: ";
cin >> y;
sum = x + y;
cout << "Sum is: " << sum;

There you go! You just built a basic calculator!


Test Yourself With Exercises
Exercise:

Use the correct keyword to get user input, stored in the variable x:

int x;
cout << "Type a number: ";
>> ;

C++ Data Types

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


data type:

Example
int myNum = 5; // Integer (whole number)
float myFloatNum = 5.99; // Floating point number
double myDoubleNum = 9.98; // Floating point number
char myLetter = 'D'; // Character
bool myBoolean = true; // Boolean
string myText = "Hello"; // String

Basic Data Types

The data type specifies the size and type of information the variable will store:

Data Type Size Description

int 4 bytes Stores whole numbers, without decimals


float 4 bytes Stores fractional numbers, containing one or more decimals. Sufficient for st

double 8 bytes Stores fractional numbers, containing one or more decimals. Sufficient for st

boolean 1 byte Stores true or false values

char 1 byte Stores a single character/letter/number, or ASCII values

Numeric Types

Use int when you need to store a whole number without decimals, like 35 or
1000, and float or double when you need a floating point number (with
decimals), like 9.99 or 3.14515.

int
int myNum = 1000;
cout << myNum;

float
float myNum = 5.75;
cout << myNum;

double
double myNum = 19.99;
cout << myNum;

float vs. double

The precision of a floating point value indicates how many digits the value can
have after the decimal point. The precision of float is only six or seven decimal
digits, while double variables have a precision of about 15 digits. Therefore it is
safer to use double for most calculations.

Scientific Numbers

A floating point number can also be a scientific number with an "e" to indicate
the power of 10:

Example
float f1 = 35e3;
double d1 = 12E4;
cout << f1;
cout << d1;

Boolean Types

A boolean data type is declared with the bool keyword and can only take the
values true or false. When the value is returned, true = 1 and false = 0.

Example
bool isCodingFun = true;
bool isFishTasty = false;
cout << isCodingFun; // Outputs 1 (true)
cout << isFishTasty; // Outputs 0 (false)

Boolean values are mostly used for conditional testing,

C++ Character Data Types

The char data type is used to store a single character. The character must be
surrounded by single quotes, like 'A' or 'c':

Example
char myGrade = 'B';
cout << myGrade;
Alternatively, you can use ASCII values to display certain characters:

Example
char a = 65, b = 66, c = 67;
cout << a;
cout << b;
cout << c;

Tip: A list of all ASCII values can be found in our ASCII Table Reference.

C++ String Data Types

The string type is used to store a sequence of characters (text). This is not a
built-in type, but it behaves like one in its most basic usage. String values must
be surrounded by double quotes:

Example
string greeting = "Hello";
cout << greeting;

To use strings, you must include an additional header file in the source code,
the <string> library:

Example
// Include the string library
#include <string>

// Create a string variable


string greeting = "Hello";

// Output string value


cout << greeting;

C++ Math

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

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

Example
cout << max(5, 10);

And the min(x,y) function can be used to find the lowest value of x and y:

Example
cout << min(5, 10);

C++ <cmath> Header

Other functions, such as sqrt (square root), round (rounds a number)


and log (natural logarithm), can be found in the <cmath> header file:

Example
// Include the cmath library
#include <cmath>

cout << sqrt(64);


cout << round(2.6);
cout << log(2);

Other Math Functions

A list of other popular Math functions (from the <cmath> library) can be found in
the table below:

Function Description

abs(x) Returns the absolute value of x


acos(x) Returns the arccosine of x, in radians

asin(x) Returns the arcsine of x, in radians

atan(x) Returns the arctangent of x, in radians

cbrt(x) Returns the cube root of x

ceil(x) Returns the value of x rounded up to its nearest integer

cos(x) Returns the cosine of x, in radians

cosh(x) Returns the hyperbolic cosine of x, in radians

exp(x) Returns the value of Ex

expm1(x) Returns ex -1

fabs(x) Returns the absolute value of a floating x

fdim(x, y) Returns the positive difference between x and y

floor(x) Returns the value of x rounded down to its nearest integer

hypot(x, y) Returns sqrt(x2 +y2) without intermediate overflow or underflow

fma(x, y, z) Returns x*y+z without losing precision

fmax(x, y) Returns the highest value of a floating x and y

fmin(x, y) Returns the lowest value of a floating x and y


fmod(x, y) Returns the floating point remainder of x/y

pow(x, y) Returns the value of x to the power of y

sin(x) Returns the sine of x (x is in radians)

sinh(x) Returns the hyperbolic sine of a double value

tan(x) Returns the tangent of an angle

tanh(x) Returns the hyperbolic tangent of a double value

Test Yourself With Exercises


Exercise:
Use the correct function to print the highest value of x and y.

int x = 5;
int y = 10;
cout << (x, y);

C++ Boolean Expressions

A Boolean expression is a C++ expression that returns a boolean


value: 1 (true) or 0 (false).

You can use a comparison operator, such as the greater than (>) operator to
find out if an expression (or a variable) is true:
Example
int x = 10;
int y = 9;
cout << (x > y); // returns 1 (true), because 10 is higher than 9

Or even easier:

Example
cout << (10 > 9); // returns 1 (true), because 10 is higher than 9

In the examples below, we use the equal to (==) operator to evaluate an


expression:

Example
int x = 10;
cout << (x == 10); // returns 1 (true), because the value of x is
equal to 10

Example
cout << (10 == 15); // returns 0 (false), because 10 is not equal
to 15

Booleans are the basis for all C++ comparisons and conditions.

Programming ….. creating a set of instructions that tell a computer how to perform a task.

Programming can be done using a variety of computer programming languages, such as C+


+. JavaScript, Python, and Created by Pamela Fox.

Program is a sequence of instruction along with data.

While executing the program, raw data is processed into a desired output format. These computer
programs are written in a programming language which are high level languages.
High level languages

are nearly human languages which are more complex than the computer understandable

programs we are going to write are in a high-level language which is almost similar to human language.
High level programs also make it easier for programmers to inspect and understand each other's
programs easier

low level languages

are called machine language/ binary language

The computer only understands binary language (the language of 0’s and 1’s) also called
machine-understandable language or low-level language

Assembly language/ symbolic machine code


Between high-level language and machine language there are assembly language also called
symbolic machine code.

is used to convert assembly code into executable machine code

What is a compiler?

Computers understand only one language and that language consists of sets of instructions made of
ones and zeros. This computer language is appropriately called machine language.

Because a computer can only understand machine language and humans wish to write in high level
languages high level languages have to be re-written (translated) into machine language at some point.
This is done by special programs called compilers, interpreters, or assemblers that are built into the
various programming applications.

Integrated Development Environment (IDE).

The easiest way for beginners to compile C++ programs is by using an Integrated Development
Environment (IDE). An IDE generally integrates several development tools, including a text editor and
tools to compile programs directly from it.

IDE Platform Console programs


Code::blocks Windows/Linux/MacOS Compile console programs using Code::blocks

Visual Studio
Windows Compile console programs using VS Express 2013
Express

Dev-C++ Windows Compile console programs using Dev-C++

Comments in C++

Comments in C++ are simply a piece of source code ignored by the compiler. They are only
helpful for a programmer to add a description or additional information about their source code.

In C++ there are two ways to add comments:

//single-line comment

/* block comment */

The first type will discard everything after the compiler encounters “//”. In the second type, the
compiler discards everything between “/*” and “*/”.

Using namespace std


If you have seen C++ code before, you may have seen cout being used instead of std::cout. Both
name the same object: the first one uses its unqualified name (cout), while the second qualifies it
directly within the namespace std (as std::cout).

cout is part of the standard library, and all the elements in the standard C++ library are declared within
what is called a namespace: the namespace std.

In order to refer to the elements in the std namespace a program shall either qualify each and every
use of elements of the library (as we have done by prefixing cout with std::), or introduce visibility of
its components. The most typical way to introduce visibility of these components is by means of using
declarations:

using namespace std;


The above declaration allows all elements in the std namespace to be accessed in
an unqualified manner (without the std:: prefix).

Identifiers
A valid identifier is a sequence of one or more letters, digits, or underscore characters (_). Spaces,
punctuation marks, and symbols cannot be part of an identifier. In addition, identifiers shall always
begin with a letter. They can also begin with an underline character (_), but such identifiers are -on most
cases- considered reserved for compiler-specific keywords or external identifiers, as well as identifiers
containing two successive underscore characters anywhere. In no case can they begin with a digit.

C++ uses a number of keywords to identify operations and data descriptions; therefore, identifiers
created by a programmer cannot match these keywords. The standard reserved keywords that cannot
be used for programmer created identifiers are:

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++ is a case-sensitive programming
language.

alignas, alignof, and, and_eq, asm, auto, bitand, bitor, bool, break, case,
catch, char, char16_t, char32_t, class, compl, const, constexpr, const_cast,
continue, decltype, default, delete, do, double, dynamic_cast, else, enum,
explicit, export, extern, false, float, for, friend, goto, if, inline, int,
long, mutable, namespace, new, noexcept, not, not_eq, nullptr, operator, or,
or_eq, private, protected, public, register, reinterpret_cast, return, short,
signed, sizeof, static, static_assert, static_cast, struct, switch, template,
this, thread_local, throw, true, try, typedef, typeid, typename, union,
unsigned, using, virtual, void, volatile, wchar_t, while, xor, xor_eq

Specific compilers may also have additional specific reserved keywords.

Fundamental data types


The values of variables are stored somewhere in an unspecified location in the computer memory as
zeros and ones. Our program does not need to know the exact location where a variable is stored; it can
simply refer to it by its name. What the program needs to be aware of is the kind of data stored in the
variable.

 Very important: The C++ language is a "case sensitive" language. That means that an identifier
written in capital letters is not equivalent to another one with the same name but written in
small letters. Thus, for example, the RESULT variable is not the same as the result variable or
the Result variable. These are three different identifiers identifiying three different variables.
Character types: They can represent a single character, such as 'A' or '$'. The most basic type
is char, which is a one-byte character. Other types are also provided for wider characters.
 Numerical integer types: They can store a whole number value, such as 7 or 1024. They exist in
a variety of sizes, and can either be signed or unsigned, depending on whether they support
negative values or not.
 Floating-point types: They can represent real values, such as 3.14 or 0.01, with different levels
of precision, depending on which of the three floating-point types is used.
 Boolean type: The boolean type, known in C++ as bool, can only represent one of two
states, true or false.

Group Type names* Notes on size / precision

char Exactly one byte in size. At least 8 bits.

char16_t Not smaller than char. At least 16 bits.

Character types
char32_t Not smaller than char16_t. At least 32 bits.

Can represent the largest supported character


wchar_t
set.

Integer types (signed) signed char Same size as char. At least 8 bits.

signed short int Not smaller than char. At least 16 bits.


signed int Not smaller than short. At least 16 bits.

signed long int Not smaller than int. At least 32 bits.

signed long long int Not smaller than long. At least 64 bits.

unsigned char

unsigned short int

Integer types unsigned int


(same size as their signed counterparts)
(unsigned)
unsigned long int

unsigned long
long int

float

Floating-point types double Precision not less than float

long double Precision not less than double

Boolean type bool

Void type void no storage

Null pointer decltype(nullptr)

Declaration of variables
C++ is a strongly-typed language, and requires every variable to be declared with its type before its first
use. This informs the compiler the size to reserve in memory for the variable and how to interpret its
value. The syntax to declare a new variable in C++ is straightforward: we simply write the type followed
by the variable name (i.e., its identifier). For example:

1 int a;
2 float mynumber;

These are two valid declarations of variables. The first one declares a variable of type int with the
identifier a. The second one declares a variable of type float with the identifier mynumber. Once
declared, the variables a and mynumber can be used within the rest of their scope in the program.
If declaring more than one variable of the same type, they can all be declared in a single statement by
separating their identifiers with commas. For example:

int a, b, c;

This declares three variables (a, b and c), all of them of type int, and has exactly the same meaning as:

1 int a;
2 int b;
3 int c;
To see what variable declarations look like in action within a program, let's have a look at the entire C++
code of the example about your mental memory proposed at the beginning of this chapter:

1 // operating with variables 4


2
3 #include <iostream>
4 using namespace std;
5
6 int main ()
7{
8 // declaring variables:
9 int a, b;
10 int result;
11 Edit
12 // process: & Run
13 a = 5;
14 b = 2;
15 a = a + 1;
16 result = a - b;
17
18 // print out the result:
19 cout << result;
20
21 // terminate the program:
22 return 0;
23 }

Initialization of variables
When the variables in the example above are declared, they have an undetermined value until they are
assigned a value for the first time. But it is possible for a variable to have a specific value from the
moment it is declared. This is called the initialization of the variable.

In C++, there are three ways to initialize variables. They are all equivalent and are reminiscent of the
evolution of the language over the years:

The first one, known as c-like initialization (because it is inherited from the C language), consists of
appending an equal sign followed by the value to which the variable is initialized:

type identifier = initial_value;


For example, to declare a variable of type int called x and initialize it to a value of zero from the same
moment it is declared, we can write:

int x = 0;

Introduction to strings
Fundamental types represent the most basic types handled by the machines where the code may run.
But one of the major strengths of the C++ language is its rich set of compound types, of which the
fundamental types are mere building blocks.

An example of compound type is the string class. Variables of this type are able to store sequences of
characters, such as words or sentences. A very useful feature!

A first difference with fundamental data types is that in order to declare and use objects (variables) of
this type, the program needs to include the header where the type is defined within the standard library
(header <string>):

1 // my first string This is a string


2 #include <iostream>
3 #include <string>
4 using namespace std;
5
Edit
6 int main ()
& Run
7{
8 string mystring;
9 mystring = "This is a string";
10 cout << mystring;
11 return 0;
12 }

As you can see in the previous example, strings can be initialized with any valid string literal, just like
numerical type variables can be initialized to any valid numerical literal. As with fundamental types, all
initialization formats are valid with strings:

1 string mystring = "This is a string";


2 string mystring ("This is a string");
3 string mystring {"This is a string"};
Strings can also perform all the other basic operations that fundamental data types can, like being
declared without an initial value and change its value during execution:

1 // my first string This is the initial string content


2 #include <iostream> This is a different string content
3 #include <string>
4 using namespace std;
5
6 int main ()
7{
Edit
8 string mystring;
& Run
9 mystring = "This is the initial string
10 content";
11 cout << mystring << endl;
12 mystring = "This is a different string
13 content";
14 cout << mystring << endl;
return 0;
}

Note: inserting the endl manipulator ends the line (printing a newline character and flushing the
stream).

Constants
Constants are expressions with a fixed value.

Literals
Literals are the most obvious kind of constants. They are used to express particular values within the
source code of a program.

a = 5;

The 5 in this piece of code was a literal constant.

Literal constants can be classified into: integer, floating-point, characters, strings, Boolean, pointers, and
user-defined literals.

Integer Numerals
1 1776
2 707
3 -273

These are numerical constants that identify integer values.

Floating Point Numerals

They express real values, with decimals and/or exponents. They can include either a decimal point,
an e character (that expresses "by ten at the Xth height", where X is an integer value that follows
the e character), or both a decimal point and an e character:

1 3.14159 // 3.14159
2 6.02e23 // 6.02 x 10^23
3 1.6e-19 // 1.6 x 10^-19
4 3.0 // 3.0

Character and string literals

Character and string literals are enclosed in quotes:

1 'z'
2 'p'
3 "Hello world"
4 "How do you do?"

The first two expressions represent single-character literals, and the following two represent string
literals composed of several characters. Notice that to represent a single character, we enclose it
between single quotes ('), and to express a string (which generally consists of more than one character),
we enclose the characters between double quotes (").

Both single-character and string literals require quotation marks surrounding them to distinguish them
from possible variable identifiers or reserved keywords. Notice the difference between these two
expressions:

x
'x'

Here, x alone would refer to an identifier, such as the name of a variable or a compound type,
whereas 'x' (enclosed within single quotation marks) would refer to the character literal 'x' (the
character that represents a lowercase x letter).

Character and string literals can also represent special characters that are difficult or impossible to
express otherwise in the source code of a program, like newline (\n) or tab (\t). These special
characters are all of them preceded by a backslash character (\).

Here you have a list of the single character escape codes:

Escape
Description
code

\n newline

\r carriage return

\t tab

\v vertical tab

\b backspace

\f form feed (page feed)

\a alert (beep)

\' single quote (')

\" double quote (")

\? question mark (?)

\\ backslash (\)

For example:

'\n'
'\t'
"Left \t Right"
"one\ntwo\nthree"

Typed constant expressions


Sometimes, it is just convenient to give a name to a constant value:

1 const double pi = 3.1415926;


2 const char tab = '\t';
1 #include <iostream> 31.4159
2 using namespace std;
3
4 const double pi = 3.14159;
5 const char newline = '\n';
6
7 int main () Edit
8{ & Run
9 double r=5.0; // radius
10 double circle;
11
12 circle = 2 * pi * r;
13 cout << circle;
14 cout << newline;
15 }

Preprocessor definitions (#define)


Another mechanism to name constant values is the use of preprocessor definitions. They have the
following form:

#define identifier replacement

After this directive, any occurrence of identifier in the code is interpreted as replacement, where
replacement is any sequence of characters (until the end of the line). This replacement is performed by
the preprocessor, and happens before the program is compiled, thus causing a sort of blind
replacement: the validity of the types or syntax involved is not checked in any way.

For example:

1 #include <iostream> 31.4159 Edit


2 using namespace std; & Run
3
4 #define PI 3.14159
5 #define NEWLINE '\n'
6
7 int main ()
8{
9 double r=5.0; // radius
10 double circle;
11
12 circle = 2 * PI * r;
13 cout << circle;
14 cout << NEWLINE;
15
16 }

Note that the #define lines are preprocessor directives, and as such are single-line instructions that -
unlike C++ statements- do not require semicolons (;) at the end; the directive extends automatically until
the end of the line. If a semicolon is included in the line, it is part of the replacement sequence and is
also included in all replaced occurrences.

Operators
Once introduced to variables and constants, we can begin to operate with them by using operators.
What follows is a complete list of operators. At this point, it is likely not necessary to know all of them,
but they are all listed here to also serve as reference.

Assignment operator (=)


The assignment operator assigns a value to a variable.

x = 5;

This statement assigns the integer value 5 to the variable x. The assignment operation always takes
place from right to left, and never the other way around:

x = y;

This statement assigns to variable x the value contained in variable y. The value of x at the moment this
statement is executed is lost and replaced by the value of y.

Consider also that we are only assigning the value of y to x at the moment of the assignment operation.
Therefore, if y changes at a later moment, it will not affect the new value taken by x.

For example, let's have a look at the following code - I have included the evolution of the content stored
in the variables as comments:

1 // assignment operator a:4 b:7 Edit


2 #include <iostream> & Run
3 using namespace std;
4
5 int main ()
6{
7 int a, b; // a:?, b:?
8 a = 10; // a:10, b:?
9 b = 4; // a:10, b:4
10 a = b; // a:4, b:4
11 b = 7; // a:4, b:7
12
13 cout << "a:";
14 cout << a;
15 cout << " b:";
16 cout << b;
17 }

This program prints on screen the final values of a and b (4 and 7, respectively). Notice how a was not
affected by the final modification of b, even though we declared a = b earlier.

Assignment operations are expressions that can be evaluated. That means that the assignment itself has
a value, and -for fundamental types- this value is the one assigned in the operation. For example:

y = 2 + (x = 5);

In this expression, y is assigned the result of adding 2 and the value of another assignment expression
(which has itself a value of 5). It is roughly equivalent to:

1 x = 5;
2 y = 2 + x;

With the final result of assigning 7 to y.

The following expression is also valid in C++:

x = y = z = 5;

It assigns 5 to the all three variables: x, y and z; always from right-to-left.

Arithmetic operators ( +, -, *, /, % )
The five arithmetical operations supported by C++ are:

operato description
r

+ addition

- subtraction

multiplicatio
*
n

/ division

% modulo

Operations of addition, subtraction, multiplication and division correspond literally to their respective
mathematical operators. The last one, modulo operator, represented by a percentage sign (%), gives the
remainder of a division of two values. For example:

x = 11 % 3;

results in variable x containing the value 2, since dividing 11 by 3 results in 3, with a remainder of 2.

Compound assignment (+=, -=, *=, /=, %=, >>=, <<=, &=, ^=, |=)
Compound assignment operators modify the current value of a variable by performing an operation on
it. They are equivalent to assigning the result of an operation to the first operand:

expression equivalent to...

y += x; y = y + x;

x -= 5; x = x - 5;

x /= y; x = x / y;

price *= units + 1; price = price * (units+1);

and the same for all other compound assignment operators. For example:

1 // compound assignment operators 5 Edit


2 #include <iostream> & Run
3 using namespace std;
4
5 int main ()
6{
7 int a, b=3;
8 a = b;
9 a+=2; // equivalent to a=a+2
10 cout << a;
11 }

Increment and decrement (++, --)


Some expression can be shortened even more: the increase operator (++) and the decrease operator
(--) increase or reduce by one the value stored in a variable. They are equivalent to +=1 and to -=1,
respectively. Thus:

1 ++x;
2 x+=1;
3 x=x+1;

are all equivalent in its functionality; the three of them increase by one the value of x.

In the early C compilers, the three previous expressions may have produced different executable code
depending on which one was used. Nowadays, this type of code optimization is generally performed
automatically by the compiler, thus the three expressions should produce exactly the same executable
code.

A peculiarity of this operator is that it can be used both as a prefix and as a suffix. That means that it can
be written either before the variable name (++x) or after it (x++). Although in simple expressions like x+
+ or ++x, both have exactly the same meaning; in other expressions in which the result of the increment
or decrement operation is evaluated, they may have an important difference in their meaning: In the
case that the increase operator is used as a prefix (++x) of the value, the expression evaluates to the
final value of x, once it is already increased. On the other hand, in case that it is used as a suffix (x++),
the value is also increased, but the expression evaluates to the value that x had before being increased.
Notice the difference:

Example 1 Example 2

x = 3; x = 3;
y = ++x; y = x++;
// x contains 4, y contains 4 // x contains 4, y contains 3

In Example 1, the value assigned to y is the value of x after being increased. While in Example 2, it is the
value x had before being increased.
There are two types of increments:
Prefix increment ++ a and Postfix increment a++
Similarly decrements are also of two types:
Prefix –a and Postfix a—

++increments the contents of associated operand by 1 where as – decrements the contents of


associated operand by 1
NOTE: In prefix increment , the operator adds 1 to the variable and then use it .
In postfix increment , first use the variable and then add one to the variable.
Similar is for post fix and prefix decrement operators

int _tmain(int argc, _TCHAR* argv[])


{
int a = 10 ;

cout<<"A = " << a++<<"\n";


cout<<"A = " << ++a<<"\n";

a++;
++a;

cout<<"A = " << --a <<"\n";


cout<<"A = " << a-- <<"\n";
cout<<"A = " << a <<"\n";
cout<<"A = " << a--<<"\n";

system ("pause");

return 0;

Relational and comparison operators ( ==, !=, >, <, >=, <= )
Two expressions can be compared using relational and equality operators. For example, to know if two
values are equal or if one is greater than the other.

The result of such an operation is either true or false (i.e., a Boolean value).

The relational operators in C++ are:


operato
description
r

== Equal to

!= Not equal to

< Less than

> Greater than

<= Less than or equal to

>= Greater than or equal to

Here there are some examples:

1 (7 == 5) // evaluates to false
2 (5 > 4) // evaluates to true
3 (3 != 2) // evaluates to true
4 (6 >= 6) // evaluates to true
5 (5 < 5) // evaluates to false

Of course, it's not just numeric constants that can be compared, but just any value, including, of course,
variables. Suppose that a=2, b=3 and c=6, then:

1 (a == 5) // evaluates to false, since a is not equal to 5


2 (a*b >= c) // evaluates to true, since (2*3 >= 6) is true
3 (b+4 > a*c) // evaluates to false, since (3+4 > 2*6) is false
4 ((b=2) == a) // evaluates to true

Be careful! The assignment operator (operator =, with one equal sign) is not the same as the equality
comparison operator (operator ==, with two equal signs); the first one (=) assigns the value on the right-
hand to the variable on its left, while the other (==) compares whether the values on both sides of the
operator are equal. Therefore, in the last expression ((b=2) == a), we first assigned the
value 2 to b and then we compared it to a (that also stores the value 2), yielding true.

Logical operators (! &&, || )


The operator ! is the C++ operator for the Boolean operation NOT. It has only one operand, to its right,
and inverts it, producing false if its operand is true, and true if its operand is false. Basically, it
returns the opposite Boolean value of evaluating its operand. For example:
1 !(5 == 5) // evaluates to false because the expression at its right (5 ==
2 5) is true
3 !(6 <= 4) // evaluates to true because (6 <= 4) would be false
4 !true // evaluates to false
!false // evaluates to true

The logical operators && and || are used when evaluating two expressions to obtain a single relational
result. The operator && corresponds to the Boolean logical operation AND, which yields true if both its
operands are true, and false otherwise. The following panel shows the result of
operator && evaluating the expression a&&b:

&& OPERATOR (and)

a b a && b

true true true

true false false

false true False

false false False

The operator || corresponds to the Boolean logical operation OR, which yields true if either of its
operands is true, thus being false only when both operands are false. Here are the possible results
of a||b:

|| OPERATOR (or)

a b a || b

true true true

true false true

false true true

false false false

For example:
1 ( (5 == 5) && (3 > 6) ) // evaluates to false ( true && false )
2 ( (5 == 5) || (3 > 6) ) // evaluates to true ( true || false )

When using the logical operators, C++ only evaluates what is necessary from left to right to come up
with the combined relational result, ignoring the rest. Therefore, in the last example ( (5==5)||(3>6)),
C++ evaluates first whether 5==5 is true, and if so, it never checks whether 3>6 is true or not. This is
known as short-circuit evaluation, and works like this for these operators:

operato
short-circuit
r

if the left-hand side expression is false, the combined result is false (the right-hand side
&&
expression is never evaluated).

if the left-hand side expression is true, the combined result is true (the right-hand side
||
expression is never evaluated).

This is mostly important when the right-hand expression has side effects, such as altering values:

if ( (i<10) && (++i<n) ) { /*...*/ } // note that the condition increments


i

Here, the combined conditional expression would increase i by one, but only if the condition on the left
of && is true, because otherwise, the condition on the right-hand side (++i<n) is never evaluated.

Conditional ternary operator ( ? : )


The conditional operator evaluates an expression, returning one value if that expression evaluates
to true, and a different one if the expression evaluates as false. Its syntax is:

condition ? result1 : result2

If condition is true, the entire expression evaluates to result1, and otherwise to result2.

1 7==5 ? 4 : 3 // evaluates to 3, since 7 is not equal to 5.


2 7==5+2 ? 4 : 3 // evaluates to 4, since 7 is equal to 5+2.
3 5>3 ? a : b // evaluates to the value of a, since 5 is greater than 3.
4 a>b ? a : b // evaluates to whichever is greater, a or b.

For example:

1 // conditional operator 7 Edit


2 #include <iostream> & Run
3 using namespace std;
4
5 int main ()
6{
7 int a,b,c;
8
9 a=2;
10 b=7;
11 c = (a>b) ? a : b;
12
13 cout << c << '\n';
14 }

In this example, a was 2, and b was 7, so the expression being evaluated (a>b) was not true, thus the
first value specified after the question mark was discarded in favor of the second value (the one after
the colon) which was b (with a value of 7).

Comma operator ( , )
The comma operator (,) is used to separate two or more expressions that are included where only one
expression is expected. When the set of expressions has to be evaluated for a value, only the right-most
expression is considered.

For example, the following code:

a = (b=3, b+2);

would first assign the value 3 to b, and then assign b+2 to variable a. So, at the end, variable a would
contain the value 5 while variable b would contain value 3.

Bitwise operators (&, |, ^, ~, <<, >> )


Bitwise operators modify variables considering the bit patterns that represent the values they store.

operato asm
description
r equivalent

& AND Bitwise AND

| OR Bitwise inclusive OR

^ XOR Bitwise exclusive OR

~ NOT Unary complement (bit inversion)

<< SHL Shift bits left


>> SHR Shift bits right

Explicit type casting operator


Type casting operators allow to convert a value of a given type to another type. There are several ways
to do this in C++. The simplest one, which has been inherited from the C language, is to precede the
expression to be converted by the new type enclosed between parentheses (()):

1 int i;
2 float f = 3.14;
3 i = (int) f;

The previous code converts the floating-point number 3.14 to an integer value (3); the remainder is
lost. Here, the typecasting operator was (int). Another way to do the same thing in C++ is to use the
functional notation preceding the expression to be converted by the type and enclosing the expression
between parentheses:

i = int (f);

Both ways of casting types are valid in C++.

sizeof
This operator accepts one parameter, which can be either a type or a variable, and returns the size in
bytes of that type or object:

x = sizeof (char);

Here, x is assigned the value 1, because char is a type with a size of one byte.

The value returned by sizeof is a compile-time constant, so it is always determined before program
execution.
Other operators
Later in these tutorials, we will see a few more operators, like the ones referring to pointers or the
specifics for object-oriented programming.

Precedence of operators
A single expression may have multiple operators. For example:

x = 5 + 7 % 2;

In C++, the above expression always assigns 6 to variable x, because the % operator has a higher
precedence than the + operator, and is always evaluated before. Parts of the expressions can be
enclosed in parenthesis to override this precedence order, or to make explicitly clear the intended
effect. Notice the difference:

1 x = 5 + (7 % 2); // x = 6 (same as without parenthesis)


2 x = (5 + 7) % 2; // x = 0

From greatest to smallest priority, C++ operators are evaluated in the following order:
Leve
Precedence group Operator Description Grouping
l

1 Scope :: scope qualifier Left-to-right

++ -- postfix increment / decrement

() functional forms
2 Postfix (unary) Left-to-right
[] subscript

. -> member access

3 Prefix (unary) ++ -- prefix increment / decrement Right-to-left

~ ! bitwise NOT / logical NOT

+ - unary prefix

& * reference / dereference

new delete allocation / deallocation

sizeof parameter pack


(type) C-style type-casting

4 Pointer-to-member .* ->* access pointer Left-to-right

5 Arithmetic: scaling * / % multiply, divide, modulo Left-to-right

6 Arithmetic: addition + - addition, subtraction Left-to-right

7 Bitwise shift << >> shift left, shift right Left-to-right

8 Relational < > <= >= comparison operators Left-to-right

9 Equality == != equality / inequality Left-to-right

10 And & bitwise AND Left-to-right

11 Exclusive or ^ bitwise XOR Left-to-right

12 Inclusive or | bitwise OR Left-to-right

13 Conjunction && logical AND Left-to-right

14 Disjunction || logical OR Left-to-right

= *= /= %= += -
= assignment / compound
Assignment-level >>= <<= &= ^= | assignment
15 Right-to-left
expressions =

?: conditional operator

16 Sequencing , comma separator Left-to-right

Basic I/O in C++:C++ comes with libraries which provides us with many ways for performing
input and output. In C++ input and output is performed in the form of a sequence of bytes or
more commonly known as streams. The two keywords cout and cin are used very often for
taking inputs and printing outputs. These two are the most basic methods of taking input and
output in C++.

Algorithm
An algorithm is a procedure used for solving problem or performing a computation.
Algorithms act as an exact list of instructions that conduct specified actions step by
step in either hardware or software based routines. Algorithms are used widely
throughout all areas of IT.
Flowcharts
A flowchart is a type of diagram that represents an algorithm, workflow or process.
The flowchart shows the steps as boxes of various kinds, and their order by connecting the boxes
with arrows. This diagrammatic representation illustrates a solution model to a given problem.

Simple Flowcharting Symbols


Terminal

The rounded rectangles, or terminal points, indicate the flowchart's starting and ending
points.

Flow Lines

Note: The default flow is left to right and top to bottom (the same way you read English).
To save time arrowheads are often only drawn when the flow lines go contrary the normal.

Input/Output

The parallelograms designate input or output operations.

Process

The rectangle depicts a process such as a mathematical computation, or a variable


assignment.

Decision

The diamond is used to represent the true/false statement being tested in a decision symbol.
Variable

Variables are containers for storing data values which change.

A scope is a region of the program and broadly speaking there are three places, where
variables can be declared −
 Inside a function or a block which is called local variables,
 In the definition of function parameters which is called formal parameters.
 Outside of all functions which is called global variables.
We will learn what is a function and it's parameter in subsequent chapters. Here let us
explain what are local and global variables.

Local Variables
Variables that are declared inside a function or block are local variables. They can be
used only by statements that are inside that function or block of code. Local variables
are not known to functions outside their own. Following is the example using local
variables −
#include <iostream>
using namespace std;

int main () {
// Local variable declaration:
int a, b;
int c;

// actual initialization
a = 10;
b = 20;
c = a + b;

cout << c;

return 0;
}

Global Variables
Global variables are defined outside of all the functions, usually on top of the program.
The global variables will hold their value throughout the life-time of your program.
A global variable can be accessed by any function. That is, a global variable is
available for use throughout your entire program after its declaration. Following is the
example using global and local variables −
#include <iostream>
using namespace std;

// Global variable declaration:


int g;

int main () {
// Local variable declaration:
int a, b;

// actual initialization
a = 10;
b = 20;
g = a + b;

cout << g;

return 0;
}

A program can have same name for local and global variables but value of local
variable inside a function will take preference. For example −
#include <iostream>
using namespace std;

// Global variable declaration:


int g = 20;

int main () {
// Local variable declaration:
int g = 10;

cout << g;

return 0;
}

When the above code is compiled and executed, it produces the following result −
10

Local and Global scope of a variable


The scope of a variable is defined as the extent of the program code within which the variable
remains active i.e. it can be declared, defined or worked with.

1. Local Scope: A variable is said to have a local scope or is local when it is declared inside
a code block. The variable remains active only inside the block and is not accessible
outside the code block.

2. Global Scope: A variable has a global scope when it is accessible throughout the
program. A global variable is declared on top of the program before all the function
definitions.

Example:

#include <iostream.h>
Int globalResult=0; //global variable
int main()
{
Int localVar = 10; //local variable.
…..

Precedence when there is a Global variable and a Local variable in the program with the
same name

Answer: Whenever there is a local variable with the same name as that of a global variable, the
compiler gives precedence to the local variable.

Example:

#include <iostream>
int x = 10;
int main()
{
int x = 5;
cout<<x<<endl;
}

The output of the above code is 5. This is because, although both the variables have the same
name, the compiler has given preference to the local scope.

When there is a Global variable and Local variable with the same name, how will you
access the global variable?
Answer: When there are two variables with the same name but different scope, i.e. one is a local
variable and the other is a global variable, the compiler will give preference to a local variable.

In order to access the global variable, we make use of “scope resolution operator (::)”. Using
this operator, we can access the value of the global variable.

Example:

#include<iostream.h>
int x= 10;
int main()
{
int x= 5;
cout<<”Global Variable x = “<<::x;
cout<<”\nlocal Variable x= “<<x;
}

Output:

Global Variable x = 10
local Variable x= 2

What is a Constant? Explain with an example.

Answer: A constant is an expression that has a fixed value. They can be divided into integer,
decimal, floating point, character or string constants depending on their data type.

Apart from decimal, C++ also supports two more constants i.e. octal (to the base 8) and
hexadecimal (to the base 16) constants.

Examples of Constants:

75 //integer (decimal)
0113 //octal
0x4b //hexadecimal
3.142 //floating point
‘c’ //character constant
“Hello, World” //string constant

Note: When we have to represent a single character, we use single quotes and when we want to
define a constant with more than one character, we use double quotes.

unary operator
It is an operator that acts on one operand e g

++x or x--

binary operator

it is an operator that acts on two operands e g

+,-,* a+b

ternary operator

It is an operator that acts on three operands e g

(a>b)? true : false

Characteristics of a programming Language –


 A programming language must be simple, easy to learn and use, have good readability and
human recognizable.
 Abstraction is a must-have Characteristics for a programming language in which ability to
define the complex structure and then its degree of usability comes.
 A portable programming language is always preferred.
 Programming language’s efficiency must be high so that it can be easily converted into a
machine code and when executed consumes little space in memory.
 A programming language should be well structured and documented so that it is suitable
for application development.
 Necessary tools for development, debugging, testing, maintenance of a program must be
provided by a programming language.
 A programming language should provide single environment known as Integrated
Development Environment(IDE).
 A programming language must be consistent in terms of syntax and semantics.
CONTROL STRUCTURES IN C++

Explain control structures (sequence, selection, iteration)

All programs could be written in terms of only three control structures, namely,

the sequence structure

the selection structure

the repetition structure

The term "control structures" comes from the field of computer science. When we introduce C++'s
implementations of control structures, we'll refer to them in the terminology of the C++ standard document as
"control statements."

Sequence Structure in C++


The sequence structure is built into C++. Unless directed otherwise, C++ statements execute one after the
other in the order in which they are written—that is, in sequence

C++ allows us to have as many actions as we want in a sequence structure.

Selection Statements in C++


C++ provides three types of selection statements:
The if selection statement either performs (selects) an action if a condition (predicate) is true or skips the

action if the condition is false.

The if...else selection statement performs an action if a condition is true or performs a different action if the

condition is false.

The switch selection statement performs one of many different actions, depending on the value of an integer

expression.

The if selection statement is a single-selection statement because it selects or ignores a single action
The if...else statement is called a double-selection statement because it selects between two different

actions
The switch selection statement is called a multiple-selection statement because it selects among many

different actions
CONDITIONAL STATEMENTS
There are three conditional statements :
If
If-else
Switch

THE IF STATEMENT
Syntax
If(condition)
{
Statement(s)
}
EXAMPLE
#include <iostream>
using namespace std;

/* run this program using the console pauser or add your own getch, system("pause") or input loop */

int main(int argc, char** argv)


{
int age;

cout<<"enter age";
cin>>age;

if(age <18)
{
cout<<"you are a juvenile you can not vote";
}

return 0;
}
Flowchart of if statement

THE IF-ELSE STATEMENT

The if statement will execute the statement when the when the condition is true.
It does nothing when the condition is false.
In many situations we want to specify both actions when the condition is true and when it is false.
If the condition is true take one action else take another action.
This is possible through if else statements.

SYNTAX

If (condition)

Statement1;
}
Else
{

Statement2;
}

EXAMPLE

// IF-ELSE Statements.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include<iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
int age;

cout<<"enter age";
cin>>age;

if(age <18)
{
cout<<"you are a juvenile you can not vote";
}

else
{
cout<<"you are an adult go and vote\n";
}

system("pause");

return 0;
}

Flowchart of if … else statement

if … else if … else statement


It is used when more than one condition is to be checked. A block of
statement is enclosed inside if, else if and else part. Conditions are checked in
each if and else if part. If the condition is true, the statements inside that block
are executed. If none of the conditions are true, the statements inside else
block are executed. A if … else if … else statement must have only one if
block but can have as many else if block as required. Else part is optional and
may be present or absent.

SYNTAX

if (condition 1)

statements;

... ... ...

else if (condition 2)

statements;

... ... ...

... ... ...

... ... ...

else if (condition n)

statements;
... ... ...

else

statements;

... ... ...

EXAMLE
#include <iostream>
using namespace std;
int main ()
{

// local variable declaration:


int a = 100;

// check the boolean condition


if( a == 10 )
{
// if condition is true then print the following
cout << "Value of a is 10" << endl;

}
else if( a == 20 )
{
// if else if condition is true
cout << "Value of a is 20" << endl;

}
else if( a == 30 )
{
// if else if condition is true
cout << "Value of a is 30" << endl;

}
Else
{
// if none of the conditions is true
cout << "Value of a is not matching" << endl;

cout << "Exact value of


Repetition Statements in C++
C++ provides three types of repetition statements that enable programs to perform statements repeatedly as
long as a condition remains true.

The repetition statements are the


while,
do...while
for statements.
The while and for statements perform the action in their bodies zero or more times—if the loop-continuation

condition is initially false, the action (or group of actions) will not execute.
The do...while statement performs the action (or group of actions) in its body at least once.

Each of the words if, else, switch, while, do and for is a C++ keyword.

These words are reserved by the C++ programming language to implement various features, such as C++'s
control statements. Keywords must not be used as identifiers, such as variable names.

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

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

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

In the example below, we test two values to find out if 20 is greater than 18. If
the condition is true, print some text:
Example
if (20 > 18) {
cout << "20 is greater than 18";
}

Example

int x = 20;
int y = 18;
if (x > y) {
cout << "x is greater than y";
}

C++ Else
The else Statement
Use the else statement to specify a block of code to be executed if the condition
is false.

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

Example
int time = 20;
if (time < 18) {
cout << "Good day.";
} else {
cout << "Good evening.";
}
// Outputs "Good evening."

Example explained

In the example above, time (20) is greater than 18, so the condition is false.
Because of this, we move on to the else condition and print to the screen "Good
evening". If the time was less than 18, the program would print "Good day".

C++ Else If

The else if Statement


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

Syntax
if (condition1)

{
// block of code to be executed if condition1 is true
}

else if (condition2)

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

else

{
// block of code to be executed if the condition1 is false and
condition2 is false
}
Example
int time = 22;
if (time < 10)

{
cout << "Good morning.";
}

else if (time < 20) {


cout << "Good day.";
}

else {
cout << "Good evening.";
}
// Outputs "Good evening."

Example explained

In the example above, time (22) is greater than 10, so the first
condition is false. The next condition, in the else if statement, is also false,
so we move on to the else condition since condition1 and condition2 is
both false - and print to the screen "Good evening".

However, if the time was 14, our program would print "Good day."

C++ Short Hand If Else

Short Hand If...Else (Ternary Operator)


There is also a short-hand if else, which is known as the ternary
operator because it consists of three operands. It can be used to replace
multiple lines of code with a single line. It is often used to replace simple if else
statements:
Syntax
variable = (condition) ? expressionTrue : expressionFalse;

Instead of writing:

Example
int time = 20;
if (time < 18) {
cout << "Good day.";
} else {
cout << "Good evening.";
}

You can simply write:

Example
int time = 20;
string result = (time < 18) ? "Good day." : "Good evening.";
cout << result;

NESTED IF ELSE STATEMENTS

It is an if-else statement within another if-else statement.

The outer if statement condition is checked and if true, that is


only when you go and check the condition of inner if statement.

If outer if statement condition is false, the else part of the


outer if is executed.

If the inner if condition is true, the if statement is executed,


otherwise the else part of inner if is executed.

SYNTAX

If (condition)

{
statement1;

Else

Statement2;

Else

Statement3;

EXAMLE

#include <iostream>

using namespace std;

/* run this program using the console pauser or add your own getch,
system("pause") or input loop */

int main(int argc, char** argv)

int n=6;

//outer if statement

if (n % 2==0) {

//Inner if statement

if(n % 3==0){
cout <<"divisible by 2 and 3";

else {

cout<< "not divisible by 2";

return 0;

Flowchart of Nested if-else


C++ Switch

C++ Switch Statements


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

It has multiple conditions of which if one condition is true then statements


beneath are executed.

If non of the conditions is true the default statement is executed .

It simplifies the else if ladder statement.

The program becomes readable.

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

This is how it works:

 The switch expression is evaluated once


 The value of the expression is compared with the values of each case
 If there is a match, the associated block of code is executed
 The break and default keywords are optional, and will be described later
in this chapter
The example below uses the weekday number to calculate the weekday name:

Example
int day = 4;
switch (day) {
case 1:
cout << "Monday";
break;
case 2:
cout << "Tuesday";
break;
case 3:
cout << "Wednesday";
break;
case 4:
cout << "Thursday";
break;
case 5:
cout << "Friday";
break;
case 6:
cout << "Saturday";
break;
case 7:
cout << "Sunday";
break;
}
// Outputs "Thursday" (day 4)

The break Keyword


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

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

When a match is found, and the job is done, it's time for a break. There is no
need for more testing.
A break can save a lot of execution time because it "ignores" the execution of all
the rest of the code in the switch block.

The default Keyword


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

Example
int day = 4;
switch (day) {
case 6:
cout << "Today is Saturday";
break;
case 7:
cout << "Today is Sunday";
break;
default:
cout << "Looking forward to the Weekend";
}
// Outputs "Looking forward to the Weekend"

Note: The default keyword must be used as the last statement in the switch,
and it does not need a break.

C++ While Loop

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

Loops are handy because they save time, reduce errors, and they make code
more readable.
A loop is used to execute statements more than once. It involves repeating of
some portions of a program either a specified number of times or until a
particular condition is satisfied.

In many a time we know in advance how many times a loop is repeated.

A loop can be repeated while a condition is true

The repetitive operation is done through a loop control structure.

There are three types of loops namely:

While loop

Do while loop

For loop

C++ While Loop


While loop is used to execute a block of code while the condition is true.

As soon as the condition becomes false , it terminates.

If the condition is false at the start, the loop will not be executed at all.

The while loop can be executed zero or multiple times .

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

Syntax
while (condition)

{
// code block to be executed
}
NOTE: For any type of a loop , these three points are important:

1 Initialization of loop counter

2 Condition to test whether condition evaluates to true or false

3 Incrementing or decrementing the loop counter


REVISED SYNTAX

Initialization;

While (condition)

Statements

EXAMLE

#include <iostream>

using namespace std;

/* run this program using the console pauser or add your own getch,
system("pause") or input loop */
int main(int argc, char** argv)

int i = 1 ;

while (i<11)

cout << i <<"\n";

i++;

return 0;

In the given program above, loop is executed ten times

NOTE: We must have some way of ending the loop, otherwise it


executes or continues forever i.e infinity loop.

We provide some method that forces condition to become false at


some moment

In this case we have provided a++ that causes the condition to


become false when the process of incrementing i by 1 reaches 11.

WHILE LOOP COUNTDOWN

include <iostream>

using namespace std;


/* run this program using the console pauser or add your own getch,
system("pause") or input loop */

int main(int argc, char** argv)

int i = 10 ;

while (i > 0)

cout<< i << "\n";

i--;

return 0;

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

Example
int i = 0;
while (i < 5) {
cout << i << "\n";
i++;
}
PROGRAM TO ADD 10 INTEGERS

EXAMPLE

#include <iostream>

using namespace std;

/* run this program using the console pauser or add your own getch,
system("pause") or input loop */

int main(int argc, char** argv)

int i = 1;

int sum = 0;

while (i<=10)

sum = sum + i; //sum + =i

i++;

cout << sum << "\n" ;

}
return 0;

NOTE : While performing sum series it is essential to initialize


variable sum to zero.

Adding any value to zero will not alter the summation.

PRODUCT OF FIVE INTEGERS

EXAMPLE

#include <iostream>

using namespace std;

/* run this program using the console pauser or add your own getch,
system("pause") or input loop */

int main(int argc, char** argv)

int i = 1;

int prod = 1;

while (i <= 5)

prod =prod * i;

i++;
cout << prod << "\n";

return 0;

While performing product series it is essential to initialize


variable prod to 1.

Multiplying any value with 1 will not alter any product.

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

C++ Exercises
Test Yourself With Exercises
Exercise:
Print i as long as i is less than 6.

int i = 1;
(i < 6) {
cout << i << "\n";
;
}
C++ Do/While Loop

The Do/While Loop


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

Do while loop is similar to the while loop except that the do while loop test the
condition at the end of the loop called posttest.

NOTE: The body of the loop will be executed at least once in the worst case.

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

NOTE: In do while loop, semi colon is used after the while


statement.

If you do not use it, the compiler will display syntax error.
The example below uses a do/while loop. The loop will always be executed at
least once, even if the condition is false, because the code block is executed
before the condition is tested:

Example
int i = 0;
do {
cout << i << "\n";
i++;
}
while (i < 5);

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

DIFFERENCE BETWEEN WHILE AND DO WHILE LOOP

The main difference is the place where the condition is tested.

The while loop tests the condition before executing any of the statements within
the while loop that is before entering the loop and it is called pretest

The do while loop tests the condition after having executed the statements
within the loop at least once that is at the end of the loop which is called
posttest.

NOTE: This means that the do while loop would execute its statements at least
once.

The while loop on the other hand will not execute its statements if the condition
fails for the first time that is loop is executed zero times or multiple times.

A program to reverse a number using do while loop:

EXAMPLE

#include <iostream>

using namespace std;

/* run this program using the console pauser or add your own getch,
system("pause") or input loop */

int main(int argc, char** argv)

int num ,rev;


cout << "enter number to be reversed " ;

cin >> num ;

cout << "reversed number is" ;

do

rev = num % 10 ;

cout << rev ;

num = num/10 ;

while (num != 0);

return 0;

C++ For Loop


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

It is often the case in programming that you want to do something for a fixed
number of times.

The for loop is ideal suited for such cases since it allows us to specify three
important things about a loop in a single line that is
1 initialization

2 condition

3 increment or decrement

Syntax
for (initialization; condition; increment or decrement of counter)

{
// code block to be executed
}

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

Statement 2 defines the condition for executing the code block.

Statement 3 is executed (every time) after the code block has been executed.
The example below will print the numbers 1 to 10:

Example
// For loop incremental.cpp : Defines the entry point for the console
application.

//

#include "stdafx.h"
#include <iostream>
using namespace std ;

int _tmain(int argc, _TCHAR* argv[])


{
int i ;

for( i = 1;i <= 10;i++)


{
cout<<i<<"\n";
}

system("pause");
return 0;
}

Example explained

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

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

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

Another Example
This example will only print even values between 0 and 10:

Example
for (int i = 0; i <= 10; i = i + 2) {
cout << i << "\n";
}

ANOTHER EXAMLE

The example will give table of results on square

// FOR LOOP table of results.cpp : Defines the entry point for the console
application.
//

#include "stdafx.h"
#include <iostream>
using namespace std ;

int _tmain(int argc, _TCHAR* argv[])


{
int i ;
cout<<"TABLE OF RESULTS \n";
cout<<"i \t i square \n" ;
for(i=1; i<=10; i++)

{
cout<<i<<"\t\t"<<i*i<<"\n";

system("pause");

return 0;
}

Exercise:
Use a for loop to print "Yes" 5 times:

(int i = 0; i < 5; ) {
cout << << "\n";
}

NOTE : You may be thinking why there are two loops doing the same thing

It is convenient to use while loop when you don’t have any idea how many times the loop will be
repeated.

The for loop is usually used in those cases when you know the number of times the loop will be
repeated in advance.

NESTED FOR LOOP


A for loop within for loop that is placing a for loop within another for loop.

In nested for loop, the outer loop starts its execution by initializing the loop counter and
checking the condition.

If the condition is true, program control moves to the inner loop.

Inner loops counter is initialized and the condition is checked.

The loop is executed while the condition is true.


As soon as the condition of the inner loop becomes false, the program control moves back to
the outer loop and increase the counter.

SYNTAX
for (initialization; condition; increase/decrease)

For(initialization; condition; increase/decrease)

Statement(s)

EXAMPLE
// nested for loop.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
using namespace std;

int _tmain(int argc, _TCHAR* argv[])


{
int i, j;

for(i=1; i<=4; i++)//outer loop


{
for(j=1; j<=3; j++)//inner loop
{
cout<<i<<"\t" <<j <<"\n";
}

cout<<"\n";

system("pause");

return 0;
}
C++ Break and Continue

C++ Break
You have already seen the break statement used in an earlier chapter of this
tutorial. It was used to "jump out" of a switch statement.

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

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

Example
for (int i = 0; i < 10; i++) {
if (i == 4) {
break;
}
cout << i << "\n";
}

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

This example skips the value of 4:


Example
for (int i = 0; i < 10; i++) {
if (i == 4) {
continue;
}
cout << i << "\n";
}

Break and Continue in While Loop


You can also use break and continue in while loops:

Break Example
int i = 0;
while (i < 10) {
cout << i << "\n";
i++;
if (i == 4) {
break;
}
}

Continue Example
int i = 0;
while (i < 10)

{
if (i == 4)

{
i++;
continue;
}
cout << i << "\n";
i++;
}

C++ Exercises
Test Yourself

Exercise:
Stop the loop if i is 5:

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


if (i == 5) {
;
}
cout << i << "\n";
}
C++ Arrays

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

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

string cars[4];

We have now declared a variable that holds an array of four strings. To insert
values to it, we can use an array literal - place the values in a comma-separated
list, inside curly braces:
string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};

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

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

Access the Elements of an Array


You access an array element by referring to the index number.

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

Example
string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};
cout << cars[0];
// Outputs Volvo

Note: Array indexes start with 0: [0] is the first element. [1] is the second
element, etc.

Change an Array Element


To change the value of a specific element, refer to the index number:

Example
cars[0] = "Opel";

Example
string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};
cars[0] = "Opel";
cout << cars[0];
// Now outputs Opel instead of Volvo
C++ Exercises

Test Yourself With Exercises


Exercise:

Create an array of type string called cars.

[4] = {"Volvo", "BMW", "Ford", "Mazda"};

C++ Arrays and Loops

Loop Through an Array


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

The following example outputs all elements in the cars array:

Example
string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};
for(int i = 0; i < 4; i++) {
cout << cars[i] << "\n";
}

The following example outputs the index of each element together with its
value:

Example
string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};
for(int i = 0; i < 4; i++) {
cout << i << ": " << cars[i] << "\n";
}
C++ Omit Array Size

Omit Array Size


You don't have to specify the size of the array. But if you don't, it will only be as
big as the elements that are inserted into it:

string cars[] = {"Volvo", "BMW", "Ford"}; // size of array is


always 3

This is completely fine. However, the problem arise if you want extra space for
future elements. Then you have to overwrite the existing values:

string cars[] = {"Volvo", "BMW", "Ford"};


string cars[] = {"Volvo", "BMW", "Ford", "Mazda", "Tesla"};

If you specify the size however, the array will reserve the extra space:

string cars[5] = {"Volvo", "BMW", "Ford"}; // size of array is 5,


even though it's only three elements inside it

Now you can add a fourth and fifth element without overwriting the others:

cars[3] = {"Mazda"};
cars[4] = {"Tesla"};

Omit Elements on Declaration


It is also possible to declare an array without specifying the elements on
declaration, and add them later:

string cars[5];
cars[0] = {"Volvo"};
cars[1] = {"BMW"};
...

C++ Functions
Why Functions?
At times, a certain portion of codes has to be used many times. Instead of re-writing the
codes many times, it is better to put them into a " function ", and "call" this " function "
many time - for ease of maintenance and understanding.
The benefits of using functions are:
Advantages of using functions in a program

 You can divide your program in logical blocks. ...


 Use of function avoids typing same pieces of code multiple times. ...
 Individual functions can be easily tested.
 In case of any modification in the code you can modify only the function without
changing the structure of the program.

Divide and conquer: construct the program from simple, small pieces or components.
Modularize the program into self-contained tasks.
1. Avoid repeating codes: It is easy to copy and paste, but hard to maintain and
synchronize all the copies.
2. Software Reuse: you can reuse the functions in other programs, by packaging
them into library codes.
Two parties are involved in using a function: a caller who calls the function, and
the function called. The caller passes argument(s) to the function. The function receives
these argument(s), performs the programmed operations within the function's body,
and returns a piece of result back to the caller.

Def:-

A function is a block of code which only runs when it is called.

You can pass data, known as parameters, into a function.

Functions are used to perform certain actions, and they are important for reusing code: Define
the code once, and use it many times.
Create a Function
C++ provides some pre-defined functions, such as main(), which is used to execute code. But you
can also create your own functions to perform certain actions.

To create (often referred to as declare) a function, specify the name of the function, followed by
parentheses ():

Syntax
void myFunction() {
// code to be executed
}

Example Explained

 myFunction() is the name of the function


 void means that the function does not have a return value. You will learn more about return
values later in the next chapter
 inside the function (the body), add code that defines what the function should do

Call a Function
Declared functions are not executed immediately. They are "saved for later use", and will be
executed later, when they are called.

To call a function, write the function's name followed by two parentheses () and a semicolon ;

In the following example, myFunction() is used to print a text (the action), when it is called:

Example
Inside main, call myFunction():

// Create a function
void myFunction() {
cout << "I just got executed!";
}
int main() {
myFunction(); // call the function
return 0;
}

// Outputs "I just got executed!"

A function can be called multiple times:

Example
void myFunction() {
cout << "I just got executed!\n";
}

int main() {
myFunction();
myFunction();
myFunction();
return 0;
}

// I just got executed!


// I just got executed!
// I just got executed!

Function Declaration and Definition


A C++ function consist of two parts:

 Declaration: return type the function's name, and parameters (if any)
 Definition: the body of the function (code to be executed)

void myFunction() { // declaration


// the body of the function (definition)
}

Note: If a user-defined function, such as myFunction() is declared after the main() function, an
error will occur. It is because C++ works from top to bottom; which means that if the function is not
declared above main(), the program is unaware of it:

Example
int main() {
myFunction();
return 0;
}

void myFunction() {
cout << "I just got executed!";
}

// Error

However, it is possible to separate the declaration and the definition of the function - for code
optimization.

You will often see C++ programs that have function declaration above main(), and function
definition below main(). This will make the code better organized and easier to read:

Example
// Function declaration
void myFunction();

// The main method


int main() {
myFunction(); // call the function
return 0;
}

// Function definition
void myFunction() {
cout << "I just got executed!";
}
C++ Exercises

Test Yourself With Exercises


Exercise:
Create a function named myFunction and call it inside main().

void () {
cout << "I just got executed!";
}

int main() {
;
return 0;
}

C++ Function Parameters

Parameters and Arguments


Information can be passed to functions as a parameter. Parameters act as
variables inside the function.

Parameters are specified after the function name, inside the parentheses. You
can add as many parameters as you want, just separate them with a comma:

Syntax
int add(parameter1, parameter2, parameter3) {
// code to be executed
}

The following example has a function that takes integers int a and int b as
formal parameters.
Example
Int add(int a, int b) // decalartion

{ //definition

int c;

c=a+b;

return c;
}
int main() {

cout<<add(4,8) //calling function


return 0;
}

When a parameter is passed to the function, it is called an argument. So, from


the example above: int a and int b are formal parameter, while 4, 8
are arguments.

C++ Default Parameters

Default Parameter Value


You can also use a default parameter value, by using the equals sign ( =).

If we call the function without an argument, it uses the default value ("Norway"):

Example
void myFunction(string country = "Norway") {
cout << country << "\n";
}

int main() {
myFunction("Sweden");
myFunction("India");
myFunction();
myFunction("USA");
return 0;
}

// Sweden
// India
// Norway
// USA

A parameter with a default value, is often known as an "optional parameter".


From the example above, country is an optional parameter and "Norway" is the
default value.

C++ Multiple Parameters

Multiple Parameters
Inside the function, you can add as many parameters as you want:

Example
void myFunction(string fname, int age) {
cout << fname << " Refsnes. " << age << " years old. \n";
}

int main() {
myFunction("Liam", 3);
myFunction("Jenny", 14);
myFunction("Anja", 30);
return 0;
}

// Liam Refsnes. 3 years old.


// Jenny Refsnes. 14 years old.
// Anja Refsnes. 30 years old.

Note that when you are working with multiple parameters, the function call must
have the same number of arguments as there are parameters, and the
arguments must be passed in the same order.

C++ The Return Keyword

Return Values

If you want the function to return a value, you can use a data type (such
as int, string, float etc.) instead of void, and use the return keyword inside the
function.

void keyword

The void keyword, indicates that the function should not return a value.
Therefore, no need to write the return keyword inside the function body.

Example
int myFunction(int x) {
return 5 + x;
}

int main() {
cout << myFunction(3);
return 0;
}

// Outputs 8 (5 + 3)

This example returns the sum of a function with two parameters:


Example
int myFunction(int x, int y) {
return x + y;
}

int main() {
cout << myFunction(5, 3);
return 0;
}

// Outputs 8 (5 + 3)

You can also store the result in a variable:

Example
int myFunction(int x, int y) {
return x + y;
}

int main() {
int z = myFunction(5, 3);
cout << z;
return 0;
}
// Outputs 8 (5 + 3)

C++ Functions - Pass By Reference

The pass by reference method of passing arguments to a function copies the address
of an argument into the formal parameter. This can be useful when you need to
change the value of the arguments.

So accordingly you need to declare the function parameters as reference types

Int Add(int &x, int &y);


Inside the function, the address is used to access the actual argument used in the call.
This means that changes made to the parameter affect the passed argument.

Pass by value

By default, arguments in C++ are passed by value. When an argument is passed


by value, the argument's value is copied into the value of the corresponding function
parameter.

Example
void swapNums(int &x, int &y) {
int z = x;
x = y;
y = z;
}
int main() {
int firstNum = 10;
int secondNum = 20;
cout << "Before swap: " << "\n";
cout << firstNum << secondNum << "\n";
// Call the function, which will change the values of firstNum
and secondNum
swapNums(firstNum, secondNum);
cout << "After swap: " << "\n";
cout << firstNum << secondNum << "\n";
return 0;
}
C++ Function Overloading
Function overloading in C++: C++ program for function
overloading. Function overloading means two or more functions
can have the same name but either the number of arguments or
the data type of arguments has to be different.

Return type has no role because the function will return a value
when it is called and at compile time compiler will not be able to
determine which function to call. In the first example in our code,
we make two functions one for adding two integers and other for
adding two floats, but they have the same name, and in the
second program we make two functions with identical names but
pass them a different number of arguments. Function
overloading is also known as compile time polymorphism.

C++ programming code


1.#include <iostream>
2.
3.using namespace std;
4.
5./* Function arguments are of different data type */
6.
7.long add(long, long);
8.float add(float, float);
9.
10. int main()
11. {
12. long a, b, x;
13. float c, d, y;
14.
15. cout << "Enter two integers\n";
16. cin >> a >> b;
17.
18. x = add(a, b);
19.
20. cout << "Sum of integers: " << x << endl;
21.
22. cout << "Enter two floating point numbers\n";
23. cin >> c >> d;
24.
25. y = add(c, d);
26.
27. cout << "Sum of floats: " << y << endl;
28.
29. return 0;
30. }
31.
32. long add(long x, long y)
33. {
34. long sum;
35.
36. sum = x + y;
37.
38. return sum;
39. }
40.
41. float add(float x, float y)
42. {
43. float sum;
44.
45. sum = x + y;
46.
47. return sum;
48. }

In the above program, we have created two functions "add" for


two different data types you can create more than two functions
with the same name according to requirement but making sure
that compiler will be able to determine which one to call. For
example, you can create add function for integers, doubles and
other data types in above program. In these functions you can
see the code of functions is same except data type, C++ provides
a solution to this problem we can create a single function for
different data types which reduces code size which is via
templates.

C++ programming code for function overloading


1.#include <iostream>
2.
3.using namespace std;
4.
5./* Number of arguments are different */
6.
7.void display(char []); // print the string passed as
argument
8.void display(char [], char []);
9.
10. int main()
11. {
12. char first[] = "C programming";
13. char second[] = "C++ programming";
14.
15. display(first);
16. display(first, second);
17.
18. return 0;
19. }
20.
21. void display(char s[])
22. {
23. cout << s << endl;
24. }
25.
26. void display(char s[], char t[])
27. {
28. cout << s << endl << t << endl;
29. }

Output of program:

1.C programming
2.C programming
3.C++ programming

Function Overloading
With function overloading, multiple functions can have the same name with
different parameters:

Example
int myFunction(int x)
float myFunction(float x)
double myFunction(double x, double y)

Consider the following example, which have two functions that add numbers of
different type:
Example
int plusFuncInt(int x, int y) {
return x + y;
}

double plusFuncDouble(double x, double y) {


return x + y;
}
int main() {
int myNum1 = plusFuncInt(8, 5);
double myNum2 = plusFuncDouble(4.3, 6.26);
cout << "Int: " << myNum1 << "\n";
cout << "Double: " << myNum2;
return 0;
}
Instead of defining two functions that should do the same thing, it is better to
overload one.

In the example below, we overload the plusFunc function to work for


both int and double:

Example
int plusFunc(int x, int y) {
return x + y;
}
double plusFunc(double x, double y) {
return x + y;
}
int main() {
int myNum1 = plusFunc(8, 5);
double myNum2 = plusFunc(4.3, 6.26);
cout << "Int: " << myNum1 << "\n";
cout << "Double: " << myNum2;
return 0;
}

Note: Multiple functions can have the same name as long as the number and/or
type of parameters are different.

Function Prototype
In C++, a function must be declared before it can be called. It can be achieved by either
placing the function definition before it is being used, or declare a so-called function
prototype.
A function prototype tells the compiler the function's interface, i.e., the return-type,
function name, and the parameter type list (the number and type of parameters). The
function can now be defined anywhere in the file. For example,

// Function prototype - placed before the function is used.


double getArea(double); // without the parameter name
int max(int, int);

You could optionally include the parameter names in the function prototype. The names
will be ignored by the compiler, but serve as documentation. For example,

// Function Prototype
double getArea(double radius); // parameter names are ignored, but serve as
documentation
int max(int number1, int number2);
Function prototypes are usually grouped together and placed in a so-called header file.
The header file can be included in many programs. We will discuss header file later.
Another Example
We have a function called max(int, int), which takes two int and return their
maximum. We invoke the max() function from the main().
1/* Testing max function (TestMaxFunction.cpp) */
2#include <iostream>
3using namespace std;
4
5int maximum(int, int); // Function prototype (declaration)
6
7int main() {
8 cout << maximum(5, 8) << endl; // Call maximum() with literals
9
10 int a = 6, b = 9, c;
11 c = maximum(a, b); // Call maximum() with variables
12 cout << c << endl;
13
14 cout << maximum(c, 99) << endl; // Call maximum()
15}
16
17// Function definition
18// A function that returns the maximum of two given int
19int maximum(int num1, int num2) {
20 return (num1 > num2) ? num1 : num2;
21}
Types of function
We have two types of function in C++:

1) Built-in functions
2) User-defined functions

1) Built-in functions
Built-in functions are also known as library functions. We need not to declare and
define these functions as they are already written in the C++ libraries such as
iostream, cmath etc. We can directly call them when we need.

Example: C++ built-in function example

Here we are using built-in function pow(x,y) which is x to the power y. This
function is declared in cmath header file so we have included the file in our
program using #include directive.

#include <iostream>
#include <cmath>
using namespace std;
int main(){
/* Calling the built-in function
* pow(x, y) which is x to the power y
* We are directly calling this function
*/
cout<<pow(2,5);
return 0;
}

Output:

32
2) User-defined functions

We have already seen user-defined functions, the example we have given at the
beginning of this tutorial is an example of user-defined function. The functions
that we declare and write in our programs are user-defined functions. Lets see
another example of user-defined functions.

User-defined functions
#include <iostream>
#include <cmath>
using namespace std;
//Declaring the function sum
int sum(int,int);

int main(){
int x, y;
cout<<"enter first number: ";
cin>> x;

cout<<"enter second number: ";


cin>>y;

cout<<"Sum of these two :"<<sum(x,y);


return 0;
}
//Defining the function sum
int sum(int a, int b) {
int c = a+b;
return c;
}
Output:
enter first number: 22
enter second number: 19
Sum of these two :41

C++ OOP

C++ What is OOP?

OOP stands for Object-Oriented Programming.

Procedural programming is about writing procedures or functions that


perform operations on the data,

Object-oriented programming is about creating objects that contain both


data and functions.

Object-oriented programming has several advantages over procedural


programming:

 OOP is faster and easier to execute


 OOP provides a clear structure for the programs
 OOP makes the code easier to maintain, modify and debug
 OOP makes it possible to create full reusable applications with less code
and shorter development time

Tip: The "Don't Repeat Yourself" (DRY) principle is about reducing the repetition
of code. You should extract out the codes that are common for the application,
and place them at a single place and reuse them instead of repeating it.

C++ What are Classes and Objects?

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

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

objects
Apple

Banana

Mango

Another example:

class
Car

objects
Volvo

Audi

Toyota

So, a class is a template for objects, and an object is an instance of a class.

When the individual objects are created, they inherit all the variables and
functions from the class.

You will learn much more about classes and objects in the next chapter.
C++ Classes and Objects

C++ Classes/Objects

C++ is an object-oriented programming language.

Everything in C++ is associated with classes and objects, along with its
attributes and methods. For example: in real life, a car is an object. The car
has attributes, such as weight and color, and methods, such as drive and
brake.

Attributes and methods are basically variables and functions that belongs to
the class. These are often referred to as "class members".

A class is a user-defined data type that we can use in our program, and it works
as an object constructor, or a "blueprint" for creating objects.

Create a Class

To create a class, use the class keyword:

Example
Create a class called "MyClass":

class MyClass { // The class


public: // Access specifier
int myNum; // Attribute (int variable)
string myString; // Attribute (string variable)
};

Example explained

 The class keyword is used to create a class called MyClass.


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

Create an Object

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

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

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

Example

Create an object called "myObj" and access the attributes:

class MyClass { // The class


public: // Access specifier
int myNum; // Attribute (int variable)
string myString; // Attribute (string variable)
};

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

// Access attributes and set values


myObj.myNum = 15;
myObj.myString = "Some text";

// Print attribute values


cout << myObj.myNum << "\n";
cout << myObj.myString;
return 0;
}
Multiple Objects

You can create multiple objects of one class:

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

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

// Create another object of Car


Car carObj2;
carObj2.brand = "Ford";
carObj2.model = "Mustang";
carObj2.year = 1969;

// Print attribute values


cout << carObj1.brand << " " << carObj1.model << " " <<
carObj1.year << "\n";
cout << carObj2.brand << " " << carObj2.model << " " <<
carObj2.year << "\n";
return 0;
}
C++ Class Methods

Class Methods

Methods are functions that belongs to the class.

There are two ways to define functions that belongs to a class:

 Inside class definition


 Outside class definition

In the following example, we define a function inside the class, and we name it
"myMethod".

Note: You access methods just like you access attributes; by creating an object
of the class and by using the dot syntax ( .):

Inside Example
class MyClass { // The class
public: // Access specifier
void myMethod() { // Method/function defined inside the class
cout << "Hello World!";
}
};

int main() {
MyClass myObj; // Create an object of MyClass
myObj.myMethod(); // Call the method
return 0;
}

To define a function outside the class definition, you have to declare it inside the
class and then define it outside of the class. This is done by specifiying the
name of the class, followed the scope resolution :: operator, followed by the
name of the function:
Outside Example
class MyClass { // The class
public: // Access specifier
void myMethod(); // Method/function declaration
};

// Method/function definition outside the class


void MyClass::myMethod() {
cout << "Hello World!";
}

int main() {
MyClass myObj; // Create an object of MyClass
myObj.myMethod(); // Call the method
return 0;
}

Parameters

You can also add parameters:

Example
#include <iostream>
using namespace std;

class Car {
public:
int speed(int maxSpeed);
};

int Car::speed(int maxSpeed) {


return maxSpeed;
}

int main() {
Car myObj; // Create an object of Car
cout << myObj.speed(200); // Call the method with an argument
return 0;
}

C++ Constructors

Constructors

A constructor in C++ is a special method that is automatically called when an


object of a class is created.

To create a constructor, use the same name as the class, followed by


parentheses ()

Example
class MyClass { // The class
public: // Access specifier
MyClass() { // Constructor
cout << "Hello World!";
}
};

int main() {
MyClass myObj; // Create an object of MyClass (this will call
the constructor)
return 0;
}

Note: The constructor has the same name as the class, it is always public, and
it does not have any return value.

Constructor Parameters

Constructors can also take parameters (just like regular functions), which can be
useful for setting initial values for attributes.
The following class have brand, model and year attributes, and a constructor with
different parameters. Inside the constructor we set the attributes equal to the
constructor parameters (brand=x, etc). When we call the constructor (by creating
an object of the class), we pass parameters to the constructor, which will set the
value of the corresponding attributes to the same:

Example
class Car { // The class
public: // Access specifier
string brand; // Attribute
string model; // Attribute
int year; // Attribute
Car(string x, string y, int z) { // Constructor with parameters
brand = x;
model = y;
year = z;
}
};

int main() {
// Create Car objects and call the constructor with different
values
Car carObj1("BMW", "X5", 1999);
Car carObj2("Ford", "Mustang", 1969);

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

Just like functions, constructors can also be defined outside the class. First,
declare the constructor inside the class, and then define it outside of the class
by specifying the name of the class, followed by the scope
resolution :: operator, followed by the name of the constructor (which is the
same as the class):
Example
class Car { // The class
public: // Access specifier
string brand; // Attribute
string model; // Attribute
int year; // Attribute
Car(string x, string y, int z); // Constructor declaration
};

// Constructor definition outside the class


Car::Car(string x, string y, int z) {
brand = x;
model = y;
year = z;
}

int main() {
// Create Car objects and call the constructor with different
values
Car carObj1("BMW", "X5", 1999);
Car carObj2("Ford", "Mustang", 1969);

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

C++ Access Specifiers

Access Specifiers

By now, you are quite familiar with the public keyword that appears in all of our
class examples:
Example
class MyClass { // The class
public: // Access specifier
// class members goes here
};

The public keyword is an access specifier. Access specifiers define how the
members (attributes and methods) of a class can be accessed. In the example
above, the members are public - which means that they can be accessed and
modified from outside the code.

However, what if we want members to be private and hidden from the outside
world?

In C++, there are three access specifiers:

 public - members are accessible from outside the class


 private - members cannot be accessed (or viewed) from outside the
class
 protected - members cannot be accessed from outside the class, but
they can be accessed in inherited classes.

 In the following example, we demonstrate the differences


between public and private members:

Example
class MyClass

{
public: // Public access specifier
int x; // Public attribute
private: // Private access specifier
int y; // Private attribute
};

int main() {
MyClass myObj;
myObj.x = 25; // Allowed (public)
myObj.y = 50; // Not allowed (private)
return 0;
}

If you try to access a private member, an error occurs:

error: y is private

Note: It is possible to access private members of a class using a public method


inside the same class. See the next chapter (Encapsulation) on how to do this.

Tip: It is considered good practice to declare your class attributes as private (as
often as you can). This will reduce the possibility of yourself (or others) to mess
up the code. This is also the main ingredient of the Encapsulation concept,
which you will learn more about in the next chapter.

Note: By default, all members of a class are private if you don't specify an
access specifier:

Example
class MyClass {
int x; // Private attribute
int y; // Private attribute
};

C++ Encapsulation

Encapsulation
Encapsulation
Encapsulation is an Object Oriented Programming concept that binds together the data
and functions that manipulate the data, and that keeps both safe from outside
interference and misuse. Data encapsulation led to the important OOP concept of data
hiding.
Data encapsulation is a mechanism of bundling the data, and the functions that use
them and data abstraction is a mechanism of exposing only the interfaces and hiding
the implementation details from the user.

The meaning of Encapsulation, is to make sure that "sensitive" data is hidden


from users. To achieve this, you must declare class variables/attributes
as private (cannot be accessed from outside the class). If you want others to
read or modify the value of a private member, you can provide
public get and set methods.

Access Private Members

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

Example
#include <iostream>
using namespace std;

class Employee {
private:
// Private attribute
int salary;

public:
// Setter
void setSalary(int s) {
salary = s;
}
// Getter
int getSalary() {
return salary;
}
};

int main() {
Employee myObj;
myObj.setSalary(50000);
cout << myObj.getSalary();
return 0;
}

Example explained

The salary attribute is private, which have restricted access.

The public setSalary() method takes a parameter (s) and assigns it to


the salary attribute (salary = s).
The public getSalary() method returns the value of the private salary attribute.

Inside main(), we create an object of the Employee class. Now we can use
the setSalary() method to set the value of the private attribute to 50000. Then
we call the getSalary() method on the object to return the value.

Why Encapsulation?

 It is considered good practice to declare your class attributes as private


(as often as you can). Encapsulation ensures better control of your data,
because you (or others) can change one part of the code without affecting
other parts
 Increased security of data

C++ Inheritance

Inheritance
Inheritance

inheritance is a process in which one object acquires all the properties and behaviors of its
parent object automatically. In such way, you can reuse, extend or modify the attributes and
behaviors which are defined in other class.

In C++, it is possible to inherit attributes and methods from one class to


another. We group the "inheritance concept" into two categories:

 derived class (child) - the class that inherits from another class
 base class (parent) - the class being inherited from

To inherit from a class, use the : symbol.

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

Example
// Base class
class Vehicle {
public:
string brand = "Ford";
void honk() {
cout << "Tuut, tuut! \n" ;
}
};

// Derived class
class Car: public Vehicle {
public:
string model = "Mustang";
};

int main() {
Car myCar;
myCar.honk();
cout << myCar.brand + " " + myCar.model;
return 0;
}

Why And When To Use "Inheritance"?


- It is useful for code reusability: reuse attributes and methods of an existing
class when you create a new class.

C++ Multilevel Inheritance

Multilevel Inheritance

A class can also be derived from one class, which is already derived from
another class.

In the following example, MyGrandChild is derived from class MyChild (which is


derived from MyClass).

Example
// Base class (parent)
class MyClass {
public:
void myFunction() {
cout << "Some content in parent class." ;
}
};

// Derived class (child)


class MyChild: public MyClass {
};

// Derived class (grandchild)


class MyGrandChild: public MyChild {
};

int main() {
MyGrandChild myObj;
myObj.myFunction();
return 0;
}

C++ Multiple Inheritance

Multiple Inheritance

A class can also be derived from more than one base class, using a comma-
separated list:

Example
// Base class
class MyClass {
public:
void myFunction() {
cout << "Some content in parent class." ;
}
};

// Another base class


class MyOtherClass {
public:
void myOtherFunction() {
cout << "Some content in another class." ;
}
};

// Derived class
class MyChildClass: public MyClass, public MyOtherClass {
};

int main() {
MyChildClass myObj;
myObj.myFunction();
myObj.myOtherFunction();
return 0;
}

C++ Inheritance Access

Access Specifiers

You learned from the Access Specifiers chapter that there are three specifiers
available in C++. Until now, we have only used public (members of a class are
accessible from outside the class) and private (members can only be accessed
within the class). The third specifier, protected, is similar to private, but it can
also be accessed in the inherited class:

Example
// Base class
class Employee {
protected: // Protected access specifier
int salary;
};

// Derived class
class Programmer: public Employee {
public:
int bonus;
void setSalary(int s) {
salary = s;
}
int getSalary() {
return salary;
}
};

int main() {
Programmer myObj;
myObj.setSalary(50000);
myObj.bonus = 15000;
cout << "Salary: " << myObj.getSalary() << "\n";
cout << "Bonus: " << myObj.bonus << "\n";
return 0;
}

C++ Polymorphism

Polymorphism

Polymorphism means "many forms", and it occurs when we have many classes that are related to
each other by inheritance.

Like Inheritance lets us inherit attributes and methods from another class. Polymorphism uses
those methods to perform different tasks. This allows us to perform a single action in different ways.

For example, think of a base class called Animal that has a method called animalSound(). Derived
classes of Animals could be Pigs, Cats, Dogs, Birds - And they also have their own implementation
of an animal sound (the pig oinks, and the cat meows, etc.):

Example
// Base class
class Animal {
public:
void animalSound() {
cout << "The animal makes a sound \n" ;
}
};

// Derived class
class Pig : public Animal {
public:
void animalSound() {
cout << "The pig says: wee wee \n" ;
}
};

// Derived class
class Dog : public Animal {
public:
void animalSound() {
cout << "The dog says: bow wow \n" ;
}
};

Remember from the Inheritance chapter that we use the : symbol to inherit from a class.

Now we can create Pig and Dog objects and override the animalSound() method:

Example
// Base class
class Animal {
public:
void animalSound() {
cout << "The animal makes a sound \n" ;
}
};

// Derived class
class Pig : public Animal {
public:
void animalSound() {
cout << "The pig says: wee wee \n" ;
}
};

// Derived class
class Dog : public Animal {
public:
void animalSound() {
cout << "The dog says: bow wow \n" ;
}
};

int main() {
Animal myAnimal;
Pig myPig;
Dog myDog;

myAnimal.animalSound();
myPig.animalSound();
myDog.animalSound();
return 0;

C++ Polymorphism

Polymorphism

Polymorphism means "many forms", and it occurs when we have many classes
that are related to each other by inheritance.

Like we specified in the previous chapter; Inheritance lets us inherit attributes


and methods from another class. Polymorphism uses those methods to
perform different tasks. This allows us to perform a single action in different
ways.

For example, think of a base class called Animal that has a method
called animalSound(). Derived classes of Animals could be Pigs, Cats, Dogs, Birds
- And they also have their own implementation of an animal sound (the pig
oinks, and the cat meows, etc.):

Example
// Base class
class Animal {
public:
void animalSound() {
cout << "The animal makes a sound \n" ;
}
};
// Derived class
class Pig : public Animal {
public:
void animalSound() {
cout << "The pig says: wee wee \n" ;
}
};

// Derived class
class Dog : public Animal {
public:
void animalSound() {
cout << "The dog says: bow wow \n" ;
}
};

Remember from the Inheritance chapter that we use the : symbol to inherit
from a class.

Now we can create Pig and Dog objects and override the animalSound() method:

Example
// Base class
class Animal {
public:
void animalSound() {
cout << "The animal makes a sound \n" ;
}
};

// Derived class
class Pig : public Animal {
public:
void animalSound() {
cout << "The pig says: wee wee \n" ;
}
};

// Derived class
class Dog : public Animal {
public:
void animalSound() {
cout << "The dog says: bow wow \n" ;
}
};

int main() {
Animal myAnimal;
Pig myPig;
Dog myDog;

myAnimal.animalSound();
myPig.animalSound();
myDog.animalSound();
return 0;
}

Why And When To Use "Inheritance" and "Polymorphism"?


- It is useful for code reusability: reuse attributes and methods of an existing
class when you create a new class.

End prac lesson


C++ Classes and Objects

Next Page
The main purpose of C++ programming is to add object orientation to the C
programming language and classes are the central feature of C++ that supports object-
oriented programming and are often called user-defined types.
A class is used to specify the form of an object and it combines data representation
and methods for manipulating that data into one neat package. The data and functions
within a class are called members of the class.

C++ Class Definitions


When you define a class, you define a blueprint for a data type. This doesn't actually
define any data, but it does define what the class name means, that is, what an object
of the class will consist of and what operations can be performed on such an object.
A class definition starts with the keyword class followed by the class name; and the
class body, enclosed by a pair of curly braces. A class definition must be followed
either by a semicolon or a list of declarations. For example, we defined the Box data
type using the keyword class as follows −
class Box {
public:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
The keyword public determines the access attributes of the members of the class that
follows it. A public member can be accessed from outside the class anywhere within
the scope of the class object. You can also specify the members of a class
as private or protected which we will discuss in a sub-section.

Define C++ Objects


A class provides the blueprints for objects, so basically an object is created from a
class. We declare objects of a class with exactly the same sort of declaration that we
declare variables of basic types. Following statements declare two objects of class Box

Box Box1; // Declare Box1 of type Box
Box Box2; // Declare Box2 of type Box
Both of the objects Box1 and Box2 will have their own copy of data members.

Accessing the Data Members


The public data members of objects of a class can be accessed using the direct
member access operator (.). Let us try the following example to make the things clear

#include <iostream>

using namespace std;

class Box {
public:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
int main() {
Box Box1; // Declare Box1 of type Box
Box Box2; // Declare Box2 of type Box
double volume = 0.0; // Store the volume of a box here

// box 1 specification
Box1.height = 5.0;
Box1.length = 6.0;
Box1.breadth = 7.0;

// box 2 specification
Box2.height = 10.0;
Box2.length = 12.0;
Box2.breadth = 13.0;

// volume of box 1
volume = Box1.height * Box1.length * Box1.breadth;
cout << "Volume of Box1 : " << volume <<endl;

// volume of box 2
volume = Box2.height * Box2.length * Box2.breadth;
cout << "Volume of Box2 : " << volume <<endl;
return 0;
}

When the above code is compiled and executed, it produces the following result −
Volume of Box1 : 210
Volume of Box2 : 1560
It is important to note that private and protected members can not be accessed directly
using direct member access operator (.) dot operator. We will learn how private and
protected members can be accessed.

Classes and Objects in Detail


So far, you have got very basic idea about C++ Classes and Objects. There are further
interesting concepts related to C++ Classes and Objects which we will discuss in
various sub-sections listed below −

Sr.No Concept & Description

1 Class Member Functions

A member function of a class is a function that has its definition or its prototype
within the class definition like any other variable.
2 Class Access Modifiers
A class member can be defined as public, private or protected. By default
members would be assumed as private.

3 Constructor & Destructor


A class constructor is a special function in a class that is called when a new object
of the class is created.
A destructor is also a special function which is called when created object is
deleted.

4 Copy Constructor
The copy constructor is a constructor which creates an object by initializing it with
an object of the same class, which has been created previously.

5 Friend Functions
A friend function is permitted full access to private and protected members of a
class.

6 Inline Functions
If a function is inline, the compiler places a copy of the code of that function at each point
where the function is called at compile time.

7 this Pointer
Every object has a special pointer this which points to the object itself.

8 Pointer to C++ Classes


A pointer to a class is done exactly the same way a pointer to a structure is. In
fact a class is really just a structure with functions in it.

9 Static Members of a Class


Both data members and function members of a class can be declared as static.

Object Oriented C++


The prime purpose of C++ programming was to add object orientation to the C programming language,
which is in itself one of the most powerful programming languages.

The core of the pure object-oriented programming is to create an object, in code, that has certain
properties and methods. While designing C++ modules, we try to see whole world in the form of objects.
For example a car is an object which has certain properties such as color, number of doors, and the like.
It also has certain methods such as accelerate, brake, and so on.

There are a few principle concepts that form the foundation of object-oriented programming −

Object

This is the basic unit of object oriented programming. That is both data and function that operate on
data are bundled as a unit called as object.

Class

When you define a class, you define a blueprint for an object. This doesn't actually define any data, but
it does define what the class name means, that is, what an object of the class will consist of and what
operations can be performed on such an object.

Abstraction

Data abstraction refers to, providing only essential information to the outside world and hiding their
background details, i.e., to represent the needed information in program without presenting the details.

For example, a database system hides certain details of how data is stored and created and maintained.
Similar way, C++ classes provides different methods to the outside world without giving internal detail
about those methods and data.

Encapsulation

Encapsulation is placing the data and the functions that work on that data in the same place. While
working with procedural languages, it is not always clear which functions work on which variables but
object-oriented programming provides you framework to place the data and the relevant functions
together in the same object.

Inheritance

One of the most useful aspects of object-oriented programming is code reusability. As the name
suggests Inheritance is the process of forming a new class from an existing class that is from the existing
class called as base class, new class is formed called as derived class.

This is a very important concept of object-oriented programming since this feature helps to reduce the
code size.

Polymorphism
The ability to use an operator or function in different ways in other words giving different meaning or
functions to the operators or functions is called polymorphism. Poly refers to many. That is a single
function or an operator functioning in many ways different upon the usage is called polymorphism.

Overloading

The concept of overloading is also a branch of polymorphism. When the exiting operator or function is
made to operate on new data type, it is said to be overloaded.
C++ Files

C++ Files

The fstream library allows us to work with files.

To use the fstream library, include both the


standard <iostream> AND the <fstream> header file:

Example
#include <iostream>
#include <fstream>

There are three objects included in the fstream library, which are used to create,
write or read files:

Object/Data Type Description

ofstream Creates and writes to files

ifstream Reads from files

fstream A combination of ofstream and ifstream: creates, reads, and writes to files

Create and Write To a File

To create a file, use either the ofstream or fstream object, and specify the name
of the file.
To write to the file, use the insertion operator (<<).

Example

#include <iostream>
#include <fstream>
using namespace std;

int main() {
// Create and open a text file
ofstream MyFile("filename.txt");

// Write to the file


MyFile << "Files can be tricky, but it is fun enough!";

// Close the file


MyFile.close();
}

Why do we close the file?


It is considered good practice, and it can clean up unnecessary memory space.

Read a File

To read from a file, use either the ifstream or fstream object, and the name of
the file.

Note that we also use a while loop together with the getline() function (which
belongs to the ifstream object) to read the file line by line, and to print the
content of the file:

Example

// Create a text string, which is used to output the text file


string myText;

// Read from the text file


ifstream MyReadFile("filename.txt");

// Use a while loop together with the getline() function to read


the file line by line
while (getline (MyReadFile, myText)) {
// Output the text from the file
cout << myText;
}

// Close the file


MyReadFile.close();

You might also like