100% found this document useful (1 vote)
269 views

C++ Material

C++ is an object-oriented programming language that is an extension of C. It supports features like inheritance, polymorphism, encapsulation, and abstraction. C++ can be used to create applications like Windows applications, client-server applications, device drivers, and embedded firmware. A basic C++ program prints "Hello World" by using input/output streams and returning 0 from the main function.

Uploaded by

Niranjan
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
269 views

C++ Material

C++ is an object-oriented programming language that is an extension of C. It supports features like inheritance, polymorphism, encapsulation, and abstraction. C++ can be used to create applications like Windows applications, client-server applications, device drivers, and embedded firmware. A basic C++ program prints "Hello World" by using input/output streams and returning 0 from the main function.

Uploaded by

Niranjan
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 109

C++ Tutorial

C++ is an object-oriented programming language. It is an extension to C programming.

What is C++
C++ is a general purpose, case-sensitive, free-form programming language that supports object-
oriented, procedural and generic programming.

C++ is a middle-level language, as it encapsulates both high and low level language features.

Object-Oriented Programming (OOPs)


C++ supports the object-oriented programming, the four major pillar of object-oriented
programming (OOPs) used in C++ are:

1. Inheritance
2. Polymorphism
3. Encapsulation
4. Abstraction

C++ Standard Libraries


Standard C++ programming is divided into three important parts:

o The core library includes the data types, variables and literals, etc.
o The standard library includes the set of functions manipulating strings, files, etc.
o The Standard Template Library (STL) includes the set of methods manipulating a data
structure.

Usage of C++
By the help of C++ programming language, we can develop different types of secured and robust
applications:

o Window application
o Client-Server application
o Device drivers
o Embedded firmware etc

C++ Program

Simple Program:
#include <iostream>  
using namespace std;  
int main() {  
   cout << "Hello C++ Programming";  
   return 0;  
}  

C vs. C++
What is C?
C is a structural or procedural oriented programming language which is machine-independent
and extensively used in various applications.

C is the basic programming language that can be used to develop from the operating systems
(like Windows) to complex programs like Oracle database, Git, Python interpreter, and many
more. C programming language can be called a god's programming language as it forms the
base for other programming languages. If we know the C language, then we can easily learn other
programming languages. C language was developed by the great computer scientist Dennis
Ritchie at the Bell Laboratories. It contains some additional features that make it unique from
other programming languages.

What is C++?
C++ is a special-purpose programming language developed by Bjarne Stroustrup at Bell Labs
circa 1980. C++ language is very similar to C language, and it is so compatible with C that it can
run 99% of C programs without changing any source of code though C++ is an object-oriented
programming language, so it is safer and well-structured programming language than C.

Differences between C & C++.

No C C++
.

1) C follows the procedural style C++ is multi-paradigm. It supports


programming. both procedural and object oriented.

2) Data is less secured in C. In C++, you can use modifiers for class members
to make it inaccessible for outside users.

3) C follows the top-down approach. C++ follows the bottom-up approach.

4) C does not support function overloading. C++ supports function overloading.

5) In C, you can't use functions in structure. In C++, you can use functions in structure.

6) C does not support reference variables. C++ supports reference variables.

7) In C, scanf() and printf() are mainly used C++ mainly uses stream cin and cout to perform
for input/output. input and output operations.
8) Operator overloading is not possible in C. Operator overloading is possible in C++.

9) C programs are divided into procedures C++ programs are divided into functions and
and modules classes.

10) C does not provide the feature of C++ supports the feature of namespace.
namespace.

11) Exception handling is not easy in C. It has C++ provides exception handling using Try and
to perform using other functions. Catch block.

12) C does not support the inheritance. C++ supports inheritance.

C++ history
History of C++ language is interesting to know. Here we are going to discuss brief history of C+
+ language.

C++ programming language was developed in 1980 by Bjarne Stroustrup at bell laboratories of


AT&T (American Telephone & Telegraph), located in U.S.A.

Bjarne Stroustrup is known as the founder of C++ language.

It was develop for adding a feature of OOP (Object Oriented Programming) in C without
significantly changing the C component.

C++ programming is "relative" (called a superset) of C, it means any valid C program is also a
valid C++ program.

Programming languages that were developed before C++ language.

Language Year Developed By

Algol 1960 International Group

BCPL 1967 Martin Richard

B 1970 Ken Thompson

Traditional C 1972 Dennis Ritchie

K&RC 1978 Kernighan & Dennis Ritchie

C++ 1980 Bjarne Stroustrup

C++ Features
C++ is object oriented programming language. It provides a lot of features that are given below.
1) Simple
C++ is a simple language in the sense that it provides structured approach (to break the problem
into parts), rich set of library functions, data types etc.

2) Machine Independent or Portable


Unlike assembly language, c++ programs can be executed in many machines with little bit or no
change. But it is not platform-independent.

3) Mid-level programming language


C++ is also used to do low level programming. It is used to develop system applications such as
kernel, driver etc. It also supports the feature of high level language. That is why it is known as
mid-level language.

4) Structured programming language


C++ is a structured programming language in the sense that we can break the program into parts
using functions. So, it is easy to understand and modify.

5) Rich Library
C++ provides a lot of inbuilt functions that makes the development fast.

6) Memory Management
It supports the feature of dynamic memory allocation. In C++ language, we can free the
allocated memory at any time by calling the free() function.

7) Speed
The compilation and execution time of C++ language is fast.

8) Pointer
C++ provides the feature of pointers. We can directly interact with the memory by using the
pointers. We can use pointers for memory, structures, functions, array etc.
9) Recursion
In C++, we can call the function within the function. It provides code reusability for every
function.

10) Extensible
C++ language is extensible because it can easily adopt new features.

11) Object Oriented


C++ is object oriented programming language. OOPs makes development and maintenance
easier where as in Procedure-oriented programming language it is not easy to manage if code
grows as project size grows.

12) Compiler based


C++ is a compiler based programming language, it means without compilation no C++ program
can be executed. First we need to compile our program using compiler and then we can execute
our program.

Turbo C++ - Download & Installation


There are many compilers available for C++. You need to download any one. Here, we are going
to use Turbo C++. It will work for both C and C++. To install the Turbo C++ software, you need
to follow following steps.

1. Download Turbo C++


2. Create turboc directory inside c drive and extract the tc3.zip inside c:\turboc
3. Double click on install.exe file

1) Download Turbo C++ software


You can download turbo C++ from many sites. download Turbo c++

2) Create turboc directory in c drive and extract the tc3.zip


Now, you need to create a new directory turboc inside the c: drive. Now extract the tc3.zip file in
c:\turboc directory.

3) Double click on the install.exe file and follow steps

C++ Program
Before starting the abcd of C++ language, you need to learn how to write, compile and run the
first C++ program.

To write the first C++ program, open the C++ console and write the following code:

#include <iostream.h>  
#include<conio.h>  
void main() {  
   clrscr();  
   cout << "Welcome to C++ Programming.";   
   getch();  
}  

#include<iostream.h> includes the standard input output library functions. It


provides cin and cout methods for reading from input and writing to output respectively.

#include <conio.h> includes the console input output library functions. The getch() function is


defined in conio.h file.

void main() The main() function is the entry point of every program in C++ language. The
void keyword specifies that it returns no value.

cout << "Welcome to C++ Programming." is used to print the data "Welcome to C++
Programming." on the console.

getch() The getch() function asks for a single character. Until you press any key, it blocks the
screen.

How to compile and run the C++ program


There are 2 ways to compile and run the C++ program, by menu and by shortcut.

By menu

Now click on the compile menu then compile sub menu to compile the c++ program.

Then click on the run menu then run sub menu to run the c++ program.

By shortcut

Or, press ctrl+f9 keys compile and run the program directly.

You will see the following output on user screen.


You can view the user screen any time by pressing the alt+f5 keys.

Now press Esc to return to the turbo c++ console.

C++ Basic Input/Output


C++ I/O operation is using the stream concept. Stream is the sequence of bytes or flow of data. It
makes the performance fast.

If bytes flow from main memory to device like printer, display screen, or a network connection,
etc, this is called as output operation.

If bytes flow from device like printer, display screen, or a network connection, etc to main
memory, this is called as input operation.

I/O Library Header Files


The common header files used in C++ programming are:

Header Function and Description


File

<iostream> It is used to define the cout, cin and cerr objects, which correspond to standard
output stream, standard input stream and standard error stream, respectively.

<iomanip> It is used to declare services useful for performing formatted I/O, such as setprecision
and setw.

<fstream> It is used to declare services for user-controlled file processing.

Standard output stream (cout)


The cout is a predefined object of ostream class. It is connected with the standard output device,
which is usually a display screen. The cout is used in conjunction with stream insertion operator
(<<) to display the output on a console
Simple example of standard output stream (cout):

