CPP UNIT-I
CPP UNIT-I
CPP UNIT-I
me/jntuh
UNIT-1
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.
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:
o Object
o Class
o Inheritance
o Polymorphism
o Abstraction
o 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
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
1
www.android.previousquestionpapers.com | www.previousquestionpapers.com | https://telegram.me/jntuh
www.android.universityupdates.in | www.universityupdates.in | https://telegram.me/jntuh
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.
2 Approach In OOPs concept of objects and On other hand in case of POP the main
classes is introduced and hence the program is divided into small parts
program is divided into small based on the functions and is treated as
chunks called objects which are separate program for individual smaller
instances of classes. program.
3 Access In OOPs access modifiers are On other hand no such modifiers are
introduced namely as Private,
2
www.android.previousquestionpapers.com | www.previousquestionpapers.com | https://telegram.me/jntuh
www.android.universityupdates.in | www.universityupdates.in | https://telegram.me/jntuh
4 Security Due to abstraction in OOPs data On other hand POP is less secure as
hiding is possible and hence it is compare to OOPs.
more secure than POP.
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.
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.
3
www.android.previousquestionpapers.com | www.previousquestionpapers.com | https://telegram.me/jntuh
www.android.universityupdates.in | www.universityupdates.in | https://telegram.me/jntuh
C++ Features
C++ is object oriented programming language. It provides a lot of features that are given below.
1. Simple
2. Machine Independent or Portable
3. Mid-level programming language
4. Structured programming language
5. Rich Library
6. Memory Management
7. Fast Speed
8. Pointers
9. Recursion
10. Extensible
11. Object Oriented
12. Compiler based
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.
4
www.android.previousquestionpapers.com | www.previousquestionpapers.com | https://telegram.me/jntuh
www.android.universityupdates.in | www.universityupdates.in | https://telegram.me/jntuh
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.
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.h> 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.
5
www.android.previousquestionpapers.com | www.previousquestionpapers.com | https://telegram.me/jntuh
www.android.universityupdates.in | www.universityupdates.in | https://telegram.me/jntuh
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
#include <iostream.h.h>
int main( ) {
cout << "C++ Tutorial";
cout << " Javatpoint"<<endl;
cout << "End of line"<<endl;
}
Output:
6
www.android.previousquestionpapers.com | www.previousquestionpapers.com | https://telegram.me/jntuh
www.android.universityupdates.in | www.universityupdates.in | https://telegram.me/jntuh
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
7
www.android.previousquestionpapers.com | www.previousquestionpapers.com | https://telegram.me/jntuh
www.android.universityupdates.in | www.universityupdates.in | https://telegram.me/jntuh
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.
type variable_list;
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:
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;
8
www.android.previousquestionpapers.com | www.previousquestionpapers.com | https://telegram.me/jntuh
www.android.universityupdates.in | www.universityupdates.in | https://telegram.me/jntuh
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
1. int data=5+10*10;
The "data" variable will contain 105 because * (multiplicative operator) is evaluated before + (additive
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
10
www.android.previousquestionpapers.com | www.previousquestionpapers.com | https://telegram.me/jntuh
www.android.universityupdates.in | www.universityupdates.in | https://telegram.me/jntuh
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.
if(condition){
//code to be executed
}
C++ If Example
#include <iostream.h>
void main () {
int num = 10;
if (num % 2 == 0)
{
cout<<"It is even number";
}
return 0;
}
Output:
It is even number
11
www.android.previousquestionpapers.com | www.previousquestionpapers.com | https://telegram.me/jntuh
www.android.universityupdates.in | www.universityupdates.in | https://telegram.me/jntuh
if(condition){
//code if condition is true
}else{
//code if condition is false
}
Output:
12
www.android.previousquestionpapers.com | www.previousquestionpapers.com | https://telegram.me/jntuh
www.android.universityupdates.in | www.universityupdates.in | https://telegram.me/jntuh
It is odd number
Output:
Enter a number:11
It is odd number
Output:
Enter a number:12
It is even number
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
}
13
www.android.previousquestionpapers.com | www.previousquestionpapers.com | https://telegram.me/jntuh
www.android.universityupdates.in | www.universityupdates.in | https://telegram.me/jntuh
14
www.android.previousquestionpapers.com | www.previousquestionpapers.com | https://telegram.me/jntuh
www.android.universityupdates.in | www.universityupdates.in | https://telegram.me/jntuh
}
else if (num >= 80 && num < 90)
{
cout<<"A Grade";
}
else if (num >= 90 && num <= 100)
{
cout<<"A+ Grade";
}
}
Output:
Output:
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;
}
15
www.android.previousquestionpapers.com | www.previousquestionpapers.com | https://telegram.me/jntuh
www.android.universityupdates.in | www.universityupdates.in | https://telegram.me/jntuh
Output:
Enter a number:
10
It is 10
Output:
Enter a number:
55
Not 10, 20 or 30
16
www.android.previousquestionpapers.com | www.previousquestionpapers.com | https://telegram.me/jntuh
www.android.universityupdates.in | www.universityupdates.in | https://telegram.me/jntuh
The C++ for loop is same as C/C#. We can initialize variable, check condition and increment/decrement
value.
#include <iostream.h>
void main() {
for(int i=1;i<=10;i++){
cout<<i <<"\n";
}
}
Output:
1
2
3
4
5
6
7
8
9
10
17
www.android.previousquestionpapers.com | www.previousquestionpapers.com | https://telegram.me/jntuh
www.android.universityupdates.in | www.universityupdates.in | https://telegram.me/jntuh
#include <iostream.h>
void main () {
for(int i=1;i<=3;i++){
for(int j=1;j<=3;j++){
cout<<i<<" "<<j<<"\n";
}
}
}
Output:
1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3
while(condition){
//code to be executed
}
18
www.android.previousquestionpapers.com | www.previousquestionpapers.com | https://telegram.me/jntuh
www.android.universityupdates.in | www.universityupdates.in | https://telegram.me/jntuh
#include <iostream.h>
void main() {
int i=1;
while(i<=10)
{
cout<<i <<"\n";
i++;
}
}
Output:
1
2
3
4
5
6
7
8
9
10
The C++ do-while loop is executed at least once because condition is checked after loop body.
do{
//code to be executed
}while(condition);
19
www.android.previousquestionpapers.com | www.previousquestionpapers.com | https://telegram.me/jntuh
www.android.universityupdates.in | www.universityupdates.in | https://telegram.me/jntuh
#include <iostream.h>
void main() {
int i = 1;
do{
cout<<i<<"\n";
i++;
} while (i <= 10) ;
}
Output:
1
2
3
4
5
6
7
8
9
10
jump-statement;
20
www.android.previousquestionpapers.com | www.previousquestionpapers.com | https://telegram.me/jntuh
www.android.universityupdates.in | www.universityupdates.in | https://telegram.me/jntuh
break;
#include <iostream.h>
void main() {
for (int i = 1; i <= 10; i++)
{
if (i == 5)
{
break;
}
cout<<i<<"\n";
}
}
Output:
1
2
3
4
jump-statement;
continue;
#include <iostream.h>
void main()
{
for(int i=1;i<=10;i++){
if(i==5){
continue;
}
cout<<i<<"\n";
}
}
Output:
1
2
3
4
6
7
8
9
10
It can be used to transfer control from deeply nested loop or switch case label.
#include <iostream.h>
void 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!";
}
22
www.android.previousquestionpapers.com | www.previousquestionpapers.com | https://telegram.me/jntuh
www.android.universityupdates.in | www.universityupdates.in | https://telegram.me/jntuh
Output:
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.
23
www.android.previousquestionpapers.com | www.previousquestionpapers.com | https://telegram.me/jntuh
www.android.universityupdates.in | www.universityupdates.in | https://telegram.me/jntuh
#include <iostream>
void 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";
}
}
Output:
10
0
20
0
30
#include <iostream.h>
void main()
{
int arr[5]={10, 0, 20, 0, 30}; //creating and initializing array
//traversing array
for (int i: arr)
{
cout<<i<<"\n";
}
}
Output:
10
20
30
40
50
C++ Pointers
24
www.android.previousquestionpapers.com | www.previousquestionpapers.com | https://telegram.me/jntuh
www.android.universityupdates.in | www.universityupdates.in | https://telegram.me/jntuh
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).
Pointer Example
Let's see the simple example of using pointers printing the address and value.
#include <iostream.h>
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;
}
Output:
Output:
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;
}
Output:
Hello
C++
#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;
}
Output:
#include <iostream>
27
www.android.previousquestionpapers.com | www.previousquestionpapers.com | https://telegram.me/jntuh
www.android.universityupdates.in | www.universityupdates.in | https://telegram.me/jntuh
#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;
}
Output:
#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;
}
Output:
28
www.android.previousquestionpapers.com | www.previousquestionpapers.com | https://telegram.me/jntuh
www.android.universityupdates.in | www.universityupdates.in | https://telegram.me/jntuh
Let's see the simple 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;
}
Output:
Length of String = 26
Function Description
void swap(string& str) It is used to swap the values of two string objects.
string& replace(int pos,int It replaces portion of the string that begins at character
len,string& str) position pos and spans len characters.
string& append(const string& str) It adds new characters at the end of another string object.
int find(string& str,int pos,int n) It is used to find the string specified in the parameter.
int find_first_of(string& str,int It is used to find the first occurrence of the specified
pos,int n) sequence.
int find_first_not_of(string& It is used to search the string for the first character that does
29
www.android.previousquestionpapers.com | www.previousquestionpapers.com | https://telegram.me/jntuh
www.android.universityupdates.in | www.universityupdates.in | https://telegram.me/jntuh
str,int pos,int n ) not match with any of the characters specified in the string.
int find_last_of(string& str,int It is used to search the string for the last character of
pos,int n) specified sequence.
int find_last_not_of(string& str,int It searches for the last character that does not match with the
pos) specified sequence.
void push_back(char ch) It adds a new character ch at the end of the string.
30
www.android.previousquestionpapers.com | www.previousquestionpapers.com | https://telegram.me/jntuh
www.android.universityupdates.in | www.universityupdates.in | https://telegram.me/jntuh
void shrink_to_fit() It reduces the capacity and makes it equal to the size of the
string.
allocator_type get_allocator(); It returns the allocated object associated with the string.
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
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.
31
www.android.previousquestionpapers.com | www.previousquestionpapers.com | https://telegram.me/jntuh
www.android.universityupdates.in | www.universityupdates.in | https://telegram.me/jntuh
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:
#include <iostream.h>
void func() {
static int i=0; //static variable
int j=0; //local variable
i++;
j++;
cout<<"i=" << i<<" and j=" <<j<<endl;
}
void main()
{
func();
func();
32
www.android.previousquestionpapers.com | www.previousquestionpapers.com | https://telegram.me/jntuh
www.android.universityupdates.in | www.universityupdates.in | https://telegram.me/jntuh
func();
}
Output:
i= 1 and j= 1
i= 2 and j= 1
i= 3 and j= 1
Let's understand call by value and call by reference in C++ language one by one.
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().
Let's try to understand the concept of call by value in C++ language by the example given below:
#include <iostream.h>
void change(int data);
int main()
{
int data = 3;
change(data);
cout << "Value of the data is: " << data<< endl;
return 0;
}
33
www.android.previousquestionpapers.com | www.previousquestionpapers.com | https://telegram.me/jntuh
www.android.universityupdates.in | www.universityupdates.in | https://telegram.me/jntuh
Output:
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.
Let's try to understand the concept of call by reference in C++ language by the example given below:
#include<iostream.h>
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;
}
Output:
34
www.android.previousquestionpapers.com | www.previousquestionpapers.com | https://telegram.me/jntuh
www.android.universityupdates.in | www.universityupdates.in | https://telegram.me/jntuh
2 Changes made inside the function is not Changes made inside the function is
reflected on other functions reflected outside the function also
3 Actual and formal arguments will be created Actual and formal arguments will be created
in 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.
recursionfunction(){
recursionfunction(); //calling self function
}
#include<iostream.h>
void main()
{
int factorial(int);
int fact,value;
cout<<"Enter any number: ";
cin>>value;
fact=factorial(value);
cout<<"Factorial of a number is: "<<fact<<endl;
}
int factorial(int n)
{
if(n<0)
return(-1); /*Wrong value*/
if(n==0)
return(1); /*Terminating condition*/
else
{
return(n*factorial(n-1));
35
www.android.previousquestionpapers.com | www.previousquestionpapers.com | https://telegram.me/jntuh
www.android.universityupdates.in | www.universityupdates.in | https://telegram.me/jntuh
}
}
Output:
Lifetime refers to the period during which the variable remains active and visibility refers to the module of
a program in which the variable is accessible.
There are five types of storage classes, which can be used in a C++ program
1. Automatic
2. Register
3. Static
4. External
5. Mutable
36
www.android.previousquestionpapers.com | www.previousquestionpapers.com | https://telegram.me/jntuh
www.android.universityupdates.in | www.universityupdates.in | https://telegram.me/jntuh
auto int y;
float y = 3.45;
The above example defines two variables with a same storage class, auto can only be used within
functions.
It is recommended to use register variable only for quick access such as in counter.
The static variable has the default value 0 which is provided by compiler.
#include <iostream.h>
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();
37
www.android.previousquestionpapers.com | www.previousquestionpapers.com | https://telegram.me/jntuh
www.android.universityupdates.in | www.universityupdates.in | https://telegram.me/jntuh
Output:
i= 1 and j= 1
i= 2 and j= 1
i= 3 and j= 1
inline function: C++ inline function is powerful concept that is commonly used with classes. If a
function is inline, the compiler places a copy of the code of that function at each point where the
function is called at compile time.
Any change to an inline function could require all clients of the function to be recompiled because
compiler would need to replace all the code once again otherwise it will continue with old
functionality.
To inline a function, place the keyword inline before the function name and define the function
before any calls are made to the function. The compiler can ignore the inline qualifier in case defined
function is more than a line.
A function definition in a class definition is an inline function definition, even without the use of
the inline specifier.
Following is an example, which makes use of inline function to return max of two numbers −
Live Demo
#include <iostream.h>
return 0;
}
When the above code is compiled and executed, it produces the following result −
Max (20,10): 20
Max (0,200): 200
Max (100,1010): 1010
Memory management is a process of managing computer memory, assigning the memory space to the
programs to improve the overall system performance.
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
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:
float *q;
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:
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:
*p = 45;
*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:
Examples:
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:
40
www.android.previousquestionpapers.com | www.previousquestionpapers.com | https://telegram.me/jntuh
www.android.universityupdates.in | www.universityupdates.in | https://telegram.me/jntuh
delete p;
delete q;
The dynamically allocated array can also be removed from the memory space by using the following
syntax:
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;
#include <iostream.h>
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;
}
In the above code, we have created an array using the new operator. The above program will take the
user input for the size of an array at the run time. When the program completes all the operations, then it
deletes the object by using the statement delete arr.
Output
41
www.android.previousquestionpapers.com | www.previousquestionpapers.com | https://telegram.me/jntuh
www.android.universityupdates.in | www.universityupdates.in | https://telegram.me/jntuh
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.
o The preprocessor directives are the lines that are included in a program which begins with the #
and it is different from the typical source code.
o They are invoked by the compiler to process the programs before compilation. The preprocessor
directive is placed at the top of the source code in a separate line beginning with the character #
and followed by a directive name.
o The preprocessor directive statement cannot be with semi colon. Some of the examples of
preprocessor directives are #define, #include, #indef, etc.
42
www.android.previousquestionpapers.com | www.previousquestionpapers.com | https://telegram.me/jntuh
www.android.universityupdates.in | www.universityupdates.in | https://telegram.me/jntuh
MACROS
The macros are the piece of code in a program which is given some name and whenever this name occurs
then the compiler replaces the name with the actual code. The #define directive is used to define a
macro.
43
www.android.previousquestionpapers.com | www.previousquestionpapers.com | https://telegram.me/jntuh