UNIT - I Notes
UNIT - I Notes
Course Objectives:
Introduces Object Oriented Programming concepts using the C++ language.
Introduces the principles of data abstraction, inheritance and polymorphism;
Introduces the principles of virtual functions and polymorphism
Introduces handling formatted I/O and unformatted I/O
Introduces exception handling
Course Outcomes:
Able to develop programs with reusability
Develop programs for file handling
Handle exceptions in programming
Develop applications for a range of problems using object-oriented programming techniques
UNIT - I
Object-Oriented Thinking: Different paradigms for problem solving, need for OOP paradigm,
differences between OOP and Procedure oriented programming, Overview of OOP concepts-
Abstraction, Encapsulation, Inheritance and Polymorphism.
C++ Basics: Structure of a C++ program, Data types, Declaration of variables, Expressions,
Operators, Operator Precedence, Evaluation of expressions, Type conversions, Pointers, Arrays,
Pointers and Arrays, Strings, Structures, References. Flow control statement- if, switch, while, for, do,
break, continue, goto statements. Functions - Scope of variables, Parameter passing, Default
arguments, inline functions, Recursive functions, Pointers to functions. Dynamic memory allocation
and de-allocation operators-new and delete, Preprocessor directives.
UNIT - II
C++ Classes and Data Abstraction: Class definition, Class structure, Class objects, Class scope,
this pointer, Friends to a class, Static class members, Constant member functions, Constructors and
Destructors, Dynamic creation and destruction of objects, Data abstraction, ADT and information
hiding.
UNIT - III
Inheritance: Defining a class hierarchy, Different forms of inheritance, Defining the Base and Derived
classes, Access to the base class members, Base and Derived class construction, Destructors, Virtual
base class.
Virtual Functions and Polymorphism: Static and Dynamic binding, virtual functions, Dynamic
binding through virtual functions, Virtual function call mechanism, Pure virtual functions, Abstract
classes, Implications of polymorphic use of classes, Virtual destructors.
UNIT - IV
C++ I/O: I/O using C functions, Stream classes hierarchy, Stream I/O, File streams and String
streams, Overloading operators, Error handling during file operations, Formatted I/O.
UNIT - V
Exception Handling: Benefits of exception handling, Throwing an exception, The try block, Catching
an exception, Exception objects, Exception specifications, Stack unwinding, Rethrowing an exception,
Catching all exceptions.
TEXT BOOKS:
1. The Complete Reference C++, 4th Edition, Herbert Schildt, Tata McGraw Hill.
2. Problem solving with C++: The Object of Programming, 4th Edition, Walter Savitch,
Pearson Education.
REFERENCES:
1. The C++ Programming Language, 3rd Edition, B. Stroutstrup, Pearson Education.
2. OOP in C++, 3rd Edition, T. Gaddis, J. Walters and G. Muganda, Wiley Dream Tech Press.
3. Object Oriented Programming in C++, 3rd Edition, R. Lafore, Galigotia Publications Pvt
Ltd.
UNIT - I
Object-Oriented Thinking:
Different paradigms for problem solving:
Paradigm: A method to solve a problem.
Programming paradigm: It is an approach to solve problem using programming language,
tools & techniques. It can be also a methodology/strategy.
Programming paradigm can be broadly classified into types,
1. Imperative programming paradigm
2. Declarative programming paradigm
Let us go, one by one,
1. Imperative programming paradigm
⮚ It performs step by step task by changing state.
⮚ This paradigm consists of several statements & after execution all, the
result will be stored,
⮚ It is based on Von-Neuman architecture i.e stored program concept(where
data & programs are stored random access memory(RAM)).
Advantages:
- Simple to implement.
- Consists of loops, variables.
Disadvantages:
- Complex problem can not be solved.
- Less efficient & productive
- Parallel programming is not possible
⮚ It ensures data-security.
⮚ We can achieve reusability via inheritance feature & also we can remove
redundancy.
⮚ It is flexible.
⮚ Here their exists, standard modules using which, we can write programs without
starting from scratch.
⮚ The principle of Data-hiding helps the programmer to build secure programs. Data is
hidden can’t be accessed by external functions.
⮚ It is easy to partition the work based on object.
Abstraction:
It refers to the act of representing essential features without including background details.
For example, Car is an abstraction – you don't know internal working of the car but within
car there are subsystems like steering, brake, clutch.
Encapsulation:
The wrapping up of data & functions into a single unit(called class) is known as
encapsulation. The data is not accessible to the outside world, & only those functions those
are wrapped in the class can access it. These functions provide the interface between the
object’s data & the program. The insulation of data from direct access by the program is
called data hiding or information hiding.
Inheritance:
It is the process by which objects of one class acquire the properties of objects of another
class. The principle behind this is that the derived class shares common characteristics with
the class from which it is derived.
The concept of inheritance provides the idea of reusability. This means that we can add
additional features to an existing class without modifying it. This is possible by deriving a new
class from then existing one. The new class will have the combined features of both classes.
The more real appealing power of the inheritance is that it allows the programmer to
reuse a class. Here each sub class defines only those features that are unique it.
Polymorphism:
It is a Greek term, means the ability to take more than one form. An operation may exhibit
different behaviors in different instances. The behavior depends upon the types of a data
used in the operation.
For ex.: consider the operation of addition. For two numbers, the operation will generate
sum. If the operands are strings, then the operation would produce a third string by
concatenation. The process of making an operator to exhibit different behaviors in different
instances is known as operator overloading.
Below figure illustrates that a single function name can be used to handle different number &
different types of arguments. Using a single function name to perform different types of tasks
is known as function overloading.
C++ Basics:
Structure of a C++ program:
#include<iostream>
using namespace std;
int main()
{
int i;
cout<<”This is output”<<”\n”; //This is single line comment.
/* This is multiline
comment*/
//input a number using >>
cout<<”Enter a number”<<endl;
cin>>i;
//now, output using <<
Cout<<i<<” Squared is = ”<<i*i;
return 0;
}
Output:
This is output
Enter a number
2
2 Squared is = 4
⮚ <iostream> supports C++ style I/O operations.
⮚ using namespace std; this line tells the compiler to use the std namespace.
A namespace is the declarative region in which program elements can be placed.
This using statement informs the compiler that you want to use the std namespace.
⮚ cout<<”This is output”<<”\n”; causes, this is output(to be displayed on the screen ).
<<(left shift operator ), but here it is a output operator.
⮚ cout is an identifier linked to the screen, cout refers to screen.
⮚ //This is single line comment. This is a single line comment whatever // follows is
ignored by compiler. For explanation purpose, we can write comments.
⮚ Multiline comments as in C, in C++ also it can be used.
⮚ cout<<”Enter a number”<<endl; Enter a number will be prompted & endl is a keyword
represents end of a line.
⮚ cin>>i; the number is read from keyboard.
⮚ >> right shift operator, when used here, it is an input operator.
⮚ i reads value from keyboard
⮚ cin refers to the standard input device i.e keyboard.
⮚ The ouput will be printed as,
2 Squared is = 4
⮚ The statement,
return 0; the program return 0 to the calling process(Operating system)
returning 0 indicates that the program terminated normally.
Abnormal termination, should be signaled by non-zero value.
Example programs.
1. Write a C++ program to print Hello message.
#include<iostream>
using namespace std;
int main()
{
cout<<”Hello, Wecome to OOPs with C++ programming ”;
return 0;
}
Output:
Hello, Wecome to OOPs with C++ programming
A data type specifies the type of data that a variable can store such as integer, floating,
character etc.
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.
Structures:
⮚ It is a collection of variables under one name.
⮚ Syntax:
struct struct_type_name
{
Type member_name;
Type member_name;
Type member_name;
.
.
.
}structure_variables;
Example:
Struct addr
{
char name[30];
char street[40];
char city[20];
char state[3];
unsigned long int ZIP;
};
⮚ The variables that make up the structure are called members.
Name 30 bytes
street 40 bytes
city 20 bytes
State 3
bytes
ZIP 4 bytes
⮚ addr a_info,b_info,c_info;
can also be declared.
⮚ Accessing structure variables,
addr_info.ZIP=12345;
i.e. structure_name.member_name;
⮚ Structure assignments,
#include<iostream>
using namespace std;
int main()
{
struct xyz
{
int a;
int b;
}x,y;
x.a=10;
x.b=15;
y=x;
cout<<y.a<<y.b;
return 0;
}
Output:
10 15
Declaration of variables:
Variables can be declared in two ways.
i. Local variables
ii. Global variables
Let us see one by one,
i. Local variables: the variable which are local to particular block are
called local variables.
ii. Global variables: The life span of these variables will be until the
program goes of scope.
Example:
#include<iostream>
using namespace std;
int a;//Global variable
int addition(int x,int y);
int main()
{
int b,result;//local variable declaration
cout<<”Enter a & b”;
cin>>a>>b;
result=addition(a,b);
cout<<”sum=”<<result;
return 0;
}
int addition(int x,int y)
{
int sum; //local variable declaration
sum=x+y;
return sum;
}
Type conversions:
⮚ When variables of one type is mixed with another type, a type conversion will occur.
⮚ The value of the right side(expression side) of the assignment is converted to the
type of the left side(target variables).
⮚ Examples:
#include<iostream>
using namespace std;
int main()
{
int x;
char ch;’
float f;
ch=x; // lower order 8 bit will remain same, & higher 8 order will be loss.
x=f;//Non-fractional part will be remained & fractional part will be loss.
f=ch;// converts into float format
f=x;// // converts into float format
return 0;
}
Operator:
There are 4 main classes of operators,
i. Arithmetic operator
ii. Relational operator
iii. Logical operator
iv. Bitwise operator
Let us see one by one,
i. Arithmetic operator:
Operator Action
- Subtraction, unary minus
+ Addition
* Multiplication
/ Division
% Modulus
-- Decrement
++ Increment
Example:
//program to demonstrate arithmetic operators.
#include<iostream>
using namespace std;
int main()
{
int x,y;
x=5;
y=2;
cout<<”x+y=”<<x+y<<”\n”;
cout<<”x-y=”<<x-y<<”\n”;
cout<<”x*y=”<<x*y<<”\n”;
cout<<”x/y=”<<x/y<<”\n”;
cout<<”x%y=”<<x%y<<”\n”;
return 0;
}
Output:’
x+y=7
x-y=3
x*y=10
x/y=2
x%y=1
//program to demonstrate increment & decrement operators.
#include<iostream>
using namespace std;
int main()
{
int x=10;
int z=10, w,y;
y=++x; // sets y=11,x=11
w=z++;//sets w=10, z=11
cout<<”y=”<<y<<”w=”<<w;
return 0;
}
Output:
y=11 w=10
#include<iostream>
using namespace std;
int main()
{
int x=10;
int z=10, w,y;
y=--x; // sets y=9,x=9
w=z--;//sets w=10, z=9
cout<<”y=”<<y<<”w=”<<w;
return 0;
}
Output:
y=9 w=10
Example,
1. !0 && 0 II 0
1 && 0 II 0
0II0
0
2. !(0 && 0) II 0
!0 II 0
1II0
1
Operator Action
& AND
I OR
^ XOR
~ NOT
>> SHIFT RIGHT
<< SHIFT LEFT
1. AND
char ch=’A’;
char result=ch & 127;
10000011 <-result
3. XOR
⮚ A bit set off the bits being compared are different.
01111111<-127 in binary
^01111000<-120 in binary
00000111<-result
⮚ Bitwise operations may produce value other than ‘0’ or ‘1’.
ex:
x=7 00000111 7
x=x<<1 00001110 14
y=12 00001100 12
y=y>>1 00000110 6
It is similar to,
x=10
if(x>9)
x=100;
else
x=200;
v. The ‘&’ and ‘*’ pointer operator.
‘&’ operator:
⮚ It is a unary operator i.e it operates on single operand.
⮚ Ex: m=&count;
&->address of
‘*’ operator:
⮚ It is complement of ‘&’.
Ex: double f;
cout<<sizeof f;
cout<<sizeof (int);
output:
84
vii. the comma operator:
⮚ the comma operator combines together several expressions.
Highest ( ), [ ], ->, .
!,~,++,--,*, &,sizeof
*,/,%
+,-
<<,>>
<,<=,>,>=
==,!=
&
^
I
&&
II
Highest ?:
Lowest =,+=,-=,*=,/=
Expressions:
i. Constant expressions
ii. Integral expressions
iii. Float expressions
iv. Pointer expressions
v. Relational expressions
vi. Logical expressions
vii. Bitwise expressions
Let us see one by one,
i. Constant expressions:
Expression consists of constants.
EX:
15
20+15/2.0
‘x’
ii. Integral expressions
These expression produce integer values,
Ex:
m
m*n-5
m*’x’
5+int(2.0) // here m & n are integers
iii. Float expressions
It produces floating point results.
Ex:
x+y
x*y/10 //here, x y are floating point variables
5+float(10)
10.75
iv. Pointer expressions:
These expressions produces address values.
&m //m is a variable
ptr
ptr+1 //ptr is a pointer
v. Relational expressions:
These expressions yields the result either true or false.’
Ex:
x<=y
a+b==c+d
m+n>100
vi. Logical expressions:
It combines two to more relational expressions & produce bool type results.
Ex:
a>b && x==10
x==10 II y==5
vii. Bitwise expressions:
⮚ These are used to manipulate data at bit level.
Pointer variable:
- Syntax:
- type *name;
Pointer operator: (‘*’ and ‘&’)
int *m;
int count,q;
m=&count; // ‘m’ points to count
q=*m;
Pointer assignments:
#include<iostream>
using namespace std;
int main()
{
int x;
int *p1,*p2;
p1=&x;
p2=p1;
cout<<p2;
return 0;
}
Output:
Prints address of x
Pointer Arithmetic:
int *p1;
p1++;
p1--;
p1=p1+12;
Operations on pointers:
- Pointers can be incremented, decremented and also two pointers
can be subtracted.
- You may add or subtract integers to or from pointers.
- Pointers can not be multiplied, divide pointers.
- We cant add two pointers.
- Pointers can be compared.
Pointers & Arrays:
- There is close relationship between pointers & arrays.
- Ex.:
char str[80], *p1;
p1=str;//p1 has been set to the address of the first array element in
//str
//to access the fifth element,
// using array
str[4]
//using pointer
*(p1+4)
- In C++, there are two methods of accessing array elements.
i. Pointers arithmetic
ii. Array indexing
- Two versions of putstr()
/*Index ‘s’ as an array */
void putstr(char *s)
{
int t;
for(t=0;s[t];++t)
putchar(s[t]);
}
/*Access s as a pointer*/
void putstr(char *str)
{
while(*s)
putchar(*s++);
}
Arrays of Pointers:
- Pointers may be arrayed like any other data type, the declaration
for an int pointer array of size 10 is,
int *x[10];
//To assign variable to third element of the point array
x[2]=&var;
//To find the value of var,
*x[2]
- if you want to pass an array of pointers into to a function.
void display_array(int *q[])
{
int t;
for(t=0;t<10;++t)
cout<<*q[t];
}
References:
- It is a feature related to the pointer.
- A reference variable can be created with ‘&’ operator.
- It is a reference for existing variable.
Ex.:
string food=”pizza”; //food variable
string &meal=food; //reference to food
cout<<food<<”\n”;
cout<<meal<<”\n”;
- Call by reference can be achieved by two ways
i. You can explicitly pass a pointer to the argument.
ii. You can use a reference parameter.
i. #include<iostream>
using namespace std;
void neg(int *i);
int main()
{
int x;
x=10;
cout<<x<<”negted is”;
neg(&x);
cout<<x<<”\n”;
return 0;
}
void neg(int *i)
{
*i=-*i;
}
ii. Use a reference parameter
#include<iostream>
using namespace std;
void neg(int &i); // ‘i’ now a reference
int main()
{
int x;
x=10;
cout<<x<<”negated is”;
neg(x); //no longer need the ‘&’ operator.
cout<<x<<”\n”;
return 0;
}
void neg(int &i)
{
i=-i; // ‘i’ is now a reference.
}
C++ strings:
- Most common use of the one dimensional array is as a character
string.
- C++ supports two types of strings
i. Null terminated strings
ii. Also defines a string class.
- i. The first is the null terminated string contains the character
array.(A null is zero)
- Thus a null terminated string contains the character that comprise
the string followed by a null.(C string)
- ii. C++ also defines a string class called, string, which provides an
object-oriented approach to string handling.
- When declaring a character array that will hold a null-terminated
string, you need to declare it to be one character longer than the
largest string that it is to hold.
- For ex. To declare an array str that can hold a 10 character string,
you would write
char str[11]; //this makes room for the null at the end of string
- When you use a quoted string constant in your program, you are
also creating a null terminated string.
- A string constant is a list of characters enclosed in double quotes.
- For ex.
“hello there”
You do not need to add the null to the end of string constants
manually – the compiler does this for automatically.
C++ supports a wide range of functions that manipulate
null-terminated strings.
The most common are,
Name Function
strcpy(s1,s2) Copies s2 into s1
strcat(s1,s2) Concatenates s2 onto the end of s1
strlen(s1) Returns the length of s1
strcmp(s1,s2) Returns 0 if s1 & s2 are same; less than
0 if s1<s2; greater than 0 if s1>s2.
strchr(s1,ch) Returns a pointer to the first occurrence
of ch in s1.
strstr(s1,s2) Returns a pointer to the first occurrence
of s2 in s1.
- These functions use the header file string.h also <cstring>.
- The following program illustrates the use of these string functions,
#include<iostream>
#include<string>
int main()
{
char s1[80],s2[80];
gets(s1);
gets(s2);
cout<<”Length of s1 & s2 is=”<<strlen(s1)<<strlen(s2);
if(!strcmp(s1,s2))
cout<<”The strings are equal”<<endl;
strcat(s1,s2);
cout<<s1<<endl;
strcpy(s1,”This is a test”);
cout<<s1<<endl;
if(strchr(“hello”,’e’))
cout<<”e is in hello \n”;
if(strstr(“hi there”,”hi”))
cout<<”found hi”<<endl;
return 0;
}
If you run this program & enter the strings “hello” & “hello”, the
output is,
output:
Type your first name: John
Your name is : John
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.
if(condition){
//code to be executed
}
C++ If Example
#include <iostream>
using namespace std;
int main () {
int num = 10;
if (num % 2 == 0)
{
cout<<"It is even number";
}
return 0;
}
Output:
It is even number
if(condition){
//code if condition is true
}else{
//code if condition is false
}
if(condition1){
//code to be executed if condition1 is true
}else if(condition2){
//code to be executed if condition2 is true
}
else if(condition3){
//code to be executed if condition3 is true
}
...
else{
//code to be executed if all the conditions are false
}
C++ 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 value.
while(condition){
//code to be executed
}
#include <iostream>
using namespace std;
int main() {
int i=1;
while(i<=10)
{
cout<<i <<"\t";
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);
#include <iostream>
using namespace std;
int main() {
int i = 1;
do{
cout<<i<<"\t";
i++;
} while (i <= 10) ;
}
Output:
1 2 3 4 5 6 7 8 9 10
C++ Break Statement
The C++ break is used to break loop or switch statement. It breaks the current flow of the
program at the given condition. In case of inner loop, it breaks only inner loop.
jump-statement;
break;
#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 10; i++)
{
if (i == 5)
{
break;
}
cout<<i<<"\n";
}
}
Output:
1
2
3
4
jump-statement;
continue;
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!";
}
}
Output:
You are not eligible to vote!
Enter your age:
16
You are not eligible to vote!
Enter your age:
7
You are not eligible to vote!
Enter your age:
22
You are eligible to vote!
Functions :
- It is a set of instructions which performs desired, specific
task.
Scope of variables:
-Scope refers to the to the visibility of variables.
-In other words, which part of your program can see or use
it.
i. Local variables
ii. Global variables,
// CPP program to illustrate scope of local & global variables.
#include<iostream>
using namespace std;
int global=5;
int main()
{
int global=2;
cout<<global<<endl;
return 0;
}
Output:
2
Ex. 2:
#include<iostream>
using namespace std;
// Global x
int x=0;
int main()
{
//local x
int x=10;
cout<<”value of global x is :”<<::x;
cout<<”value of local x is :”<<x;
return 0;
}
Output:
Value of global x is : 0
Value of local x is : 10
Parameter passing:
#include<iostream>
using namespace std;
void swap(int a,int b);
int main()
{
int x,y;
cout<<”Enter x, y”;
cin>>x>>y;
swap(x,y); //passing parameter x,y
return 0;
}
Inline functions:
- In C++, we can create short functions, that are not actually called,
rather their code is expanded in line at the point of each
invocation.
- It is like macro.
- The function should precede its definition with the inline keyword.
It causes a function to be expanded in line rather than called.
#include<iostream>
using namespace std;
inline int max(int a,int b)
{
return a>b?a:b;
}
int main()
{
cout<<max(10,20);
cout<<” ”<<max(99,88);
return 0;
}
- inline function allow you create very efficient code.
- When function is called, a significant overhead is generated by the
calling & return mechanism.
- Arguments are pushed to the stack & registers are saved when the
function is called & restored when the function returns.
- The problem is that these instruction takes time.
- When function is expanded, no such operation occur.
- It produce faster run times.
- It is best to inline only very small function.
- It is also good idea to inline only those functions that will have
significant impact on the performance of your program.
Recursive Functions:
- A function can call itself.
- A function is said to be recursive, if a statement in the body of the
function calls itself.
- Recursion is the process of defining something in terms of itself.
Ex:
int fact(int n)
{
int answer;
if(n==1)
return 1;
answer=fact(n-1)*n;
return(answer);
}
Ex:
fact(5)
fact(4)*5
fact(3)*4*5
fact(2)*3*4*5
fact(1)*2*3*4*5
1*2*3*4*5=120
Pointers to Functions
- Even though a function is not a variable, it still has a physical location in memory that
can be assigned to a pointer.
- This address is the entry point of the function & it is the address used when the
function is called.
- Once a pointer points to a function, the function can be called through that pointer.
- Function pointer also allow functions to be passed as arguments to other functions.
- We can obtain the address of a function name without any parentheses or
arguments.(similar to the way an array’s address is obtained when only the array
name, without index is used)
Ex:1)
#include<iostream>
using namespace std;
int Add(int a,int b)
{
return a+b;
}
int main()
{
int c;
int (*p)(int,int); //pointers to functions
//pointers to function that should take (int,int) as argument or parameter
//returns int
p=&Add;
c=(*p)(2,3); //de-referencing & executing the function
cout<<c;
return 0;
}
Output:
5
In above example,
Instead of writing,
p=&Add;
we can also write,
p=Add; //Function name will return pointers
Also, instead of writing, c=(*p)(2,3);
We can also wirte, c=p(2,3); //de-referencing, executing the function.
Output,
5
Ex:2)
#include<iostream>
using namespace std;
void PrintHello()
{
Cout<<”Hello \n”;
}
void PrintHello(char *name)
{
cout<<”Hello”<<name;
}
int main()
{
void (*p)();
p=PrintHello; // p points to PrintHello function
p();
void (*ptr)(char *);
ptr=PrintHello;
ptr(“Tom”);
return 0;
}
Output:
Hello
Hello Tom
Dynamic memory allocation & de-allocation operator using new & delete:
- C++ provides two dynamic allocation operator: new & delete.
- These operator are used to allocate & free memory at run time.
- Dynamic allocations is an important part of almost all real-world
programs.
- C++ also supports dynamic memory allocation functions called,
malloc() & free().
- The new operator allocates memory & returns a pointer to the start
of it.
- The delete operator frees memory previously allocated using new.
- The general form of new & delete are,
p_var=new type;
delete p_var;
here, p_var is a pointer variable that receives a pointer to memory
that is large enough to hold an item of type.
- On new operator failure, it returns null.
//here is a program that allocates memory to hold an integer.
#include<iostream>
using namespace std;
int main()
{
int *p;
p=new int;
*p=100;
cout<<”At”<<p<<””;
cout<<”is the value”<<*p<<endl;
delete p;
return 0;
}
- This program assigns to p and address in the heap that is large
enough to hold an integer.
- It then assigns that memory the value 100 & displays the content
of the memory on the screen.
- Finally, it frees the dynamically allocated memory by delete
operator.
- New & delete perform functions similar to malloc() & free(), but
they have several advantages.
i. new allocates memory automatically of specified type. We
need not use sizeof operator because, the size is
computed automatically.
ii. new automatically returns a pointer of the specified
type.(you need not use explicit type cast as you when
allocating memory by using malloc()).
Initializing Allocated Memory:
- you can initialize allocated memory to some known value by
putting an initializer after the type name in the new statement.
- Here, is the general form of new when an initialization is included,
p_var=new var_type(initializer);
//this program gives the allocated integer an initial value of 87.
#include<iostream>
using namespace std;
int main()
{
int *p;
p=new int(87);
cout<<”At”<<p<<” ”;
cout<<”is the value”<<*p<<”\n”;
delete p;
return 0;
}
Allocating Arrays:
- We can allocate memory for arrays using new operator,
p_var=new array_type[size];
here, size specifies the number of elements in the array.
- To free an array, use this form of delete.
delete [] p_var;
here, the [] informs delete that an array is being released.
// The below program allocates 10 element integer array.
#include<iostream>
using namespace std;
int main()
{
int *p,i;
p=new int[10]; //allocates 10 integer array.
for(i=0;i<10;i++)
p[i]=i;
for(i=0;i<10;i++)
cout<<p[i]<<” ”;
delete [] p; //releases the array
return 0;
Pre-processor Directives:
- Pre-processor directives instructions to compiler. Preprocessor are
programs that process our source code before compiles.
- The pre-processor contains the following diterctives.
#define #elif #else #endif
#error #if #ifdef #ifndef
#include #line #pragma #undef
- All pre-processor begins with ‘#’ symbol.
Let us one by one,
i. #define
The general form of the directive is,
Ex.1 #define LEFT 1
#define RIGHT 0
cout<<RIGHT<<LEFT+1;
output:
02
Ex.2 #define ONE 1
#define TWO ONE+ONE
#define THREE ONE+TWO
Output:
cout<<ONE<<TWO<<THREE;
output:
123
Ex.3 #define E_MS “Standard error on input \n”
cout<<E_MS;
Output:
Standard error on input
Ex.4 #define MAX_SIZE 10
float balance[MAX_SIZE];
for(i=0;i<MAX_SIZE;i++)
cout<<balance[i];
for(i=0;i<MAX_SIZE;i++)
x+=balance[i];
ii. #error
- The #error directive forces the compiler to stop compilation.
- It is used for primarily for debugging.
- The general form of the #error directive is
#error error_message
- When the #error directive is encountered, the error message is
displayed. Along with the other information defined by compiler.
iii. #include
- The #include directive instructs the compiler to read another
source file in addition to the that contains the #include directive.
For ex.:
#include<iostream>
- Include files can have #include directives in them. This is referred
to as nested includes.
- Standard C++ recommends that the at least 256 levels of nesting
be supported.
- In addition to files, a C++ program can use the #include directive
to include directive a C++ header.
- C++ defines a set of standard header that provide the information
necessary to the various libraries.
- A header is simply an abstraction that guarantees that the
appropriate information required by your program is included.
v. #undef
- The #undef directive removes a previously defined definition of
the macro name that follow it.
- The general form for #undef is
#undef macro_name
For ex.:
#define LEN 100
#define WIDTH 100
char array[LEN][WIDTH];
#undef LEN
#undef WIDTH
/* At this point both LEN & WIDTH are undefined*/