#include <iostream>  
using namespace std;  
int main( ) {  
   char ary[] = "Welcome to C++ tutorial";  
   cout << "Value of ary is: " << ary << endl;  

Standard input stream (cin)


The cin is a predefined object of istream class. It is connected with the standard input device,
which is usually a keyboard. The cin is used in conjunction with stream extraction operator (>>) to
read the input from a console.

simple example of standard input stream (cin):

#include <iostream>  
using namespace std;  
int main( ) {  
  int age;  
   cout << "Enter your age: ";  
   cin >> age;  
   cout << "Your age is: " << age << endl;  
}  

Standard end line (endl)


The endl is a predefined object of ostream class. It is used to insert a new line characters and
flushes the stream.

Example of standard end line (endl):

#include <iostream>  
using namespace std;  
int main( ) {  
cout << "C++ Tutorial";     
cout << " Javatpoint"<<endl;   
cout << "End of line"<<endl;   
}  

C++ Variable
A variable is a name of memory location. It is used to store data. Its value can be changed and it
can be reused many times.

It is a way to represent memory location through symbol so that it can be easily identified.

syntax to declare a variable:


type variable_list;   

The example of declaring variable is given below:

int x;    
float y;    
char z;    

Here, x, y, z are variables and int, float, char are data types.

We can also provide values while declaring the variables as given below:

int x=5,b=10;  //declaring 2 variable of integer type    
float f=30.8;    
char c='A';    

Rules for defining variables


A variable can have alphabets, digits and underscore.

A variable name can start with alphabet and underscore only. It can't start with digit.

No white space is allowed within variable name.

A variable name must not be any reserved word or keyword e.g. char, float etc.

Valid variable names:

int a;    
int _ab;    
int a30; 

Valid variable names:

int 4;    
int x y;    
int double;

C++ Data Types


A data type specifies the type of data that a variable can store such as integer, floating, character
etc.
There are 4 types of data types in C++ language.

Types Data Types

Basic Data Type int, char, float, double, etc

Derived Data Type array, pointer, etc

Enumeration Data Type enum

User Defined Data Type structure

Basic Data Types


The basic data types are integer-based and floating-point based. C++ language supports both
signed and unsigned literals.

The memory size of basic data types may change according to 32 or 64 bit operating system.

Let's see the basic data types. It size is given according to 32 bit OS.

Data Types Memory Size Range

char 1 byte -128 to 127

signed char 1 byte -128 to 127

unsigned char 1 byte 0 to 127

short 2 byte -32,768 to 32,767

signed short 2 byte -32,768 to 32,767

unsigned short 2 byte 0 to 32,767

int 2 byte -32,768 to 32,767


signed int 2 byte -32,768 to 32,767

unsigned int 2 byte 0 to 32,767

short int 2 byte -32,768 to 32,767

signed short int 2 byte -32,768 to 32,767

unsigned short int 2 byte 0 to 32,767

long int 4 byte

signed long int 4 byte

unsigned long int 4 byte

float 4 byte

double 8 byte

long double 10 byte

C++ Keywords
A keyword is a reserved word. You cannot use it as a variable name, constant name etc. A list of
32 Keywords in C++ Language which are also available in C language are given below.

auto break case char const continue default do

double else enum extern float for goto if

int long register return short signed sizeof static

struct switch typedef union unsigned void volatile while

A list of 30 Keywords in C++ Language which are not available in C language are given
below.

asm dynamic_cast namespace reinterpret_cast bool

explicit new static_cast false catch

operator template friend private class

this inline public throw const_cast

delete mutable protected true try

typeid typename using virtual wchar_t


C++ Operators
An operator is simply a symbol that is used to perform operations. There can be many types of
operations like arithmetic, logical, bitwise etc.

There are following types of operators to perform different types of operations in C language.

o Arithmetic Operators
o Relational Operators
o Logical Operators
o Bitwise Operators
o Assignment Operator
o Unary operator
o Ternary or Conditional Operator
o Misc Operator

C++ Identifiers
C++ identifiers in a program are used to refer to the name of the variables, functions, arrays, or
other user-defined data types created by the programmer. They are the basic requirement of any
language. Every language has its own rules for naming the identifiers.

In short, we can say that the C++ identifiers represent the essential elements in a program which
are given below:

o Constants
o Variables
o Functions
o Labels
o Defined data types
Some naming rules are common in both C and C++. They are as follows:

o Only alphabetic characters, digits, and underscores are allowed.


o The identifier name cannot start with a digit, i.e., the first letter should be alphabetical. After
the first letter, we can use letters, digits, or underscores.
o In C++, uppercase and lowercase letters are distinct. Therefore, we can say that C++
identifiers are case-sensitive.
o A declared keyword cannot be used as a variable name.

For example, suppose we have two identifiers, named as 'FirstName', and 'Firstname'. Both the
identifiers will be different as the letter 'N' in the first case in uppercase while lowercase in second.
Therefore, it proves that identifiers are case-sensitive.

Some naming rules are common in both C and C++. They are as follows:

o Only alphabetic characters, digits, and underscores are allowed.


o The identifier name cannot start with a digit, i.e., the first letter should be alphabetical. After
the first letter, we can use letters, digits, or underscores.
o In C++, uppercase and lowercase letters are distinct. Therefore, we can say that C++
identifiers are case-sensitive.
o A declared keyword cannot be used as a variable name.

For example, suppose we have two identifiers, named as 'FirstName', and 'Firstname'. Both the
identifiers will be different as the letter 'N' in the first case in uppercase while lowercase in second.
Therefore, it proves that identifiers are case-sensitive.

Valid Identifiers

The following are the examples of valid identifiers are:

Result  
Test2  
_sum  
power  

Invalid Identifiers

The following are the examples of invalid identifiers:

Sum-1   // containing special character '-'.  
2data    // the first letter is a digit.   
break    // use of a keyword.  

he major difference between C and C++ is the limit on the length of the name of the variable.
ANSI C considers only the first 32 characters in a name while ANSI C++ imposes no limit on the
length of the name.
Constants are the identifiers that refer to the fixed value, which do not change during the
execution of a program. Both C and C++ support various kinds of literal constants, and they do
have any memory location. For example, 123, 12.34, 037, 0X2, etc. are the literal constants.

Example to understand the concept of identifiers

#include <iostream>  
using namespace std;  
int main()  
{  
    int a;  
    int A;  
    cout<<"Enter the values of 'a' and 'A'";  
    cin>>a;  
    cin>>A;  
    cout<<"\nThe values that you have entered are : "<<a<<" , "<<A;  
    return 0;  
}  

In the above code, we declare two variables 'a' and 'A'. Both the letters are same but they will
behave as different identifiers. As we know that the identifiers are the case-sensitive so both the
identifiers will have different memory locations.

What are the keywords?


Keywords are the reserved words that have a special meaning to the compiler. They are reserved
for a special purpose, which cannot be used as the identifiers. For example, 'for', 'break', 'while',
'if', 'else', etc. are the predefined words where predefined words are those words whose meaning
is already known by the compiler. Whereas, the identifiers are the names which are defined by the
programmer to the program elements such as variables, functions, arrays, objects, classes.

Differences between Identifiers and Keywords

The following is the list of differences between identifiers and keywords:

Identifiers Keywords

Identifiers are the names defined by the programmer Keywords are the reserved words whose
to the basic elements of a program. meaning is known by the compiler.

It is used to identify the name of the variable. It is used to specify the type of entity.

It can consist of letters, digits, and underscore. It contains only letters.

It can use both lowercase and uppercase letters. It uses only lowercase letters.
No special character can be used except the It cannot contain any special character.
underscore.

The starting letter of identifiers can be lowercase, It can be started only with the lowercase
uppercase or underscore. letter.

It can be classified as internal and external identifiers. It cannot be further classified.

Examples are test, result, sum, power, etc. Examples are 'for', 'if', 'else', 'break', etc.

C++ Expression
C++ expression consists of operators, constants, and variables which are arranged according to
the rules of the language. It can also contain function calls which return values. An expression can
consist of one or more operands, zero or more operators to compute a value. Every expression
produces some value which is assigned to the variable with the help of an assignment operator.

Examples of C++ expression:

1. (a+b) - c  
2. (x/y) -z  
3. 4a2 - 5b +c  
4. (a+b) * (x+y)  

An expression can be of following types:


o Constant expressions
o Integral expressions
o Float expressions
o Pointer expressions
o Relational expressions
o Logical expressions
o Bitwise expressions
o Special assignment expressions
If the expression is a combination of the above expressions, such expressions are known as
compound expressions.

Constant expressions
A constant expression is an expression that consists of only constant values. It is an expression
whose value is determined at the compile-time but evaluated at the run-time. It can be composed
of integer, character, floating-point, and enumeration constants.

Constants are used in the following situations:

o It is used in the subscript declarator to describe the array bound.


o It is used after the case keyword in the switch statement.
o It is used as a numeric value in an enum
o It specifies a bit-field width.
o It is used in the pre-processor #if

In the above scenarios, the constant expression can have integer, character, and enumeration
constants. We can use the static and extern keyword with the constants to define the function-
scope.

The following table shows the expression containing constant value:

Expression containing constant Constant value

x = (2/3) * 4 (2/3) * 4

extern int y = 67 67

int z = 43 43

static int a = 56 56
simple program containing constant expression:

#include <iostream>  
using namespace std;  
int main()  
{  
    int x;        // variable declaration.  
    x=(3/2) + 2;  // constant expression  
    cout<<"Value of x is : "<<x;  // displaying the value of x.  
    return 0;  
}  

Integral Expressions
An integer expression is an expression that produces the integer value as output after performing
all the explicit and implicit conversions.

Following are the examples of integral expression:

(x * y) -5        
x + int(9.0)  
where x and y are the integers.  

simple example of integral expression:

#include <iostream>  
using namespace std;  
int main()  
{  
    int x;  // variable declaration.  
    int y;  // variable declaration  
    int z;  // variable declaration  
    cout<<"Enter the values of x and y";  
    cin>>x>>y;  
    z=x+y;  
    cout<<"\n"<<"Value of z is :"<<z; //  displaying the value of z.  
    return 0;  
}  

Float Expressions
A float expression is an expression that produces floating-point value as output after performing
all the explicit and implicit conversions.

The following are the examples of float expressions:

x+y  
(x/10) + y  
34.5  
x+float(10)  

Example:
#include <iostream>  
using namespace std;  
int main()  
{  
      
   float x=8.9;      // variable initialization  
   float y=5.6;      // variable initialization  
   float z;             // variable declaration  
   z=x+y;  
   std::cout <<"value of z is :"  << z<<std::endl;  // displaying the value of z.  
     
  
    return 0;  
}  

Pointer Expressions
A pointer expression is an expression that produces address value as an output.

The following are the examples of pointer expression:

&x  
ptr  
ptr++  
ptr-  

Example.

#include <iostream>  
using namespace std;  
int main()  
{  
      
   int a[]={1,2,3,4,5};  // array initialization  
   int *ptr;       // pointer declaration  
   ptr=a;    // assigning base address of array to the pointer ptr  
   ptr=ptr+1;   // incrementing the value of pointer  
   std::cout <<"value of second element of an array : "  << *ptr<<std::endl;  
   return 0;  
}  
Relational Expressions
A relational expression is an expression that produces a value of type bool, which can be either
true or false. It is also known as a boolean expression. When arithmetic expressions are used on
both sides of the relational operator, arithmetic expressions are evaluated first, and then their
results are compared.

The following are the examples of the relational expression:

a>b  
a-b >= x-y  
a+b>80  

Example

#include <iostream>  
using namespace std;  
int main()  
{  
    int a=45;    // variable declaration  
    int b=78;    // variable declaration  
    bool y= a>b;   // relational expression  
    cout<<"Value of y is :"<<y;  // displaying the value of y.  
    return 0;  
}  

Logical Expressions
A logical expression is an expression that combines two or more relational expressions and
produces a bool type value. The logical operators are '&&' and '||' that combines two or more
relational expressions.

Examples of logical expressions:

a>b && x>y  
a>10 || b==5 

Example of logical expression.

#include <iostream>  
using namespace std;  
int main()  
{  
 int a=2;  
 int b=7;  
 int c=4;  
cout<<((a>b)||(a>c));  
return 0;  
}

Bitwise Expressions
A bitwise expression is an expression which is used to manipulate the data at a bit level. They are
basically used to shift the bits.

For example:

x=3

x>>3 // This statement means that we are shifting the three-bit position to the right.

In the above example, the value of 'x' is 3 and its binary value is 0011. We are shifting the value of
'x' by three-bit position to the right. Let's understand through the diagrammatic representation.

simple example.

#include <iostream>  
using namespace std;  
int main()  
{  
 int x=5;   // variable declaration  
std::cout << (x>>1) << std::endl;  
return 0;  
}  

Special Assignment Expressions


Special assignment expressions are the expressions which can be further classified depending
upon the value assigned to the variable.
o Chained Assignment

Chained assignment expression is an expression in which the same value is assigned to more than
one variable by using single statement.

 Example.

#include <iostream>  
using namespace std;  
int main()  
  
 int a;   // variable declaration  
 int b;   // variable declaration  
 a=b=80;  // chained assignment  
 std::cout <<"Values of 'a' and 'b' are : " <<a<<","<<b<< std::endl;  
 return 0;  
}  

o Embedded Assignment Expression

An embedded assignment expression is an assignment expression in which assignment


expression is enclosed within another assignment expression.

Example.

#include <iostream>  
using namespace std;  
int main()  
{  
 int a;  // variable declaration  
 int b;  // variable declaration  
 a=10+(b=90);  // embedded assignment expression  
 std::cout <<"Values of 'a' is " <<a<< std::endl;  
 return 0;  
}  

o Compound Assignment

A compound assignment expression is an expression which is a combination of an assignment


operator and binary operator.

For example,

a+=10;   

In the above statement, 'a' is a variable and '+=' is a compound statement.

Let's understand through an example.

#include <iostream>  
using namespace std;  
int main()  
{  
  int a=10;   // variable declaration  
  a+=10;    // compound assignment  
  std::cout << "Value of a is :" <<a<< std::endl; // displaying the value of a.  
  return 0;  
}  

C++ Control Statement

C++ if-else
In C++ programming, if statement is used to test the condition. There are various types of if
statements in C++.

o if statement
o if-else statement
o nested if statement
o if-else-if ladder

C++ IF Statement
The C++ if statement tests the condition. It is executed if condition is true.

1. if(condition){    
2. //code to be executed    
3. }  

C++ If Example
#include <iostream>  
using namespace std;  
   
int main () {  
   int num = 10;    
            if (num % 2 == 0)    
            {    
                cout<<"It is even number";    
            }   
   return 0;  
}  

C++ IF-else Statement


The C++ if-else statement also tests the condition. It executes if block if condition is true
otherwise else block is executed.
if(condition){    
//code if condition is true    
}else{    
//code if condition is false    
}   

#include <iostream>  
using namespace std;  
int main () {  
   int num = 11;    
            if (num % 2 == 0)    
            {    
                cout<<"It is even number";    
            }   
            else  
            {    
                cout<<"It is odd number";    
            }  
   return 0;  
}  

C++ If-else Example: with input from user

#include <iostream>  
using namespace std;  
int main () {  
    int num;  
    cout<<"Enter a Number: ";  
    cin>>num;  
            if (num % 2 == 0)    
            {    
                cout<<"It is even number"<<endl;    
            }   
            else  
            {    
                cout<<"It is odd number"<<endl;    
            }  
   return 0;  
}  

C++ IF-else-if ladder Statement


The C++ if-else-if ladder statement executes one condition from multiple statements.
if(condition1){    
//code to be executed if condition1 is true    
}else if(condition2){    
//code to be executed if condition2 is true    
}    
else if(condition3){    
//code to be executed if condition3 is true    
}    
...    
else{    
//code to be executed if all the conditions are false    
}    

C++ If else-if Example

#include <iostream>  
using namespace std;  
int main () {  
       int num;  
       cout<<"Enter a number to check grade:";    
       cin>>num;  
            if (num <0 || num >100)    
            {    
                cout<<"wrong number";    
            }    
            else if(num >= 0 && num < 50){    
                cout<<"Fail";    
            }    
            else if (num >= 50 && num < 60)    
            {    
                cout<<"D Grade";    
            }    
            else if (num >= 60 && num < 70)    
            {    
                cout<<"C Grade";    
            }    
            else if (num >= 70 && num < 80)    
            {    
                cout<<"B Grade";    
            }    
            else if (num >= 80 && num < 90)    
            {    
                cout<<"A Grade";    
            }    
            else if (num >= 90 && num <= 100)    
            {    
                cout<<"A+ Grade";  
            }    
    }    

C++ switch
The C++ switch statement executes one statement from multiple conditions. It is like if-else-if
ladder statement in C++.

switch(expression){      
case value1:      
 //code to be executed;      
 break;    
case value2:      
 //code to be executed;      
 break;    
......      
      
default:       
 //code to be executed if all cases are not matched;      
 break;    
}    

C++ Switch Example


#include <iostream>  
using namespace std;  
int main () {  
       int num;  
       cout<<"Enter a number to check grade:";    
       cin>>num;  
           switch (num)    
          {    
              case 10: 
cout<<"It is 10";
 break;    
              case 20: 
cout<<"It is 20"; 
break;    
              case 30: 
cout<<"It is 30"; 
break;    
              default:
 cout<<"Not 10, 20 or 30";
 break;    
          }    
    }    
C++ For Loop
The C++ for loop is used to iterate a part of the program several times. If the number of iteration
is fixed, it is recommended to use for loop than while or do-while loops.

The C++ for loop is same as C/C#. We can initialize variable, check condition and
increment/decrement

1. for(initialization; condition; incr/decr){    
2. //code to be executed    
3. }  

C++ For Loop Example


1. #include <iostream>  
2. using namespace std;  
3. int main() {  
4.          for(int i=1;i<=10;i++){      
5.             cout<<i <<"\n";      
6.           }       
7.     }   

C++ Nested For Loop


In C++, we can use for loop inside another for loop, it is known as nested for loop. The inner loop
is executed fully when outer loop is executed one time. So if outer loop and inner loop are
executed 4 times, inner loop will be executed 4 times for each outer loop i.e. total 16 times.

C++ Nested For Loop Example


simple example of nested for loop in C++.
1. #include <iostream>  
using namespace std;  
   
int main () {  
        for(int i=1;i<=3;i++){      
             for(int j=1;j<=3;j++){      
            cout<<i<<" "<<j<<"\n";      
          }     
        }  
    }    

C++ Infinite For Loop


If we use double semicolon in for loop, it will be executed infinite times. Let's see a simple
example of infinite for loop in C++.

#include <iostream>  
using namespace std;  
   
int main () {  
        for (; ;)    
          {    
                  cout<<"Infinitive For Loop";    
          }    
    }    

C++ While loop


In C++, while loop is used to iterate a part of the program several times. If the number of
iteration is not fixed, it is recommended to use while loop than for loop

1. while(condition){    
2. //code to be executed    
3. }    

FlowChart
C++ While Loop Example
Example of while loop to print table of 1.

#include <iostream>  
using namespace std;  
int main() {         
 int i=1;      
         while(i<=10)   
       {      
            cout<<i <<"\n";    
            i++;  
          }       
    }  

C++ Nested While Loop Example


In C++, we can use while loop inside another while loop, it is known as nested while loop. The
nested while loop is executed fully when outer loop is executed once.

Example of nested while loop in C++ programming language.

