C++ Material
C++ Material
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.
1. Inheritance
2. Polymorphism
3. Encapsulation
4. Abstraction
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.
No C C++
.
2) Data is less secured in C. In C++, you can use modifiers for class members
to make it inaccessible for outside users.
5) In C, you can't use functions in structure. In C++, you can use functions in structure.
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.
C++ history
History of C++ language is interesting to know. Here we are going to discuss brief history 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.
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.
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.
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();
}
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.
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
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.
<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.
#include <iostream>
using namespace std;
int main( ) {
char ary[] = "Welcome to C++ tutorial";
cout << "Value of ary is: " << ary << endl;
}
#include <iostream>
using namespace std;
int main( ) {
int age;
cout << "Enter your age: ";
cin >> age;
cout << "Your age is: " << age << 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.
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';
A variable name can start with alphabet and underscore only. It can't start with digit.
A variable name must not be any reserved word or keyword e.g. char, float etc.
int a;
int _ab;
int a30;
int 4;
int x y;
int double;
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.
float 4 byte
double 8 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.
A list of 30 Keywords in C++ Language which are not available in C language are given
below.
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:
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:
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
Result
Test2
_sum
power
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.
#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.
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 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.
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.
1. (a+b) - c
2. (x/y) -z
3. 4a2 - 5b +c
4. (a+b) * (x+y)
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.
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.
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.
(x * y) -5
x + int(9.0)
where x and y are the integers.
#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.
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.
&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.
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.
a>b && x>y
a>10 || b==5
#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;
}
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;
}
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
For example,
a+=10;
#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++ 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;
}
#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;
}
#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;
}
#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;
}
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. }
#include <iostream>
using namespace std;
int main () {
for (; ;)
{
cout<<"Infinitive 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++;
}
}
#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++;
}
}
#include <iostream>
using namespace std;
int main () {
while(true)
{
cout<<"Infinitive 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:
#include <iostream>
using namespace std;
int main() {
int i = 1;
do{
cout<<i<<"\n";
i++;
} while (i <= 10) ;
}
do{
//code to be executed
}while(true);
jump-statement;
break;
#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 10; i++)
{
if (i == 5)
{
break;
}
cout<<i<<"\n";
}
}
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";
}
}
}
jump-statement;
continue;
#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";
}
}
}
It can be used to transfer control from deeply nested loop or switch case label.
#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.
#include <iostream>
using namespace std;
int main()
{
int x = 11; // x is a variable
cout<<x<<"\n";
}
#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.
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
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();
}
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().
#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;
}
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.
#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
}
#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.
1. const keyword
2. #define preprocessor
const float PI=3.14;
#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;
}
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
#include <iostream.h>
#define PI 3.14
main() {
cout<<pi;
}
#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.
#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";
}
}
functionname(arrayname); //passing array to function
#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.
#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;
}
#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.
3) It makes you able to access any memory location in the computer's memory.
Usage of pointer
In c language, we can dynamically allocate memory using malloc() and calloc() functions where
pointer is used.
Pointers in c language are widely used in arrays, functions and structures. It reduces the code and
improves the performance.
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;
}
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.
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;
}
#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;
}
#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;
}
#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;
}
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;
}
}
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.
#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;
}
They are mainly useful for event-driven applications, callbacks, and even for storing the functions
in arrays.
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.
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.
#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;
}
#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;
}
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;
Example 2:
1. float *q;
2. q = new 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;
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);
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;
}
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.
Object Oriented Programming is a paradigm that provides many concepts such as inheritance,
data binding, polymorphism etc.
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.
Abstraction
Hiding internal details and showing functionality is known as abstraction. For example: phone
call, we don't know the internal processing.
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.
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 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.
class Student
{
public:
int id; //field or data member
float salary; //field or data member
String name;//field or data member
}
#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;
}
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.
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.
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;
}
class Game {
public:
void play(); // Function declaration
};
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.
o Default constructor
o Parameterized 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;
}
#include <iostream>
class A {
private:
public:
num2 = n2;
}
void display() {
}
};
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 (~).
#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;
}
#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.
It is used to refer the common property of all objects such as rateOfInterest in case of Account,
companyName in case of Employee etc.
#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;
}
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.
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.
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.
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.
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;
}
#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
#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;
}
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.
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.
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.
#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;
}
#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;
}
Trignometric functions
Method Description
Power functions
Method Description
llround(x) It rounds off the value of x and cast to long long integer.
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.
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.
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.
class derived_class_name :: visibility-mode base_class_name
{
// body of the derived class.
}
Where,
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.
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.
Where 'A' is the base class, and 'B' is the derived class.
#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;
}
#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;
}
class D : visibility B-1, visibility B-2,
{
// Body of the class;
}
#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.
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.
}
};
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;
}
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.
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.
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.
#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;
}
o methods,
o constructors, and
o indexed properties
It is because these members have parameters only.
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.
#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.
#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;
}
The advantage of Operators overloading is to perform different operations on the same operand.
operator op is an operator function where op is the operator being overloaded, and the operator
is the keyword.
#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;
}
#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;
}
#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;
}
#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
}
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;
}
1. Abstract class
2. Interface
Abstract class and interface both can have abstract methods which are necessary for abstraction.
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.
In C++, global namespace is the root namespace. The global::std will always refer to the
namespace "std" of C++ Framework.
#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;
}
#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.
#include <iostream>
using namespace std;
int main( ) {
string s1 = "Hello";
char ch[] = { 'C', '+', '+'};
string s2 = string(ch);
cout<<s1<<endl;
cout<<s2<<endl;
}
#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;
}
#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;
}
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char ary[] = "Welcome to C++ Programming";
cout << "Length of String = " << strlen(ary)<<endl;
return 0;
}
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.
Exception Description
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.
#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;
}
#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();
}
}
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.
#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;
}
#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;
}
#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.
istream& getline( istream& is, string& str, char delim );
Where,
s: It is an object of the istream class that defines from where to read the input stream.
Return value
This function returns the input stream object, which is passed as a parameter to the function.
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.
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.
#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:
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.
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.
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.
#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.
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.
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;
}
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.
class_name<type> ob;
type: It is the type of the data that the class is operating on.
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.
}
#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;
}