#include <iostream>  
using namespace std;  
int main () {  
        int i=1;      
          while(i<=3)     
          {    
              int j = 1;    
              while (j <= 3)    
{      
            cout<<i<<" "<<j<<"\n";      
            j++;  
          }     
           i++;  
        }  
    }    

C++ Infinitive While Loop Example:


We can also create infinite while loop by passing true as the test condition.

#include <iostream>  
using namespace std;  
int main () {  
        while(true)  
          {    
                  cout<<"Infinitive While Loop";    
          }    
    }    

C++ Do-While Loop


The C++ do-while loop is used to iterate a part of the program several times. If the number of
iteration is not fixed and you must have to execute the loop at least once, it is recommended to
use do-while loop.

The C++ do-while loop is executed at least once because condition is checked after loop body.

1. do{    
2. //code to be executed    
3. }while(condition);  

Flowchart:

C++ do-while Loop Example


Example of C++ do-while loop to print the table of 1.

#include <iostream>  
using namespace std;  
int main() {  
     int i = 1;    
          do{    
              cout<<i<<"\n";    
              i++;    
          } while (i <= 10) ;    
}  

C++ Nested do-while Loop


In C++, if you use do-while loop inside another do-while loop, it is known as nested do-while
loop. The nested do-while loop is executed fully for each outer do-while loop.

Example of nested do-while loop in C++.


#include <iostream>  
using namespace std;  
int main() {  
     int i = 1;    
         do{    
              int j = 1;          
              do{    
                cout<<i<<"\n";        
                  j++;    
              } while (j <= 3) ;    
              i++;    
          } while (i <= 3) ;     
}  

C++ Infinitive do-while Loop


In C++, if you pass true in the do-while loop, it will be infinitive do-while loop.

do{    
//code to be executed    
}while(true);

C++ Infinitive do-while Loop Example


#include <iostream>  
using namespace std;  
int main() {  
      do{    
              cout<<"Infinitive do-while Loop";    
          } while(true);     
}  

C++ Break Statement


The C++ break is used to break loop or switch statement. It breaks the current flow of the
program at the given condition. In case of inner loop, it breaks only inner loop.

jump-statement;      
break; 

Example of C++ break statement which is used inside the loop.

#include <iostream>  
using namespace std;  
int main() {  
      for (int i = 1; i <= 10; i++)    
          {    
              if (i == 5)    
              {    
                  break;    
              }    
        cout<<i<<"\n";    
          }    
}  

C++ Break Statement with Inner Loop


The C++ break statement breaks inner loop only if you use break statement inside the inner loop.

Example:

#include <iostream>  
using namespace std;  
int main()  
{  
    for(int i=1;i<=3;i++){        
            for(int j=1;j<=3;j++){        
                if(i==2&&j==2){        
                    break;        
                        }        
                    cout<<i<<" "<<j<<"\n";             
                    }        
          }    
}  

C++ Continue Statement


The C++ continue statement is used to continue loop. It continues the current flow of the
program and skips the remaining code at specified condition. In case of inner loop, it continues
only inner loop.

jump-statement;      
continue;     

C++ Continue Statement Example


#include <iostream>  
using namespace std;  
int main()  
{  
     for(int i=1;i<=10;i++){      
            if(i==5){      
                continue;      
            }      
            cout<<i<<"\n";      
        }        
}  

C++ Continue Statement with Inner Loop


C++ Continue Statement continues inner loop only if you use continue statement inside the inner
loop.

#include <iostream>  
using namespace std;  
int main()  
{  
 for(int i=1;i<=3;i++){        
            for(int j=1;j<=3;j++){        
             if(i==2&&j==2){        
                continue;        
                        }        
                cout<<i<<" "<<j<<"\n";                  
                    }        
            }            
}  

C++ Goto Statement


The C++ goto statement is also known as jump statement. It is used to transfer control to the
other part of the program. It unconditionally jumps to the specified label.

It can be used to transfer control from deeply nested loop or switch case label.

C++ Goto Statement Example


simple example of goto statement in C++.

#include <iostream>  
using namespace std;  
int main()  
{  
ineligible:    
         cout<<"You are not eligible to vote!\n";    
      cout<<"Enter your age:\n";    
      int age;  
      cin>>age;  
      if (age < 18){    
              goto ineligible;    
      }    
      else    
      {    
              cout<<"You are eligible to vote!";     
      }         
}  

C++ Comments
The C++ comments are statements that are not executed by the compiler. The comments in C++
programming can be used to provide explanation of the code, variable, method or class. By the
help of comments, you can hide the program code also.

There are two types of comments in C++.

o Single Line comment


o Multi Line comment

C++ Single Line Comment


The single line comment starts with // (double slash). Let's see an example of single line comment
in C++.

#include <iostream>  
using namespace std;  
int main()  
{  
 int x = 11; // x is a variable      
 cout<<x<<"\n";         
}  

C++ Multi Line Comment


The C++ multi line comment is used to comment multiple lines of code. It is surrounded by slash
and asterisk (/∗ ..... ∗/). Let's see an example of multi line comment in C++.

#include <ostream>  
using namespace std;  
int main()  
{  
/* declare and   
print variable in C++. */   
 int x = 35;     
 cout<<x<<"\n";         
}  

C++ Functions
The function in C++ language is also known as procedure or subroutine in other programming
languages.
To perform any task, we can create function. A function can be called many times. It provides
modularity and code reusability.

Advantage of functions in C++


There are many advantages of functions.

1) Code Reusability

By creating functions in C++, you can call it many times. So we don't need to write the same code
again and again.

2) Code optimization

It makes the code optimized, we don't need to write much code.

Suppose, you have to check 3 numbers (531, 883 and 781) whether it is prime number or not.
Without using function, you need to write the prime number logic 3 times. So, there is repetition
of code.

But if you use functions, you need to write the logic only once and you can reuse it several times.

Types of Functions
There are two types of functions in C ++ programming:

1. Library Functions: are the functions which are declared in the C++ header files such as ceil(x),
cos(x), exp(x), etc.

2. User-defined functions: are the functions which are created by the C++ programmer, so that
he/she can use it many times. It reduces complexity of a big program and optimizes the code.

Declaration of a function
The syntax of creating function in C++ language is given below:

return_type function_name(data_type parameter...)  
{    
//code to be executed    
}  
C++ Function Example
Example of C++ function.

#include <iostream>  
using namespace std;  
void func() {    
   static int i=0; //static variable    
   int j=0; //local variable    
   i++;    
   j++;    
   cout<<"i=" << i<<" and j=" <<j<<endl;    
}    
int main()  
{  
 func();    
 func();    
 func();    
}  

Call by value and call by reference in C++


There are two ways to pass value or data to function in C language: call by value and call by
reference. Original value is not modified in call by value but it is modified in call by reference.

call by value and call by reference in C++ language one by one.

Call by value in C++


In call by value, original value is not modified.

In call by value, value being passed to the function is locally stored by the function parameter in
stack memory location. If you change the value of function parameter, it is changed for the
current function only. It will not change the value of variable inside the caller method such as
main().

call by value in C++ language by the example given below:

#include <iostream>  
using namespace std;  
void change(int data);  
int main()  
{  
int data = 3;  
change(data);  
cout << "Value of the data is: " << data<< endl;  
return 0;  
}  
void change(int data)  
{  
data = 5;  
}  

Call by reference in C++


In call by reference, original value is modified because we pass reference (address).

Here, address of the value is passed in the function, so actual and formal arguments share the
same address space. Hence, value changed inside the function, is reflected inside as well as
outside the function.

Note: To understand the call by reference, you must have the basic knowledge of pointers.

 call by reference in C++ language by the example given below:

#include<iostream>  
using namespace std;    
void swap(int *x, int *y)  
{  
 int swap;  
 swap=*x;  
 *x=*y;  
 *y=swap;  
}  
int main()   
{    
 int x=500, y=100;    
 swap(&x, &y);  // passing value to function  
 cout<<"Value of x is: "<<x<<endl;  
 cout<<"Value of y is: "<<y<<endl;  
 return 0;  
}    
Difference between call by value and call by reference in C++
No Call by value Call by reference
.

1 A copy of value is passed to the function An address of value is passed to the function

2 Changes made inside the function is not Changes made inside the function is reflected
reflected on other functions outside the function also

3 Actual and formal arguments will be created in Actual and formal arguments will be created
different memory location in same memory location

C++ Recursion
When function is called within the same function, it is known as recursion in C++. The function
which calls the same function, is known as recursive function.

A function that calls itself, and doesn't perform any task after function call, is known as tail
recursion. In tail recursion, we generally call the same function with return statement.

Example of recursion.

recursionfunction(){    
recursionfunction(); //calling self function    
}    

C++ Recursion Example


Example to print factorial number using recursion in C++ language.

#include<iostream>  
using namespace std;    
int main()  
{  
int factorial(int);  
int fact,value;  
cout<<"Enter any number: ";  
cin>>value;  
fact=factorial(value);  
cout<<"Factorial of a number is: "<<fact<<endl;  
return 0;  
}  
int factorial(int n)  
{  
if(n<0)  
return(-1); /*Wrong value*/    
if(n==0)  
return(1);  /*Terminating condition*/  
else  
{  
return(n*factorial(n-1));      
}  
}  

Constants in C++
A constant is a value or variable that can't be changed in the program, for example: 10, 20, 'a', 3.4,
"c++ programming" etc.

There are different types of constants in C++ programming.

List of Constants in C++


Constant Example

Decimal Constant 10, 20, 450 etc.

Real or Floating-point Constant 10.3, 20.2, 450.6 etc.

Octal Constant 021, 033, 046 etc.

Hexadecimal Constant 0x2a, 0x7b, 0xaa etc.

Character Constant 'a', 'b', 'x' etc.

String Constant "c++", "c++ program", "welcome to c++" etc.

2 ways to define constant in C++


There are two ways to define constant in C++ programming.

1. const keyword
2. #define preprocessor

1) C++ const keyword


The const keyword is used to define constant in C++ programming.

const float PI=3.14;

Now, the value of PI variable can't be changed.

#include<iostream.h>    
int main(){    
    const float PI=3.14;    
    Cout<<”The vlue of pi is”<<pi;
    return 0;  
}     

if you try to change the the value of PI, it will render compile time error.

#include<iostream.h>    
int main(){    
const float PI=3.14;     
PI=4.5;    
Cout<<”The vlue of pi is”<<pi;
    return 0;  
}     

2) C++ #define preprocessor


The #define preprocessor is also used to define constant. We will learn about #define
preprocessor directive later.

C++ #define
The #define preprocessor directive is used to define constant or micro substitution. It can use any
basic data type.

Syntax:

#define token value  

Example of #define to define a constant.

#include <iostream.h>  
#define PI 3.14  
main() {  
   cout<<pi;
}  

Example of #define to create a macro.

#include <iostream.h>  
#define MIN(a,b) ((a)<(b)?(a):(b))  
void main() {  
   cout<<"Minimum between 10 and 20 is:"<< MIN(10,20));    
}  

C++ Arrays
Like other programming languages, array in C++ is a group of similar types of elements that have
contiguous memory location.
In C++ std::array is a container that encapsulates fixed size arrays. In C++, array index starts from
0. We can store only fixed set of elements in C++ array.

Advantages of C++ Array


o Code Optimization (less code)
o Random Access
o Easy to traverse data
o Easy to manipulate data
o Easy to sort data etc.

Disadvantages of C++ Array


o Fixed size

C++ Array Types


There are 2 types of arrays in C++ programming:

1. Single Dimensional Array


2. Multidimensional Array

C++ Single Dimensional Array


Example of C++ array, where we are going to create, initialize and traverse array.

#include <iostream>  
using namespace std;  
int main()  
{  
 int arr[5]={10, 0, 20, 0, 30};  //creating and initializing array    
        //traversing array    
        for (int i = 0; i < 5; i++)    
        {    
            cout<<arr[i]<<"\n";    
        }    
}  
C++ Array Example: Traversal using foreach loop
We can also traverse the array elements using foreach loop. It returns array element one by one.

#include <iostream>  
using namespace std;  
int main()  
{  
 int arr[5]={10, 0, 20, 0, 30}; //creating and initializing array    
        //traversing array    
       for (int i: arr)     
        {    
            cout<<i<<"\n";    
        }    
}  

C++ Passing Array to Function


In C++, to reuse the array logic, we can create function. To pass array to function in C++, we need
to provide only array name.

functionname(arrayname); //passing array to function    

C++ Passing Array to Function Example: print array elements


Example of C++ function which prints the array elements.

#include <iostream>  
using namespace std;  
void printArray(int arr[5]);  
int main()  
{  
        int arr1[5] = { 10, 20, 30, 40, 50 };    
        int arr2[5] = { 5, 15, 25, 35, 45 };    
        printArray(arr1); //passing array to function    
        printArray(arr2);  
}  
void printArray(int arr[5])  
{  
    cout << "Printing array elements:"<< endl;  
    for (int i = 0; i < 5; i++)  
    {  
                   cout<<arr[i]<<"\n";    
    }  
}  
C++ Multidimensional Arrays
The multidimensional array is also known as rectangular arrays in C++. It can be two dimensional
or three dimensional. The data is stored in tabular form (row ∗ column) which is also known as
matrix.

C++ Multidimensional Array Example


Example of multidimensional array in C++ which declares, initializes and traverse two dimensional
arrays.

#include <iostream>  
using namespace std;  
int main()  
{  
  int test[3][3];  //declaration of 2D array   
    test[0][0]=5;  //initialization   
    test[0][1]=10;   
    test[1][1]=15;  
    test[1][2]=20;  
    test[2][0]=30;  
    test[2][2]=10;  
    //traversal    
    for(int i = 0; i < 3; ++i)  
    {  
        for(int j = 0; j < 3; ++j)  
        {  
            cout<< test[i][j]<<" ";  
        }  
        cout<<"\n"; //new line at each row   
    }  
    return 0;  
}  

C++ Multidimensional Array Example: Declaration and


initialization at same time
Example of multidimensional array which initializes array at the time of declaration.

#include <iostream>  
using namespace std;  
int main()  
{  
  int test[3][3] =  
    {  
        {2, 5, 5},  
        {4, 0, 3},  
        {9, 1, 8}  };  //declaration and initialization    
    //traversal    
    for(int i = 0; i < 3; ++i)  
    {  
        for(int j = 0; j < 3; ++j)  
        {  
            cout<< test[i][j]<<" ";  
        }  
        cout<<"\n"; //new line at each row   
    }  
    return 0;  
}  

C++ Pointers
The pointer in C++ language is a variable, it is also known as locator or indicator that points to an
address of a value.

Advantage of pointer

1) Pointer reduces the code and improves the performance, it is used to retrieving strings, trees
etc. and used with arrays, structures and functions.

2) We can return multiple values from function using pointer.

3) It makes you able to access any memory location in the computer's memory.

Usage of pointer

There are many usage of pointers in C++ language.

1) Dynamic memory allocation

In c language, we can dynamically allocate memory using malloc() and calloc() functions where
pointer is used.

2) Arrays, Functions and Structures

Pointers in c language are widely used in arrays, functions and structures. It reduces the code and
improves the performance.

Symbols used in pointer


Symbol Name Description
& (ampersand sign) Address operator Determine the address of a variable.

∗ (asterisk sign) Indirection operator Access the value of an address.

Declaring a pointer
The pointer in C++ language can be declared using ∗ (asterisk symbol).

int ∗   a; //pointer to int    
char ∗  c; //pointer to char    

Pointer Example
Example of using pointers printing the address and value.

#include <iostream>  
using namespace std;  
int main()  
{  
int number=30;    
int ∗   p;      
p=&number;//stores the address of number variable    
cout<<"Address of number variable is:"<<&number<<endl;    
cout<<"Address of p variable is:"<<p<<endl;    
cout<<"Value of p variable is:"<<*p<<endl;    
   return 0;  
}  

Pointer Program to swap 2 numbers without using 3rd


variable
#include <iostream>  
using namespace std;  
int main()  
{  
int a=20,b=10,∗p1=&a,∗p2=&b;    
cout<<"Before swap: ∗p1="<<∗p1<<" ∗p2="<<∗p2<<endl;    
∗p1=∗p1+∗p2;    
∗p2=∗p1-∗p2;    
∗p1=∗p1-∗p2;    
cout<<"After swap: ∗p1="<<∗p1<<" ∗p2="<<∗p2<<endl;    
   return 0;  
}  

sizeof() operator in C++


The sizeof() is an operator that evaluates the size of data type, constants, variable. It is a compile-
time operator as it returns the size of any variable or a constant at the compilation time.
The size, which is calculated by the sizeof() operator, is the amount of RAM occupied in the
computer.

Syntax of the sizeof() operator is given below:

sizeof(data_type);  

In the above syntax, the data_type can be the data type of the data, variables, constants, unions,
structures, or any other user-defined data type.

The sizeof () operator can be applied to the following operand types:

o When an operand is of data type

If the parameter of a sizeof() operator contains the data type of a variable, then


the sizeof() operator will return the size of the data type.

example.

#include <iostream>  
using namespace std;  
int main()  
{  
  // Determining the space in bytes occupied by each data type.  
  std::cout << "Size of integer data type : " <<sizeof(int)<< std::endl;  
  std::cout << "Size of float data type : " <<sizeof(float)<< std::endl;  
  std::cout << "Size of double data type : " <<sizeof(double)<< std::endl;  
  std::cout << "Size of char data type : " <<sizeof(char)<< std::endl;  
  return 0;  
}  

o When an operand is of Class type.

#include <iostream>  
using namespace std;  
class Base  
{  
int a;  
};  
int main()  
{  
Base b;  
std::cout << "Size of class base is : "<<sizeof(b) << std::endl;  
return 0;  
}  
If we add one more integer variable in a class, then the code would look like:

#include <iostream>  
using namespace std;  
class Base  
{  
    int a;  
    int d;  
};  
int main()  
{  
  Base b;  
  std::cout << "Size of class base is : "<<sizeof(b) << std::endl;  
  return 0;  
}  

if we add a char variable in the above code, then the code would look like:

#include <iostream>  
  
using namespace std;  
  
class Base  
{  
    int a;  
    int d;  
    char ch;  
};  
int main()  
{  
  Base b;  
  std::cout << "Size of class base is : "<<sizeof(b) << std::endl;  
    return 0;  
}  

o When an operand is of array type.

#include <iostream>  
using namespace std;  
 int main()  
{  
  int arr[]={10,20,30,40,50};  
  std::cout << "Size of the array 'arr' is : "<<sizeof(arr) << std::endl;  
  return 0;  
}  

o When an operand is of pointer type.

#include <iostream>  
using namespace std;  
int main()  
{  
    int *ptr1=new int(10);  
    std::cout << "size of ptr1 : " <<sizeof(ptr1)<< std::endl;                                                                     
                                                                                                                                                             
   std::cout << "size of *ptr1 : " <<sizeof(*ptr1)<< std::endl;  
   char *ptr2=new char('a');  
   std::cout <<"size of ptr2 : " <<sizeof(ptr2)<< std::endl;  
   std::cout <<"size of *ptr2 : "<<sizeof(*ptr2)<< std::endl;  
   double *ptr3=new double(12.78);  
    std::cout <<"size of ptr3 : " <<sizeof(ptr3)<< std::endl;  
   std::cout <<"size of *ptr3 : "<<sizeof(*ptr3)<< std::endl;  
    return 0;  
}  

C++ Array of Pointers


Array and pointers are closely related to each other. In C++, the name of an array is considered às
a pointer, i.e., the name of an array contains the address of an element. C++ considers the array
name as the address of the first element. For example, if we create an array, i.e., marks which hold
the 20 values of integer type, then marks will contain the address of first element, i.e., marks[0].
Therefore, we can say that array name (marks) is a pointer which is holding the address of the first
element of an array.

Example:
#include <iostream>  
using namespace std;  
int main()  
{  
    int *ptr;  // integer pointer declaration  
    int marks[10]; // marks array declaration  
    std::cout << "Enter the elements of an array :" << std::endl;  
    for(int i=0;i<10;i++)  
    {  
        cin>>marks[i];  
    }  
    ptr=marks; // both marks and ptr pointing to the same element..  
    std::cout << "The value of *ptr is :" <<*ptr<< std::endl;  
    std::cout << "The value of *marks is :" <<*marks<<std::endl;  
}  

 Another example.

#include <iostream>  
using namespace std;  
int main()  
{  
    int ptr1[5]; // integer array declaration  
    int *ptr2[5]; // integer array of pointer declaration  
    std::cout << "Enter five numbers :" << std::endl;  
    for(int i=0;i<5;i++)  
    {  
        std::cin >> ptr1[i];  
    }  
    for(int i=0;i<5;i++)  
    {  
        ptr2[i]=&ptr1[i];   
    }  
    // printing the values of ptr1 array  
    std::cout << "The values are" << std::endl;  
    for(int i=0;i<5;i++)  
    {  
        std::cout << *ptr2[i] << std::endl;  
    }  
    }  

C++ Void Pointer


A void pointer is a general-purpose pointer that can hold the address of any data type, but it is
not associated with any data type.

Syntax of void pointer


1. void *ptr;  

In C++, we cannot assign the address of a variable to the variable of a different data type.
Consider the following example:

int *ptr;  // integer pointer declaration  
float a=10.2; // floating variable initialization  
ptr= &a;  // This statement throws an error.  

In the above example, we declare a pointer of type integer, i.e., ptr and a float variable, i.e., 'a'.
After declaration, we try to store the address of 'a' variable in 'ptr', but this is not possible in C++
as the variable cannot hold the address of different data types.

#include <iostream.h>  
using namespace std;  
int main()  
{  
    int *ptr;  
    float f=10.3;  
    ptr = &f; // error  
    std::cout << "The value of *ptr is : " <<*ptr<< std::endl;  
    return 0;  
}  
In the above program, we declare a pointer of integer type and variable of float type. An integer
pointer variable cannot point to the float variable, but it can point to an only integer variable.

C++ has overcome the above problem by using the C++ void pointer as a void pointer can hold
the address of any data type.

Let's look at a simple example of void pointer.

#include <iostream>  
using namespace std;  
int main()  
{  
  void *ptr;   // void pointer declaration  
  int a=9;   // integer variable initialization  
  ptr=&a;   // storing the address of 'a' variable in a void pointer variable.  
  std::cout << &a << std::endl;  
  std::cout << ptr << std::endl;  
  return 0;  
}  

Function Pointer in C++


As we know that pointers are used to point some variables; similarly, the function pointer is a
pointer used to point functions. It is basically used to store the address of a function. We can call
the function by using the function pointer, or we can also pass the pointer to another function as
a parameter.

They are mainly useful for event-driven applications, callbacks, and even for storing the functions
in arrays.

What is the address of a function?


Computer only understands the low-level language, i.e., binary form. The program we write in C+
+ is always in high-level language, so to convert the program into binary form, we use compiler.
Compiler is a program that converts source code into an executable file. This executable file gets
stored in RAM. The CPU starts the execution from the main() method, and it reads the copy in
RAM but not the original file.

All the functions and machine code instructions are data. This data is a bunch of bytes, and all
these bytes have some address in RAM. The function pointer contains RAM address of the first
instruction of a function.

Syntax for Declaration


The following is the syntax for the declaration of a function pointer:

int (*FuncPtr) (int,int);  

The above syntax is the function declaration. As functions are not simple as variables, but C++ is a
type safe, so function pointers have return type and parameter list. In the above syntax, we first
supply the return type, and then the name of the pointer, i.e., FuncPtr which is surrounded by the
brackets and preceded by the pointer symbol, i.e., (*). After this, we have supplied the parameter
list (int,int). The above function pointer can point to any function which takes two integer
parameters and returns integer type value.

Address of a function
We can get the address of a function very easily. We just need to mention the name of the
function, we do not need to call the function.

Example.

#include <iostream>  
using namespace std;  
int main()  
{  
  std::cout << "Address of a main() function is : " <<&main<< std::endl;  
  return 0;  
}  

In the above program, we are displaying the address of a main() function. To print the address of
a main() function, we have just mentioned the name of the function, there is no bracket not
parameters. Therefore, the name of the function by itself without any brackets or parameters
means the address of a function.

We can use the alternate way to print the address of a function, i.e., &main.

Calling a function indirectly


We can call the function with the help of a function pointer by simply using the name of the
function pointer. The syntax of calling the function through the function pointer would be similar
as we do the calling of the function normally.

#include <iostream>  
using namespace std;  
int add(int a , int b)  
{  
    return a+b;  
}  
int main()  
{  
 int (*funcptr)(int,int);  // function pointer declaration  
 funcptr=add; // funcptr is pointing to the add function  
 int sum=funcptr(5,5);  
 std::cout << "value of sum is :" <<sum<< std::endl;  
  return 0;  
}  

Another example of function pointer.

#include <iostream>  
using namespace std;  
void printname(char *name)  
{  
    std::cout << "Name is :" <<name<< std::endl;  
}  
  
int main()  
{  
    char s[20];  // array declaration  
    void (*ptr)(char*);  // function pointer declaration  
    ptr=printname;  // storing the address of printname in ptr.  
    std::cout << "Enter the name of the person: " << std::endl;  
    cin>>s;  
    cout<<s;  
    ptr(s);  // calling printname() function  
   return 0;  
}  

What is Memory Management?


Memory management is a process of managing computer memory, assigning the memory space
to the programs to improve the overall system performance.

Why is memory management required?


As we know that arrays store the homogeneous data, so most of the time, memory is allocated to
the array at the declaration time. Sometimes the situation arises when the exact memory is not
determined until runtime. To avoid such a situation, we declare an array with a maximum size, but
some memory will be unused. To avoid the wastage of memory, we use the new operator to
allocate the memory dynamically at the run time.

Memory Management Operators


In C language, we use the malloc() or calloc() functions to allocate the memory dynamically at
run time, and free() function is used to deallocate the dynamically allocated memory. C++ also
supports these functions, but C++ also defines unary operators such as new and delete to
perform the same tasks, i.e., allocating and freeing the memory.
New operator
A new operator is used to create the object while a delete operator is used to delete the object.
When the object is created by using the new operator, then the object will exist until we explicitly
use the delete operator to delete the object. Therefore, we can say that the lifetime of the object
is not related to the block structure of the program.

Syntax

pointer_variable = new data-type  

The above syntax is used to create the object using the new operator. In the above
syntax, 'pointer_variable' is the name of the pointer variable, 'new' is the operator, and 'data-
type' defines the type of the data.

Example 1:

int *p;  
p = new int;  

In the above example, 'p' is a pointer of type int.

Example 2:

1. float *q;   
2. q = new float;  

In the above example, 'q' is a pointer of type float.

In the above case, the declaration of pointers and their assignments are done separately. We can
also combine these two statements as follows:

1. int *p = new int;  
2. float *q =   new float;  

Assigning a value to the newly created object


Two ways of assigning values to the newly created object:

o We can assign the value to the newly created object by simply using the assignment
operator. In the above case, we have created two pointers 'p' and 'q' of type int and float,
respectively. Now, we assign the values as follows:

1. *p = 45;  
2. *q = 9.8;  

We assign 45 to the newly created int object and 9.8 to the newly created float object.

o We can also assign the values by using new operator which can be done as follows:

pointer_variable = new data-type(value);  

Examples.
1. int *p = new int(45);  
2. float *p = new float(9.8);  

How to create a single dimensional array


As we know that new operator is used to create memory space for any data-type or even user-
defined data type such as an array, structures, unions, etc., so the syntax for creating a one-
dimensional array is given below:

pointer-variable = new data-type[size];  

Example:
int *a1 = new int[8];  

In the above statement, we have created an array of type int having a size equal to 8 where p[0] refers first element, p[1] refers the first
element, and so on.

Delete operator
When memory is no longer required, then it needs to be deallocated so that the memory can be
used for another purpose. This can be achieved by using the delete operator, as shown below:

delete pointer_variable;   

In the above statement, 'delete' is the operator used to delete the existing object,
and 'pointer_variable' is the name of the pointer variable.

In the previous case, we have created two pointers 'p' and 'q' by using the new operator, and can
be deleted by using the following statements:

1. delete p;  
2. delete q;  

The dynamically allocated array can also be removed from the memory space by using the
following syntax:

delete [size] pointer_variable;   

In the above statement, we need to specify the size that defines the number of elements that are
required to be freed. The drawback of this syntax is that we need to remember the size of the
array. But, in recent versions of C++, we do not need to mention the size as follows:

delete [ ] pointer_variable;   

Example:
#include <iostream>  
using namespace std  
int main()  
{  
int size;  // variable declaration  
int *arr = new int[size];   // creating an array   
cout<<"Enter the size of the array : ";     
std::cin >> size;    //   
cout<<"\nEnter the element : ";  
for(int i=0;i<size;i++)   // for loop  
{  
cin>>arr[i];  
}  
cout<<"\nThe elements that you have entered are :";  
for(int i=0;i<size;i++)    // for loop  
{  
cout<<arr[i]<<",";  
}  
delete arr;  // deleting an existing array.  
return 0;  
}  

Advantages of the new operator


The following are the advantages of the new operator over malloc() function:

o It does not use the sizeof() operator as it automatically computes the size of the data object.
o It automatically returns the correct data type pointer, so it does not need to use the
typecasting.
o Like other operators, the new and delete operator can also be overloaded.
o It also allows you to initialize the data object while creating the memory space for the
object.

C++ OOPs Concepts


The major purpose of C++ programming is to introduce the concept of object orientation to the
C programming language.

Object Oriented Programming is a paradigm that provides many concepts such as inheritance,
data binding, polymorphism etc.

The programming paradigm where everything is represented as an object is known as truly


object-oriented programming language. Smalltalk is considered as the first truly object-oriented
programming language.
OOPs (Object Oriented Programming System)
Object means a real word entity such as pen, chair, table etc. Object-Oriented Programming is a
methodology or paradigm to design a program using classes and objects. It simplifies the
software development and maintenance by providing some concepts:

 Object
 Class
 Inheritance
 Polymorphism
 Abstraction
 Encapsulation

Object
Any entity that has state and behavior is known as an object. For example: chair, pen, table,
keyboard, bike etc. It can be physical and logical.

Class
Collection of objects is called class. It is a logical entity.

Inheritance
When one object acquires all the properties and behaviours of parent object i.e. known as
inheritance. It provides code reusability. It is used to achieve runtime polymorphism.

Polymorphism
When one task is performed by different ways i.e. known as polymorphism. For example: to
convince the customer differently, to draw something e.g. shape or rectangle etc.

In C++, we use Function overloading and Function overriding to achieve polymorphism.

Abstraction
Hiding internal details and showing functionality is known as abstraction. For example: phone
call, we don't know the internal processing.

In C++, we use abstract class and interface to achieve abstraction.

Encapsulation
Binding (or wrapping) code and data together into a single unit is known as
encapsulation. For example: capsule, it is wrapped with different medicines.

Advantage of OOPs over Procedure-oriented programming


language
1. OOPs makes development and maintenance easier where as in Procedure-oriented
programming language it is not easy to manage if code grows as project size grows.
2. OOPs provide data hiding whereas in Procedure-oriented programming language a global
data can be accessed from anywhere.
3. OOPs provide ability to simulate real-world event much more effectively. We can provide
the solution of real word problem if we are using the Object-Oriented Programming
language.

C++ Object and Class


Since C++ is an object-oriented language, program is designed using objects and classes in C++.

C++ Object
In C++, Object is a real world entity, for example, chair, car, pen, mobile, laptop etc.

In other words, object is an entity that has state and behavior. Here, state means data and
behavior means functionality.

Object is a runtime entity, it is created at runtime.

Object is an instance of a class. All the members of the class can be accessed through object.

C++ Class
In C++, class is a group of similar objects. It is a template from which objects are created. It can
have fields, methods, constructors etc.

Example of C++ class that has three fields only.

class Student    
 {    
     public:  
     int id;  //field or data member     
     float salary; //field or data member  
     String name;//field or data member    
 }    

C++ Object and Class Example


Let's see an example of class that has two fields: id and name. It creates instance of the class,
initializes the object and prints the object value.

#include <iostream>  
using namespace std;  
class Student {  
   public:  
      int id;//data member (also instance variable)      
      string name;//data member(also instance variable)      
};  
int main() {  
    Student s1; //creating an object of Student   
    s1.id = 201;    
    s1.name = "Sonoo Jaiswal";   
    cout<<s1.id<<endl;  
    cout<<s1.name<<endl;  
    return 0;  
}  

Example of C++ class where we are initializing and displaying object through method.

#include <iostream>  
using namespace std;  
class Student {  
   public:  
       int id;//data member (also instance variable)      
       string name;//data member(also instance variable)      
       void insert(int i, string n)    
        {    
            id = i;    
            name = n;    
        }    
       void display()    
        {    
            cout<<id<<"  "<<name<<endl;    
        }    
};  
int main(void) {  
    Student s1; //creating an object of Student   
    Student s2; //creating an object of Student  
    s1.insert(201, "Sonoo");    
    s2.insert(202, "Nakul");    
    s1.display();    
    s2.display();  
    return 0;  
}  

Example of C++ class where we are storing and displaying employee information
using method.

#include <iostream>  
using namespace std;  
class Employee {  
   public:  
       int id;//data member (also instance variable)      
       string name;//data member(also instance variable)  
       float salary;  
       void insert(int i, string n, float s)    
        {    
            id = i;    
            name = n;    
            salary = s;  
        }    
       void display()    
        {    
            cout<<id<<"  "<<name<<"  "<<salary<<endl;    
        }    
};  
int main(void) {  
    Employee e1; //creating an object of Employee   
    Employee e2; //creating an object of Employee  
    e1.insert(201, "Sonoo",990000);    
    e2.insert(202, "Nakul", 29000);    
    e1.display();    
    e2.display();    
    return 0;  
}  

Access Modifiers or Visibility modes can be classified into three categories:

o Public: When the member is declared as public, it is accessible to all the functions of the
program.
o Private: When the member is declared as private, it is accessible within the class only.
o Protected: When the member is declared as protected, it is accessible within its own class as
well as the class immediately derived from it.

Visibility of Inherited Members


Base class visibility Derived class visibility

Public Private Protected

Private Not Inherited Not Inherited Not Inherited

Protected Protected Private Protected

Public Public Private Protected


Scope resolution operator in C++

Scope resolution operator (::) in C++ is used to define a function outside a class or
when we want to use a global variable but also has a local variable with the same
name.

C++ programming code


#include <iostream>

using namespace std;
 
char c = 'a';     // global variable (accessible to all functions)
 
int main() {
  char c = 'b';   // local variable (accessible only in main function)
 
  cout << "Local  variable: " << c << "\n";      
  cout << "Global variable: " << ::c << "\n";  // Using scope resolution operator
 
  return 0;
}

Scope resolution operator in class


#include <iostream>
using namespace std;

class Game {
public:
  void play();  // Function declaration
};

// function definition outside the class

void Game::play() {
  cout << "Function defined outside the class.\n";
}

int main() {
  Game g;
  g.play();
  return 0;
}

C++ Constructor
In C++, constructor is a special method which is invoked automatically at the time of object
creation. It is used to initialize the data members of new object generally. The constructor in C++
has the same name as class or structure.

There can be two types of constructors in C++.

o Default constructor
o Parameterized constructor

C++ Default Constructor


A constructor which has no argument is known as default constructor. It is invoked at the time of
creating object.

Example of C++ default Constructor.

#include <iostream>  
using namespace std;  
class Employee  
 {  
   public:  
        Employee()    
        {    
            cout<<"Default Constructor Invoked"<<endl;    
        }    
};  
int main(void)   
{  
    Employee e1; //creating an object of Employee   
    Employee e2;   
    return 0;  
}  

C++ Parameterized Constructor


A constructor which has parameters is called parameterized constructor. It is used to provide
different values to distinct objects.

Example of C++ Parameterized Constructor.

#include <iostream>

using namespace std;

class A {

   private:

   int num1, num2 ;

   public:

   A(int n1, int n2) {


      num1 = n1;

      num2 = n2;

   }

   void display() {

      cout<<"num1 = "<< num1 <<endl;

      cout<<"num2 = "<< num2 <<endl;

   }

};

int main() {

   A obj(3,8);

   obj.display();

   return 0;

C++ Destructor
A destructor works opposite to constructor; it destructs the objects of classes. It can be defined
only once in a class. Like constructors, it is invoked automatically.

A destructor is defined like constructor. It must have same name as class. But it is prefixed with a
tilde sign (~).

C++ Constructor and Destructor Example


Example of constructor and destructor in C++ which is called automatically.

#include <iostream>  
using namespace std;  
class Employee  
 {  
   public:  
        Employee()    
        {    
            cout<<"Constructor Invoked"<<endl;    
        }    
        ~Employee()    
        {    
            cout<<"Destructor Invoked"<<endl;    
        }  
};  
int main(void)   
{  
    Employee e1; //creating an object of Employee   
    Employee e2; //creating an object of Employee  
    return 0;  
}  

C++ this Pointer


In C++ programming, this is a keyword that refers to the current instance of the class. There can
be 3 main usage of this keyword in C++.

o It can be used to pass current object as a parameter to another method.


o It can be used to refer current class instance variable.
o It can be used to declare indexers.

C++ this Pointer Example


Example of this keyword in C++ that refers to the fields of current class.

#include <iostream>  
using namespace std;  
class Employee {  
   public:  
       int id; //data member (also instance variable)      
       string name; //data member(also instance variable)  
       float salary;  
       Employee(int id, string name, float salary)    
        {    
             this->id = id;    
            this->name = name;    
            this->salary = salary;   
        }    
       void display()    
        {    
            cout<<id<<"  "<<name<<"  "<<salary<<endl;    
        }    
};  
int main(void) {  
    Employee e1 =Employee(101, "Sonoo", 890000); //creating an object of Employee   
    Employee e2=Employee(102, "Nakul", 59000); //creating an object of Employee  
    e1.display();    
    e2.display();    
    return 0;  
}

C++ static
In C++, static is a keyword or modifier that belongs to the type not instance. So instance is not
required to access the static members. In C++, static can be field, method, constructor, class,
properties, operator and event.
Advantage of C++ static keyword
Memory efficient: Now we don't need to create instance for accessing the static members, so it
saves memory. Moreover, it belongs to the type, so it will not get memory each time when
instance is created.

C++ Static Field


A field which is declared as static is called static field. Unlike instance field which gets memory
each time whenever you create object, there is only one copy of static field created in the
memory. It is shared to all the objects.

It is used to refer the common property of all objects such as rateOfInterest in case of Account,
companyName in case of Employee etc.

C++ static field example


Let's see the simple example of static field in C++.

#include <iostream>  
using namespace std;  
class Account {  
   public:  
       int accno; //data member (also instance variable)      
       string name; //data member(also instance variable)  
       static float rateOfInterest;   
       Account(int accno, string name)   
        {    
             this->accno = accno;    
            this->name = name;    
        }    
       void display()    
        {    
            cout<<accno<< "<<name<< " "<<rateOfInterest<<endl;   
        }    
};  
float Account::rateOfInterest=6.5;  
int main(void) {  
    Account a1 =Account(201, "Sanjay"); //creating an object of Employee   
    Account a2=Account(202, "Nakul"); //creating an object of Employee  
    a1.display();    
    a2.display();    
    return 0;  
}  

Example of static keyword in C++ which counts the objects.


#include <iostream>  
using namespace std;  
class Account {  
   public:  
       int accno; //data member (also instance variable)      
       string name;   
       static int count;     
       Account(int accno, string name)   
        {    
             this->accno = accno;    
            this->name = name;    
            count++;  
        }    
       void display()    
        {    
            cout<<accno<<" "<<name<<endl;   
        }    
};  
int Account::count=0;  
int main(void) {  
    Account a1 =Account(201, "Sanjay"); //creating an object of Account  
    Account a2=Account(202, "Nakul");   
     Account a3=Account(203, "Ranjana");  
    a1.display();    
    a2.display();    
    a3.display();    
    cout<<"Total Objects are: "<<Account::count;  
    return 0;  
}  

C++ Structs
In C++, classes and structs are blueprints that are used to create the instance of a class. Structs
are used for lightweight objects such as Rectangle, color, Point, etc.

Unlike class, structs in C++ are value type than reference type. It is useful if you have data that is
not intended to be modified after creation of struct.

C++ Structure is a collection of different data types. It is similar to the class that holds different
types of data.

The Syntax Of Structure


struct structure_name  
{  
     // member declarations.  
}   
In the above declaration, a structure is declared by preceding the struct keyword followed by the
identifier(structure name). Inside the curly braces, we can declare the member variables of different
types.

 Consider the following situation:

struct Student  
{  
    char name[20];  
     int id;  
     int age;  
}  

In the above case, Student is a structure contains three variables name, id, and age. When the
structure is declared, no memory is allocated. When the variable of a structure is created, then the
memory is allocated. Let's understand this scenario.

How to create the instance of Structure?


Structure variable can be defined as:

Student s;

Here, s is a structure variable of type Student. When the structure variable is created, the memory
will be allocated. Student structure contains one char variable and two integer variable. Therefore,
the memory for one char variable is 1 byte and two ints will be 2*4 = 8. The total memory
occupied by the s variable is 9 byte.

How to access the variable of Structure:


The variable of the structure can be accessed by simply using the instance of the structure
followed by the dot (.) operator and then the field of the structure.

For example:

s.id = 4;  

In the above statement, we are accessing the id field of the structure Student by using
the dot(.) operator and assigns the value 4 to the id field.

C++ Struct Example

Struct Rectangle which has two data members width and height.

#include <iostream>    
using namespace std;    
 struct Rectangle      
{      
   int width, height;      
      
 };      
int main(void) {    
    struct Rectangle rec;    
    rec.width=8;    
    rec.height=5;    
   cout<<"Area of Rectangle is: "<<(rec.width * rec.height)<<endl;    
 return 0;    
}    

C++ Struct Example: Using Constructor and Method


Example of struct where we are using the constructor to initialize data and method to
calculate the area of rectangle.

#include <iostream>    
using namespace std;    
 struct Rectangle    {      
   int width, height;      
  Rectangle(int w, int h)      
    {      
        width = w;      
        height = h;      
    }      
  void areaOfRectangle() {       
    cout<<"Area of Rectangle is: "<<(width*height); }      
 };      
int main(void) {    
    struct Rectangle rec=Rectangle(4,6);    
    rec.areaOfRectangle();    
   return 0;    
}    

C++ Enumeration
Enum in C++ is a data type that contains fixed set of constants.

It can be used for days of the week (SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY,
FRIDAY and SATURDAY) , directions (NORTH, SOUTH, EAST and WEST) etc. The C++ enum
constants are static and final implicitly.

C++ Enums can be thought of as classes that have fixed set of constants.
Points to remember for C++ Enum
o enum improves type safety
o enum can be easily used in switch
o enum can be traversed
o enum can have fields, constructors and methods
o enum may implement many interfaces but cannot extend any class because it internally
extends Enum class

C++ Enumeration Example


Example of enum data type used in C++ program.

#include <iostream>  
using namespace std;  
enum week { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday };  
int main()  
{  
    week day;  
    day = Friday;  
    cout << "Day: " << day+1<<endl;  
    return 0;  
}     

C++ Friend function


If a function is defined as a friend function in C++, then the protected and private data of a class
can be accessed using the function.

By using the keyword friend compiler knows the given function is a friend function.

For accessing the data, the declaration of a friend function should be done inside the body of a
class starting with the keyword friend.

Declaration of friend function in C++

class class_name    
{    
    friend data_type function_name(argument/s);            // syntax of friend function.  
};    

in the above declaration, the friend function is preceded by the keyword friend. The function can be
defined anywhere in the program like a normal C++ function. The function definition does not use
either the keyword friend or scope resolution operator.

Characteristics of a Friend function:

o The function is not in the scope of the class to which it has been declared as a friend.
o It cannot be called using the object as it is not in the scope of that class.
o It can be invoked like a normal function without using the object.
o It cannot access the member names directly and has to use an object name and dot
membership operator with the member name.
o It can be declared either in the private or the public part.

C++ friend function Example


Example of C++ friend function used to print the length of a box.

#include <iostream>    
using namespace std;    
class Box    
{    
    private:    
        int length;    
    public:    
        Box(): length(0) { }    
        friend int printLength(Box); //friend function    
};    
int printLength(Box b)    
{    
   b.length += 10;    
    return b.length;    
}    
int main()    
{    
    Box b;    
    cout<<"Length of box: "<< printLength(b)<<endl;    
    return 0;    
}    

 Example when the function is friendly to two classes.

#include <iostream>  
using namespace std;  
class B;          // forward declarartion.  
class A  
{  
    int x;  
    public:  
    void setdata(int i)  
    {  
        x=i;  
    }  
    friend void min(A,B);         // friend function.  
};  
class B  
{  
    int y;  
    public:  
    void setdata(int i)  
    {  
        y=i;  
    }  
    friend void min(A,B);                    // friend function  
};  
void min(A a,B b)  
{  
    if(a.x<=b.y)  
    std::cout << a.x << std::endl;  
    else  
    std::cout << b.y << std::endl;  
}  
   int main()  
{  
   A a;  
   B b;  
   a.setdata(10);  
   b.setdata(20);  
   min(a,b);  
    return 0;  
 }  

C++ Math Functions


C++ offers some basic math functions and the required header file to use these functions is
<math.h>

Trignometric functions
Method Description

cos(x) It computes the cosine of x.

sin(x) It computes the sine of x.

tan(x) It computes the tangent of x.

acos(x) It finds the inverse cosine of x.

asin(x) It finds the inverse sine of x.


atan(x) It finds the inverse tangent of x.

atan2(x,y) It finds the inverse tangent of a coordinate x and y.

Maximum,Minimum and Difference functions


Method Description

fdim(x,y) It calculates the positive difference between x and y.

fmax(x,y) It returns the larger number among two numbers x and y.

fmin() It returns the smaller number among two numbers x and y .

Power functions
Method Description

pow(x,y) It computes x raised to the power y.

sqrt(x) It computes the square root of x.

cbrt(x) It computes the cube root of x.

hypot(x,y) It finds the hypotenuse of a right angled triangle.

Nearest integer operations


Method Description

ceil(x) It rounds up the value of x.

floor(x) It rounds down the value of x.

round(x) It rounds off the value of x.

lround(x) It rounds off the value of x and cast to long integer.

llround(x) It rounds off the value of x and cast to long long integer.

fmod(n,d) It computes the remainder of division n/d.

trunc(x) It rounds off the value x towards zero.


rint(x) It rounds off the value of x using rounding mode.

lrint(x) It rounds off the value of x using rounding mode and cast to long integer.

llrint(x) It rounds off the value x and cast to long long integer.

nearbyint(x) It rounds off the value x to a nearby integral value.

remainder(n,d) It computes the remainder of n/d.

remquo() It computes remainder and quotient both.

Comparison macro functions


Method Description

isgreater(x,y) It determines whether x is greater than y or not.

isgreaterequal(x,y) It determines whether x is greater than or equal to y or not.

less(x,y) It determines whether x is less than y or not.

islessequal(x,y) It determines whether x is less than or equal to y.

islessgreater(x,y) It determines whether x is less or greater than y or not.

isunordered(x,y) It checks whether x can be meaningfully compared or not.

C++ Inheritance
In C++, 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++, the class which inherits the members of another class is called derived class and the class
whose members are inherited is called base class. The derived class is the specialized class for the
base class.

Advantage of C++ Inheritance


Code reusability: Now you can reuse the members of your parent class. So, there is no need to
define the member again. So less code is required in the class.
Types Of Inheritance
C++ supports five types of inheritance:

 Single inheritance
 Multiple inheritance
 Hierarchical inheritance
 Multilevel inheritance
 Hybrid inheritance

Derived Classes
A Derived class is defined as the class derived from the base class.

The Syntax of Derived class:

class derived_class_name :: visibility-mode base_class_name  
{  
    // body of the derived class.  
}  

Where,

derived_class_name: It is the name of the derived class.

visibility mode: The visibility mode specifies whether the features of the base class are publicly
inherited or privately inherited. It can be public or private.

base_class_name: It is the name of the base class.

o When the base class is privately inherited by the derived class, public members of the base
class becomes the private members of the derived class. Therefore, the public members of
the base class are not accessible by the objects of the derived class only by the member
functions of the derived class.
o When the base class is publicly inherited by the derived class, public members of the base
class also become the public members of the derived class. Therefore, the public members
of the base class are accessible by the objects of the derived class as well as by the member
functions of the base class.

Note:
o In C++, the default mode of visibility is private.
o The private members of the base class are never inherited.

C++ Single Inheritance


Single inheritance is defined as the inheritance in which a derived class is inherited from the only
one base class.

Where 'A' is the base class, and 'B' is the derived class.

C++ Single Level Inheritance Example: Inheriting Fields


When one class inherits another class, it is known as single level inheritance. Let's see the example
of single level inheritance which inherits the fields only.

#include <iostream>  
using namespace std;  
 class Account {  
   public:  
   float salary = 60000;   
 };  
   class Programmer: public Account {  
   public:  
   float bonus = 5000;    
   };       
int main(void) {  
     Programmer p1;  
     cout<<"Salary: "<<p1.salary<<endl;    
     cout<<"Bonus: "<<p1.bonus<<endl;    
    return 0;  
}  
C++ Single Level Inheritance Example: Inheriting Methods
Example of inheritance in C++ which inherits methods only.

#include <iostream>  
using namespace std;  
 class Animal {  
   public:  
 void eat() {   
    cout<<"Eating..."<<endl;   
 }    
   };  
   class Dog: public Animal    
   {    
       public:  
     void bark(){  
    cout<<"Barking...";   
     }    
   };   
int main(void) {  
    Dog d1;  
    d1.eat();  
    d1.bark();  
    return 0;  
}  

C++ Multilevel Inheritance

Multilevel inheritance is a process of deriving a class from another derived class.


C++ Multi Level Inheritance Example
When one class inherits another class which is further inherited by another class, it is known as
multi level inheritance in C++. Inheritance is transitive so the last derived class acquires all the
members of all its base classes.

Example of multi level inheritance in C++.

#include <iostream>  
using namespace std;  
 class Animal {  
   public:  
 void eat() {   
    cout<<"Eating..."<<endl;   
 }    
   };  
   class Dog: public Animal   
   {    
       public:  
     void bark(){  
    cout<<"Barking..."<<endl;   
     }    
   };   
   class BabyDog: public Dog   
   {    
       public:  
     void weep() {  
    cout<<"Weeping...";   
     }    
   };   
int main(void) {  
    BabyDog d1;  
    d1.eat();  
    d1.bark();  
     d1.weep();  
     return 0;  
}  

C++ Multiple Inheritance


Multiple inheritance is the process of deriving a new class that inherits the attributes from two
or more classes.
Syntax of the Derived class:

class D : visibility B-1, visibility B-2, 
{  
    // Body of the class;  
}   

Example of multiple inheritance.

#include <iostream>  
using namespace std;  
class A  
{  
    protected:  
     int a;  
    public:  
    void get_a(int n)  
    {  
        a = n;  
    }  
};  
  
class B  
{  
    protected:  
    int b;  
    public:  
    void get_b(int n)  
    {  
        b = n;  
    }  
};  
class C : public A,public B  
{  
   public:  
    void display()  
    {  
        std::cout << "The value of a is : " <<a<< std::endl;  
        std::cout << "The value of b is : " <<b<< std::endl;  
        cout<<"Addition of a and b is : "<<a+b;  
    }  
};  
int main()  
{  
   C c;  
   c.get_a(10);  
   c.get_b(20);  
   c.display();  
  
    return 0;  
}  

In the above example, class 'C' inherits two base classes 'A' and 'B' in a public mode.

Ambiquity Resolution in Inheritance


Ambiguity can be occurred in using the multiple inheritance when a function with the same name
occurs in more than one base class.

Example:

#include <iostream>  
using namespace std;  
class A  
{  
    public:  
    void display()  
    {  
        std::cout << "Class A" << std::endl;  
    }  
};  
class B  
{  
    public:  
    void display()  
    {  
        std::cout << "Class B" << std::endl;  
    }  
};  
class C : public A, public B  
{  
    void view()  
    {  
        display();  
    }  
};  
int main()  
{  
    C c;  
    c.display();  
    return 0;  
}  

o The above issue can be resolved by using the class resolution operator with the function. In
the above example, the derived class code can be rewritten as:
class C : public A, public B  
{  
    void view()  
    {  
        A :: display();         // Calling the display() function of class A.  
        B :: display();         // Calling the display() function of class B.  
  
    }  
};  

C++ Hybrid Inheritance


Hybrid inheritance is a combination of more than one type of inheritance.

Example:

#include <iostream>  
using namespace std;  
class A  
{  
    protected:  
    int a;  
    public:  
    void get_a()  
    {  
       std::cout << "Enter the value of 'a' : " << std::endl;  
       cin>>a;  
    }  
};  
  
class B : public A   
{  
    protected:  
    int b;  
    public:  
    void get_b()  
    {  
        std::cout << "Enter the value of 'b' : " << std::endl;  
       cin>>b;  
    }  
};  
class C   
{  
    protected:  
    int c;  
    public:  
    void get_c()  
    {  
        std::cout << "Enter the value of c is : " << std::endl;  
        cin>>c;  
    }  
};  
  
class D : public B, public C  
{  
    protected:  
    int d;  
    public:  
    void mul()  
    {  
         get_a();  
         get_b();  
         get_c();  
         std::cout << "Multiplication of a,b,c is : " <<a*b*c<< std::endl;  
    }  
};  
int main()  
{  
    D d;  
    d.mul();  
    return 0;  
}  

C++ Hierarchical Inheritance


Hierarchical inheritance is defined as the process of deriving more than one class from a base
class.
Syntax of Hierarchical inheritance:

class A  
{  
    // body of the class A.  
}    
class B : public A   
{  
    // body of class B.  
}  
class C : public A  
{  
    // body of class C.  
}   
class D : public A  
{  
    // body of class D.  
}   

 Example:

#include <iostream>  
using namespace std;  
class Shape                 // Declaration of base class.  
{  
    public:  
    int a;  
    int b;  
    void get_data(int n,int m)  
    {  
        a= n;  
        b = m;  
    }  
};  
class Rectangle : public Shape  // inheriting Shape class  
{  
    public:  
    int rect_area()  
    {  
        int result = a*b;  
        return result;  
    }  
};  
class Triangle : public Shape    // inheriting Shape class  
{  
    public:  
    int triangle_area()  
    {  
        float result = 0.5*a*b;  
        return result;  
    }  
};  
int main()  
{  
    Rectangle r;  
    Triangle t;  
    int length,breadth,base,height;  
    std::cout << "Enter the length and breadth of a rectangle: " << std::endl;  
    cin>>length>>breadth;  
    r.get_data(length,breadth);  
    int m = r.rect_area();  
    std::cout << "Area of the rectangle is : " <<m<< std::endl;  
    std::cout << "Enter the base and height of the triangle: " << std::endl;  
    cin>>base>>height;  
    t.get_data(base,height);  
    float n = t.triangle_area();  
    std::cout <<"Area of the triangle is : "  << n<<std::endl;  
    return 0;  
}  

C++ Polymorphism
The term "Polymorphism" is the combination of "poly" + "morphs" which means many forms. It is
a greek word. In object-oriented programming, we use 3 main concepts: inheritance,
encapsulation, and polymorphism.

Real Life Example Of Polymorphism


Let's consider a real-life example of polymorphism. A lady behaves like a teacher in a classroom,
mother or daughter in a home and customer in a market. Here, a single person is behaving
differently according to the situations.

There are two types of polymorphism in C++:


o Compile time polymorphism: The overloaded functions are invoked by matching the type
and number of arguments. This information is available at the compile time and, therefore,
compiler selects the appropriate function at the compile time. It is achieved by function
overloading and operator overloading which is also known as static binding or early binding.
Now, let's consider the case where function name and prototype is same.

class A                                  //  base class declaration.  
  {  
       int a;  
       public:  
       void display()  
       {   
             cout<< "Class A ";  
        }  
  };  
class B : public A                       //  derived class declaration.  
{  
    int b;  
    public:  
   void display()  
  {  
        cout<<"Class B";  
  }  
};  

In the above case, the prototype of display() function is the same in both the base and derived
class. Therefore, the static binding cannot be applied. It would be great if the appropriate
function is selected at the run time. This is known as run time polymorphism.
74.3K
2. Objects in PHP | Build a CMS using OOP PHP tutorial MVC [2020]

o Run time polymorphism: Run time polymorphism is achieved when the object's method is
invoked at the run time instead of compile time. It is achieved by method overriding which is
also known as dynamic binding or late binding.

Differences b/w compile time and run time polymorphism.

Compile time polymorphism Run time polymorphism

The function to be invoked is known at the compile The function to be invoked is known at the run
time. time.

It is also known as overloading, early binding and It is also known as overriding, Dynamic
static binding. binding and late binding.

Overloading is a compile time polymorphism where Overriding is a run time polymorphism where
more than one method is having the same name but more than one method is having the same
with the different number of parameters or the type name, number of parameters and the type of
of the parameters. the parameters.

It is achieved by function overloading and operator It is achieved by virtual functions and pointers.
overloading.

It provides fast execution as it is known at the It provides slow execution as it is known at the
compile time. run time.

It is less flexible as mainly all the things execute at It is more flexible as all the things execute at
the compile time. the run time.

C++ Runtime Polymorphism Example


Example of run time polymorphism in C++.

Example without the virtual keyword.

#include <iostream>    
using namespace std;    
class Animal {    
    public:    
void eat(){      
cout<<"Eating...";      
    }        
};     
class Dog: public Animal      
{      
 public:    
 void eat()      
    {           cout<<"Eating bread...";      
    }      
};    
int main(void) {    
   Dog d = Dog();      
   d.eat();    
   return 0;    
}    

C++ Run time Polymorphism Example: By using two derived


class
Example of run time polymorphism in C++ where we are having two derived classes.

Example with virtual keyword.


#include <iostream>    
using namespace std;    
class Shape {                                        //  base class  
    public:    
virtual void draw(){                             // virtual function  
cout<<"drawing..."<<endl;      
    }        
};     
class Rectangle: public Shape                  //  inheriting Shape class.  
{      
 public:    
 void draw()      
   {      
       cout<<"drawing rectangle..."<<endl;      
    }      
};    
class Circle: public Shape                        //  inheriting Shape class.  
  
{      
 public:    
 void draw()      
   {      
      cout<<"drawing circle..."<<endl;      
   }      
};    
int main(void) {    
    Shape *s;                               //  base class pointer.  
    Shape sh;                               // base class object.  
       Rectangle rec;    
        Circle cir;    
      s=&sh;    
     s->draw();     
        s=&rec;    
     s->draw();      
    s=?    
    s->draw();     
}    

C++ Overloading (Function and Operator)


If we create two or more members having the same name but different in number or type of
parameter, it is known as C++ overloading. In C++, we can overload:

o methods,
o constructors, and
o indexed properties
It is because these members have parameters only.

Types of overloading in C++ are:


o Function overloading
o Operator overloading

C++ Function Overloading


Function Overloading is defined as the process of having two or more function with the same
name, but different in parameters is known as function overloading in C++. In function
overloading, the function is redefined by using either different types of arguments or a different
number of arguments. It is only through these differences compiler can differentiate between the
functions.

The advantage of Function overloading is that it increases the readability of the program because
you don't need to use different names for the same action.

C++ Function Overloading Example


Let's see the simple example of function overloading where we are changing number of
arguments of add() method.

// program of function overloading when number of arguments vary.

#include <iostream>    
using namespace std;    
class Cal {    
    public:    
static int add(int a,int b){      
        return a + b;      
    }      
static int add(int a, int b, int c)      
    {      
        return a + b + c;      
    }      
};     
int main(void) {    
    Cal C;                                                    //     class object declaration.   
    cout<<C.add(10, 20)<<endl;      
    cout<<C.add(12, 20, 23);     
   return 0;    
}    
Example when the type of the arguments vary.

// Program of function overloading with different types of arguments.

#include<iostream>  
using namespace std;  
int mul(int,int);  
float mul(float,int);  
  
  
int mul(int a,int b)  
{  
    return a*b;  
}  
float mul(double x, int y)  
{  
    return x*y;  
}  
int main()  
{  
    int r1 = mul(6,7);  
    float r2 = mul(0.2,3);   
    std::cout << "r1 is : " <<r1<< std::endl;  
    std::cout <<"r2 is : "  <<r2<< std::endl;  
    return 0;  
}  

C++ Operators Overloading


Operator overloading is a compile-time polymorphism in which the operator is overloaded to
provide the special meaning to the user-defined data type. Operator overloading is used to
overload or redefines most of the operators available in C++. It is used to perform the operation
on the user-defined data type. For example, C++ provides the ability to add the variables of the
user-defined data type that is applied to the built-in data types.

The advantage of Operators overloading is to perform different operations on the same operand.

Operator that cannot be overloaded are as follows:

o Scope operator (::)


o Sizeof
o member selector(.)
o member pointer selector(*)
o ternary operator(?:)

Syntax of Operator Overloading


return_type class_name  : : operator op(argument_list)  
{  
     // body of the function.  
}  

Where the return type is the type of value returned by the function.

class_name is the name of the class.

operator op is an operator function where op is the operator being overloaded, and the operator
is the keyword.

Rules for Operator Overloading


o Existing operators can only be overloaded, but the new operators cannot be overloaded.
o The overloaded operator contains atleast one operand of the user-defined data type.
o We cannot use friend function to overload certain operators. However, the member function
can be used to overload those operators.
o When unary operators are overloaded through a member function take no explicit
arguments, but, if they are overloaded by a friend function, takes one argument.
o When binary operators are overloaded through a member function takes one explicit
argument, and if they are overloaded through a friend function takes two explicit
arguments.

C++ Operators Overloading Example


Example of operator overloading in C++. In this example, void operator ++ () operator function is
defined (inside Test class).

program to overload the unary operator ++.

#include <iostream>    
using namespace std;    
class Test    
{    
   private:    
      int num;    
   public:    
       Test(): num(8){}    
       void operator ++()         {     
          num = num+2;     
       }    
       void Print() {     
           cout<<"The Count is: "<<num;     
       }    
};    
int main()    
{    
    Test tt;    
    ++tt;  // calling of a function "void operator ++()"    
    tt.Print();    
    return 0;    
}    

Example of overloading the binary operators.

// program to overload the binary operators.

#include <iostream>  
using namespace std;  
class A  
{  
    
    int x;  
      public:  
      A(){}  
    A(int i)  
    {  
       x=i;  
    }  
    void operator+(A);  
    void display();  
};  
  
void A :: operator+(A a)  
{  
     
    int m = x+a.x;  
    cout<<"The result of the addition of two objects is : "<<m;  
  
}  
int main()  
{  
    A a1(5);  
    A a2(4);  
    a1+a2;  
    return 0;  
}  

C++ Function Overriding


If derived class defines same function as defined in its base class, it is known as function
overriding in C++. It is used to achieve runtime polymorphism. It enables you to provide specific
implementation of the function which is already provided by its base class.

C++ Function Overriding Example


Example of Function overriding in C++. In this example, we are overriding the eat() function.
#include <iostream>  
using namespace std;  
class Animal {  
    public:  
void eat(){    
cout<<"Eating...";    
    }      
};   
class Dog: public Animal    
{    
 public:  
 void eat()    
    {    
       cout<<"Eating bread...";    
    }    
};  
int main(void) {  
   Dog d = Dog();    
   d.eat();  
   return 0;  
}  

C++ virtual function


o A C++ virtual function is a member function in the base class that you redefine in a derived
class. It is declared using the virtual keyword.
o It is used to tell the compiler to perform dynamic linkage or late binding on the function.
o There is a necessity to use the single pointer to refer to all the objects of the different
classes. So, we create the pointer to the base class that refers to all the derived objects. But,
when base class pointer contains the address of the derived class object, always executes
the base class function. This issue can only be resolved by using the 'virtual' function.
o A 'virtual' is a keyword preceding the normal declaration of a function.
o When the function is made virtual, C++ determines which function is to be invoked at the
runtime based on the type of the object pointed by the base class pointer.

Late binding or Dynamic linkage


In late binding function call is resolved during runtime. Therefore compiler determines the type of
object at runtime, and then binds the function call.

Rules of Virtual Function

o Virtual functions must be members of some class.


o Virtual functions cannot be static members.
o They are accessed through object pointers.
o They can be a friend of another class.
o A virtual function must be defined in the base class, even though it is not used.
o The prototypes of a virtual function of the base class and all the derived classes must be
identical. If the two functions with the same name but different prototypes, C++ will
consider them as the overloaded functions.
o We cannot have a virtual constructor, but we can have a virtual destructor

Consider the situation when we don't use the virtual keyword.

#include <iostream>  
using namespace std;  
class A  
{  
   int x=5;  
    public:  
    void display()  
    {  
        std::cout << "Value of x is : " << x<<std::endl;  
    }  
};  
class B: public A  
{  
    int y = 10;  
    public:  
    void display()  
    {  
        std::cout << "Value of y is : " <<y<< std::endl;  
    }  
};  
int main()  
{  
    A *a;  
    B b;  
    a = &b;  
   a->display();  
    return 0;  
}  

C++ virtual function Example


Example of C++ virtual function used to invoked the derived class in a program.

#include <iostream>    
{    
 public:    
 virtual void display()    
 {    
  cout << "Base class is invoked"<<endl;    
 }    
};    
class B:public A    
{    
 public:    
 void display()    
 {    
  cout << "Derived Class is invoked"<<endl;    
 }    
};    
int main()    
{    
 A* a;    //pointer of base class    
 B b;     //object of derived class    
 a = &b;    
 a->display();   //Late Binding occurs    
}    

Pure Virtual Function


o A virtual function is not used for performing any task. It only serves as a placeholder.
o When the function has no definition, such function is known as "do-nothing" function.
o The "do-nothing" function is known as a pure virtual function. A pure virtual function is a
function declared in the base class that has no definition relative to the base class.
o A class containing the pure virtual function cannot be used to declare the objects of its own,
such classes are known as abstract base classes.
o The main objective of the base class is to provide the traits to the derived classes and to
create the base pointer used for achieving the runtime polymorphism.

Pure virtual function can be defined as:

virtual void display() = 0;   

Example:

#include <iostream>  
using namespace std;  
class Base  
{  
    public:  
    virtual void show() = 0;  
};  
class Derived : public Base  
{  
    public:  
    void show()  
    {  
        std::cout << "Derived class is derived from the base class." << std::endl;  
    }  
};  
int main()  
{  
    Base *bptr;  
    //Base b;  
    Derived d;  
    bptr = &d;  
    bptr->show();  
    return 0;  
}  

Interfaces in C++ (Abstract Classes)


Abstract classes are the way to achieve abstraction in C++. Abstraction in C++ is the process to
hide the internal details and showing functionality only. Abstraction can be achieved by two ways:

1. Abstract class
2. Interface

Abstract class and interface both can have abstract methods which are necessary for abstraction.

C++ Abstract class

In C++ class is made abstract by declaring at least one of its functions as <>strong>pure virtual
function. A pure virtual function is specified by placing "= 0" in its declaration. Its implementation
must be provided by derived classes.

Example of abstract class in C++ which has one abstract method draw(). Its implementation is
provided by derived classes: Rectangle and Circle. Both classes have different implementation.

#include <iostream>  
using namespace std;  
 class Shape    
{    
    public:   
    virtual void draw()=0;    
};    
 class Rectangle : Shape    
{    
    public:  
     void draw()    
    {    
        cout < <"drawing rectangle..." < <endl;    
    }    
};    
class Circle : Shape    
{    
    public:  
     void draw()    
    {    
        cout <<"drawing circle..." < <endl;    
    }    
};    
int main( ) {  
    Rectangle rec;  
    Circle cir;  
    rec.draw();    
    cir.draw();   
   return 0;  
}  

C++ Namespaces
Namespaces in C++ are used to organize too many classes so that it can be easy to handle the
application.

For accessing the class of a namespace, we need to use namespacename::classname. We can


use using keyword so that we don't have to use complete name all the time.

In C++, global namespace is the root namespace. The global::std will always refer to the
namespace "std" of C++ Framework.

C++ namespace Example


Example of namespace which include variable and functions.

#include <iostream>  
using namespace std;  
namespace First {    
    void sayHello() {   
        cout<<"Hello First Namespace"<<endl;          
    }    
}    
namespace Second  {    
       void sayHello() {   
           cout<<"Hello Second Namespace"<<endl;   
       }    
}   
int main()  
{  
 First::sayHello();  
 Second::sayHello();  
return 0;  
}

C++ namespace example: by using keyword


Let's see another example of namespace where we are using "using" keyword so that we don't
have to use complete name for accessing a namespace program.

#include <iostream>  
using namespace std;  
namespace First{  
   void sayHello(){  
      cout << "Hello First Namespace" << endl;  
   }  
}  
namespace Second{  
   void sayHello(){  
      cout << "Hello Second Namespace" << endl;  
   }  
}  
using namespace First;  
int main () {  
   sayHello();  
   return 0;  
}  

C++ Strings
In C++, string is an object of std::string class that represents sequence of characters. We can
perform many operations on strings such as concatenation, comparison, conversion etc.

C++ String Example


Example of C++ string.

#include <iostream>  
using namespace std;  
int main( ) {  
    string s1 = "Hello";    
        char ch[] = { 'C', '+', '+'};    
        string s2 = string(ch);    
        cout<<s1<<endl;    
        cout<<s2<<endl;    

C++ String Compare Example


Let's see the simple example of string comparison using strcmp() function.
#include <iostream>  
#include <cstring>  
using namespace std;  
int main ()  
{  
  char key[] = "mango";  
  char buffer[50];  
  do {  
     cout<<"What is my favourite fruit? ";  
     cin>>buffer;  
  } while (strcmp (key,buffer) != 0);  
 cout<<"Answer is correct!!"<<endl;  
  return 0;  
}  

C++ String Concat Example


Example of string concatenation using strcat() function.

#include <iostream>  
#include <cstring>  
using namespace std;  
int main()  
{  
    char key[25], buffer[25];  
    cout << "Enter the key string: ";  
    cin.getline(key, 25);  
    cout << "Enter the buffer string: ";  
     cin.getline(buffer, 25);  
    strcat(key, buffer);   
    cout << "Key = " << key << endl;  
    cout << "Buffer = " << buffer<<endl;  
    return 0;  
}  

C++ String Copy Example


Example of copy the string using strcpy() function.

#include <iostream>  
#include <cstring>  
using namespace std;  
int main()  
{  
    char key[25], buffer[25];  
    cout << "Enter the key string: ";  
    cin.getline(key, 25);  
    strcpy(buffer, key);  
    cout << "Key = "<< key << endl;  
    cout << "Buffer = "<< buffer<<endl;  
    return 0;  
}  

C++ String Length Example


Example of finding the string length using strlen() function.

#include <iostream>  
#include <cstring>  
using namespace std;  
int main()  
{  
    char ary[] = "Welcome to C++ Programming";  
    cout << "Length of String = " << strlen(ary)<<endl;  
    return 0;  
}  

C++ Exception Handling


Exception Handling in C++ is a process to handle runtime errors. We perform exception handling
so the normal flow of the application can be maintained even after runtime errors.

In C++, exception is an event or object which is thrown at runtime. All exceptions are derived
from std::exception class. It is a runtime error which can be handled. If we don't handle the
exception, it prints exception message and terminates the program.

Advantage
It maintains the normal flow of the application. In such case, rest of the code is executed even
after exception.

C++ Exception Classes


In C++ standard exceptions are defined in <exception> class that we can use inside our
programs. The arrangement of parent-child class hierarchy is shown below:
All the exception classes in C++ are derived from std::exception class. Let's see the list of C++
common exception classes.

Exception Description

std::exception It is an exception and parent class of all standard C++ exceptions.

std::logic_failure It is an exception that can be detected by reading a code.

std::runtime_error It is an exception that cannot be detected by reading a code.

std::bad_exception It is used to handle the unexpected exceptions in a c++ program.

std::bad_cast This exception is generally be thrown by dynamic_cast.

std::bad_typeid This exception is generally be thrown by typeid.

std::bad_alloc This exception is generally be thrown by new.

C++ Exception Handling Keywords


In C++, we use 3 keywords to perform exception handling:

o try
o catch, and
o throw
C++ try/catch
In C++ programming, exception handling is performed using try/catch statement. The C++ try
block is used to place the code that may occur exception. The catch block is used to handle
the exception.

C++ example without try/catch


#include <iostream>  
using namespace std;  
float division(int x, int y) {  
   return (x/y);  
}  
int main () {  
   int i = 50;  
   int j = 0;  
   float k = 0;  
      k = division(i, j);  
      cout << k << endl;  
   return 0;  
}  

C++ try/catch example

#include <iostream>  
using namespace std;  
float division(int x, int y) {  
   if( y == 0 ) {  
      throw "Attempted to divide by zero!";  
   }  
   return (x/y);  
}  
int main () {  
   int i = 25;  
   int j = 0;  
   float k = 0;  
   try {  
      k = division(i, j);  
      cout << k << endl;  
   }catch (const char* e) {  
      cerr << e << endl;  
   }  
   return 0;  
}  

C++ User-Defined Exceptions


The new exception can be defined by overriding and inheriting exception class functionality.

C++ user-defined exception example


Example of user-defined exception in which std::exception class is used to define the exception.

#include <iostream>  
#include <exception>  
using namespace std;  
class MyException : public exception{  
    public:  
        const char * what() const throw()  
        {  
            return "Attempted to divide by zero!\n";  
        }  
};  
int main()  
{  
    try  
    {  
        int x, y;  
        cout << "Enter the two numbers : \n";  
        cin >> x >> y;  
        if (y == 0)  
        {  
            MyException z;  
            throw z;  
        }  
        else  
        {  
            cout << "x / y = " << x/y << endl;  
        }  
    }  
    catch(exception& e)  
    {  
        cout << e.what();  
    }  
}  

C++ Files and Streams


In  C++ programming we are using the  iostream  standard library, it
provides cin and cout methods for reading from input and writing to output respectively.

To read and write from a file we are using the standard C++ library called fstream. Let us see the
data types define in fstream library is:
Data Type Description

fstream It is used to create files, write information to files, and read information from files.

ifstream It is used to read information from files.

ofstream It is used to create files and write information to the files.

C++ FileStream example: writing to a file


Example of writing to a text file testout.txt using C++ FileStream programming.

#include <iostream>  
#include <fstream>  
using namespace std;  
int main () {  
  ofstream filestream("testout.txt");  
  if (filestream.is_open())  
  {  
    filestream << "Welcome to javaTpoint.\n";  
    filestream << "C++ Tutorial.\n";  
    filestream.close();  
  }  
  else cout <<"File opening is fail.";  
  return 0;  
}  

C++ FileStream example: reading from a file


Example of reading from a text file testout.txt using C++ FileStream programming.

#include <iostream>  
#include <fstream>  
using namespace std;  
int main () {  
  string srg;  
  ifstream filestream("testout.txt");  
  if (filestream.is_open())  
  {  
    while ( getline (filestream,srg) )  
    {  
      cout << srg <<endl;  
    }  
    filestream.close();  
  }  
  else {  
      cout << "File opening is fail."<<endl;   
    }  
  return 0;  
}  

C++ Read and Write Example


Example of writing the data to a text file testout.txt and then reading the data from the file using
C++ FileStream programming.

#include <fstream>  
#include <iostream>  
using namespace std;  
int main () {  
   char input[75];  
   ofstream os;  
   os.open("testout.txt");  
   cout <<"Writing to a text file:" << endl;  
   cout << "Please Enter your name: ";   
   cin.getline(input, 100);  
   os << input << endl;  
   cout << "Please Enter your age: ";   
   cin >> input;  
   cin.ignore();  
   os << input << endl;  
   os.close();  
   ifstream is;   
   string line;  
   is.open("testout.txt");   
   cout << "Reading from a text file:" << endl;   
   while (getline (is,line))  
   {  
   cout << line << endl;  
   }      
   is.close();  
   return 0;  
}  

C++ getline()
The cin is an object which is used to take input from the user but does not allow to take the input
in multiple lines. To accept the multiple lines, we use the getline() function. It is a pre-defined
function defined in a <string.h> header file used to accept a line or a string from the input
stream until the delimiting character is encountered.

Syntax of getline() function:


There are two ways of representing a function:
o The first way of declaring is to pass three parameters.

istream& getline( istream& is, string& str, char delim );  

The above syntax contains three parameters, i.e., is, str, and delim.

Where,

s: It is an object of the istream class that defines from where to read the input stream.

str: It is a string object in which string is stored.

delim: It is the delimiting character.

Return value

This function returns the input stream object, which is passed as a parameter to the function.

o The second way of declaring is to pass two parameters.


o stream& getline( istream& is, string& str );  

The above syntax contains two parameters, i.e., is and str. This syntax is almost similar to the
above syntax; the only difference is that it does not have any delimiting character.

Where,

is: It is an object of the istream class that defines from where to read the input stream.

str: It is a string object in which string is stored.

Return value

This function also returns the input stream, which is passed as a parameter to the function.

Example.

First, we will look at an example where we take the user input without using getline() function.

#include <iostream>  
#include<string.h>  
using namespace std;  
int main()  
{  
string name; // variable declaration  
std::cout << "Enter your name :" << std::endl;  
cin>>name;  
cout<<"\nHello "<<name;  
return 0;  
}  

In the above code, we take the user input by using the statement cin>>name, i.e., we have not used
the getline() function.

Output:
Enter Your Name: john miller

In the above output, we gave the name 'John Miller' as user input, but only 'John' was displayed.
Therefore, we conclude that cin does not consider the character when the space character is
encountered.

To resolve the above problem by using getline() function.

#include <iostream>  
#include<string.h>  
using namespace std;  
int main()  
{  
string name; // variable declaration.  
std::cout << "Enter your name :" << std::endl;  
getline(cin,name); // implementing a getline() function  
cout<<"\nHello "<<name;  
return 0;

}  

In the above code, we have used the getline() function to accept the character even when the space
character is encountered.

Enter your
Output:

Enter Your Name: john miller

In the above output, we can observe that both the words, i.e., John and Miller, are displayed, which
means that the getline() function considers the character after the space character also.

When we do not want to read the character after space then we use the following code:

#include <iostream>  
#include<string.h>  
using namespace std;  
int main()  
{  
string profile; // variable declaration  
std::cout << "Enter your profile :" << std::endl;  
getline(cin,profile,' '); // implementing getline() function with a delimiting character.  
cout<<"\nProfile is :"<<profile;  
}  
C++ Templates
A C++ template is a powerful feature added to C++. It allows you to define the generic classes
and generic functions and thus provides support for generic programming. Generic programming
is a technique where generic types are used as parameters in algorithms so that they can work for
a variety of data types.

Templates can be represented in two ways:

o Function templates
o Class templates

Function Templates:

We can define a template for a function. For example, if we have an add() function, we can create
versions of the add function for adding the int, float or double type values.

Class Template:

We can define a template for a class. For example, a class template can be created for the array
class that can accept the array of various types such as int array, float array or double array.

Function Template
o Generic functions use the concept of a function template. Generic functions define a set of
operations that can be applied to the various types of data.
o The type of the data that the function will operate on depends on the type of the data
passed as a parameter.
o For example, Quick sorting algorithm is implemented using a generic function, it can be
implemented to an array of integers or array of floats.
o A Generic function is created by using the keyword template. The template defines what
function will do.

Syntax of Function Template

template < class Ttype> ret_type func_name(parameter_list)  
{  
    // body of function.  
}  
Where Ttype: It is a placeholder name for a data type used by the function. It is used within the
function definition. It is only a placeholder that the compiler will automatically replace this
placeholder with the actual data type.

class: A class keyword is used to specify a generic type in a template declaration.

Example of a function template:

 #include <iostream>  
using namespace std;  
template<class T> T add(T &a,T &b)  
{  
    T result = a+b;  
    return result;  
      
}  
int main()  
{  
  int i =2;  
  int j =3;  
  float m = 2.3;  
  float n = 1.2;  
  cout<<"Addition of i and j is :"<<add(i,j);  
  cout<<'\n';  
  cout<<"Addition of m and n is :"<<add(m,n);  
  return 0;  
}  

In the above example, we create the function template which can perform the addition operation on
any type either it can be integer, float or double.

Function Templates with Multiple Parameters


We can use more than one generic type in the template function by using the comma to separate
the list.

Syntax
 template<class T1, class T2,.....>  
return_type function_name (arguments of type T1, T2....)  
{  
    // body of function.  
}  

In the above syntax, we have seen that the template function can accept any number of
arguments of a different type.

Example:
#include <iostream>  
using namespace std;  
template<class X,class Y> void fun(X a,Y b)  
{  
    std::cout << "Value of a is : " <<a<< std::endl;  
    std::cout << "Value of b is : " <<b<< std::endl;  
}  
  
int main()  
{  
   fun(15,12.3);  
   
   return 0;  
}  

In the above example, we use two generic types in the template function, i.e., X and Y.

Overloading a Function Template


We can overload the generic function means that the overloaded template functions can differ in
the parameter list.

Example:

#include <iostream>  
using namespace std;  
template<class X> void fun(X a)  
{  
    std::cout << "Value of a is : " <<a<< std::endl;  
}  
template<class X,class Y> void fun(X b ,Y c)  
{  
    std::cout << "Value of b is : " <<b<< std::endl;  
    std::cout << "Value of c is : " <<c<< std::endl;  
}  
int main()  
{  
   fun(10);  
   fun(20,30.5);  
   return 0;  
}  

In the above example, template of fun() function is overloaded.


Restrictions of Generic Functions
Generic functions perform the same operation for all the versions of a function except the data
type differs. Let's see a simple example of an overloaded function which cannot be replaced by
the generic function as both the functions have different functionalities.

Example:

#include <iostream>  
using namespace std;  
void fun(double a)  
{  
    cout<<"value of a is : "<<a<<'\n';  
}  
  
void fun(int b)  
{  
    if(b%2==0)  
    {  
        cout<<"Number is even";  
    }  
    else  
    {  
        cout<<"Number is odd";  
    }  
  
}  
  
int main()  
{  
   fun(4.6);  
   fun(6);  
   return 0;  
}  

In the above example, we overload the ordinary functions. We cannot overload the generic
functions as both the functions have different functionalities. First one is displaying the value and
the second one determines whether the number is even or not.

CLASS TEMPLATE
Class Template can also be defined similarly to the Function Template. When a class uses the
concept of Template, then the class is known as generic class.

Syntax
template<class Ttype>  
class class_name  
{  
  .  
  .  
}  

Ttype is a placeholder name which will be determined when the class is instantiated. We can
define more than one generic data type using a comma-separated list. The Ttype can be used
inside the class body.

Now, we create an instance of a class

class_name<type> ob;  

where class_name: It is the name of the class.

type: It is the type of the data that the class is operating on.

ob: It is the name of the object.

Example:

#include <iostream>  
using namespace std;  
template<class T>  
class A   
{  
    public:  
    T num1 = 5;  
    T num2 = 6;  
    void add()  
    {  
        std::cout << "Addition of num1 and num2 : " << num1+num2<<std::endl;  
    }  
      
};  
  
int main()  
{  
    A<int> d;  
    d.add();  
    return 0;  
}  

In the above example, we create a template for class A. Inside the main() method, we create the
instance of class A named as, 'd'.
CLASS TEMPLATE WITH MULTIPLE PARAMETERS
We can use more than one generic data type in a class template, and each generic data type is
separated by the comma.

Syntax
template<class T1, class T2, ......>   
class class_name  
{  
   // Body of the class.  
}  

Example when class template contains two generic data types.

#include <iostream>  
     using namespace std;  
     template<class T1, class T2>  
    class A   
    {  
         T1 a;  
         T2 b;  
         public:  
        A(T1 x,T2 y)  
       {  
           a = x;  
           b = y;  
        }  
           void display()  
          {  
                 std::cout << "Values of a and b are : " << a<<" ,"<<b<<std::endl;  
           }  
      };  
  
      int main()  
     {  
           A<int,float> d(5,6.5);  
           d.display();  
           return 0;  
     }  

You might also like