Professional Documents
Culture Documents
PGDIT
Object Oriented Programming
Semester 2nd
Session - 1
Welcome
to
Object Oriented
Programming
Session Outline
Genesis of C++
Structured vs. Object Oriented Programming
Basics Concepts of Object Oriented Programming
Structure of C++ program
C++ Comments
A simple C++ program with explanation
Using streams for input and output (cin , cout)
Placement of variable declarations
The const qualifier
Executing a C++ program
A Class in C++
Synonyms
Practice Questions & answers
GENESIS OF C++
Factors that contributed to the evolution
Increasing complexity of the problem domain.
Difficulty in capturing the complexity of the problem domain
through procedural languages(like C, Fortran, Pascal)
Difficulty in modeling real-world objects through procedural
languages.
GENESIS OF C++
Growing demands on software in terms of
Correctness
Maintainability
Reusability
Scalability
Openness and interoperability
Integrity
GENESIS OF C++
Commercial viability
A huge investment in C lead to the incorporation of object
oriented features with C leading to
C++ is a superset to C and C++ = C +OOPs.
C++ provides object-oriented programming (OOP).
OOPs was invented to overcome the drawbacks of the
pop(Procedure-Oriented Programming).
Structured
Vs
Object-oriented
Development
Structured Programming
In the structured approach, the problem is
viewed as a sequence of things to be done,
such as reading, calculating and printing.
A number of functions are written to
accomplish these tasks.
The primary focus is on functions.
A typical program structure for procedural
programming is shown in the next slide.
Function - 1
Function - 2
Function - 4
Function - 3
Function - 5
Function - 6
Global Data
Function - 1
Function - 1
Function - 1
Local Data
Local Data
Local Data
Data
Functions
Functions
Object A
Object B
Functions
Data
Object C
Library
Management
System
Comparison
b/w OOAD &
SSAD
Object-Oriented A/D
Structured A/D
Decompose by
objects or concepts
Decompose by
functions or processes
Book
Catalog
System
Library
Librarian
Record
Issues
Add To
Stock
Report
Fines
OOP
Emphasis is on procedure.
1.
2.
3.
4.
5.
6.
7.
Objects
Classes
Encapsulation
Abstraction
Inheritance
Polymorphism
DynamicBinding&
MessagePassing
1
2
7
5
Objects
Objects are often used to model real world entities
that we normally find in everyday life.
An object can be a person , place , thing ,concept or
anything we see in the real world . Some common
examples of an object include car ,book, computer ,
apple etc.
The principal building blocks of object-oriented
programming.
Each object is a programming unit consisting of data
(variables) and functionality (methods).
OBJECT:STUDENT
Data
A. Name
B. Date Of Birth
C. Marks
....................
A
2
B
Functions
1. Total
2. Average
3. Display
................
Objectscontaindata(likeName,DOB,Marks)andfunctions
(likeTotal,averageanddisplay)tomanipulatethatdata.
Objects
Each object possess the following characteristics.
Each object has an identity and are distinguishable.
Data and functions are binded together to form an
object.
Objects in the system communicate with each other
using the concept of message passing.
Objects store data which is manipulated by its
functions.
Since all software applications serve people living in the
real world, then that software should mirror the real world
as closely as possible, both in its workings and in its
appearance :: thats the reason to use objects
Class
A class is a general specification or description for a
set of objects that defines their common structure
(data), behaviour (methods), and relationships
(inheritance).
A class is a prototype that defines the variables and
methods common to all objects of a certain kind.
Once a class has been defined, we can create any
number of objects belonging to that class.
If fruit has been defined as a class, then the
statement fruit mango; will create an object mango
belonging to the class fruit.
Class
Encapsulation
Encapsulation
Encapsulation
Book Id
Book author
Book title
Issue()
Book_status
Book_description
Library Class
Roll no
Name
Class
Input()
Show()
Student Class
ADVANTAGES OF ENCAPSULATION
Abstraction
Abstraction Simplicity is good; complexity is bad.
Abstraction is a process that involves identifying the essential
features without including the internal details.
A good abstraction is the one that emphasizes details that are significant
and suppresses details that are not.
Let us take a real world example ::
Consider an example of a Television which consists of features such as
changing the channel ,ON/OFF switch etc. User interacts with television
using interfaces like channel changer, volume controller, and power button
without going in to internal details of the working of each of the interface.
The user is not concerned about how it receives signals over the air.
,translate them and display on the screen. So,it shows how the internal
complexity of working of the television is hidden from the user.
Abstraction
Abstraction
In object oriented programming , classes uses the concept of Abstraction.
A class encapsulates the relevant data and functions that operate on data
by hiding the complex implementation details from the user . In other
words ,user needs to focus on what a class does rather than how it will be
implemented.
The following diagram shows that the basic concept of Abstraction.
Inheritance
Inheritance is the process by which objects of one class
acquire properties of objects of another class.
Types of class in inheritance.
1. Base class.
2. Derived class.
Grand Father
Father
// Base class
// Derived class
Inheritance
Inheritance is the process by which one
object acquires the properties of one or more
other object. It supports the concept of
hierarchical classification (top-down).
An object need to define only those qualities
that make it unique within its class.
It implements "is-a" relationships between
objects.
Inheritance creates a hierarchy of related
classes (types) which share code and
interface.
INHERITANCE EXAMPLES
Base Class
Derived Class
Employee
Manager
Researcher
Worker
Account
Checking Account
Saving Account
Generalization/Specialization
Generalization/Specialization represents the is
a relationship set, an essential element of the
object oriented paradigm. The main idea in
Generalization/ Specialization is that one
object class (the specialization) is a subset of
another (the generalization).
A generalization-specialization (gen-spec)
relationship states that one object is a kind-of
(or is-a) the other, and that the other is a
generalization of the object
Specialization
Specialization is either:
the process of defining a new object based on a
(typically) more narrow definition of an existing
object, or
an object that is directly related to, and more
narrowly defined than, another object.
A specialization relation requires that every
instance of the subtype be an instance of the
supertype.
It is common to say that everything that is true for a
generalization is also true for its corresponding
specialization.
POLYMORPHISM
The word Polymorphism is derived from two Greek
words Poly means many and morphs means forms.
So , polymorphism means the ability to take many
forms.
Polymorphism means one name, multiple forms. It
allows us to have more than one function with the
same name in a program .
It also allows overloading of operators so that an
operation can exhibit different behaviors in different
instances.
Basics of OOP
Polymorphism Example
Ex:-addition(+)
For two numbers ,the operation will generate a sum.
For two strings , then the operation would produce a
third string by concatenation.
Basics of OOP
Dynamic Binding
MESSAGE PASSING
In Object oriented programming (OOP) different objects
communicate with each other using the concept of Message
Passing. From the programmer point of view ,message passing
provides an easy way of modeling real world problems on the
computer. Objects communicate with each other in the same way as
human beings exchange messages among themselves.
A message comprises of the name of the object , name of the
function and any information (arguments) to be sent to the object.
For example :If a user wants to check the balance of his account ,
he simply sends the message getbalance to the object account by
passing the information account_no. as shown below
account. getbalance (account_no)
account:: Object
Getbalance:: Message
account_no :: Argument or Onformation
Main Program Section:: from here the execution of program actually starts.
Eg:: int main()
{ // Executable Part
}
SubProgram Section :: includes user defined functions.
C++ Comments
C++ supports the C comment format where /* begins a
comment and */ ends it.
The // also starts a comment in C++ (unless it is inside a
string). Everything to the end of the current line is a
comment.
e.g.,
/* This is a comment */
//
//
This is invalid
in the next line
/*
This is valid in
the next line */
C++ Comments
Good practice: C++ style of comment is recommended as can
be seen in the following example.
C++ style
if(a>b)
{ //int temp=a;
//swap a, b
//a=b;
//b=temp;
}
C style
if(a>b)
{ /*
int temp=a; /*swap a,b*/
a=b;
b=temp; */
}
Streams
47
use cin
eg cin >> num_in;
48
49
main()
{
cout << Enter a number ;
int num;
// declaration of variable within block
cin >> num;
cout << Number = << num;
}
Bytes
Range
Char
-128 to 127
Unsigned char
0 to 255
Signed char
-128 to 127
Int
-32768 to 32767
Unsigned int
0 to 65532
signed int
-31768 to 32767
Short int
-31768 to 32767
0 to 65535
-32768 to 32767
Long int
-2147483648 to
2147483647
-2147483648 to
2147483647
0 to 4294967295
Float
3.4E-38 to 3.4E+38
Double
1.7E-308 to
1.7E+308
Long double
10
3.4E-4932 to
1.1E+4932
BOOL
It takes only two values: true or false
true=1;
false=0;
eg: #include<iostream.h>
#include<conio.h>
void main()
{
bool b=32;
bool i=false;
cout<<b<<i;
int j=b+b;
bool k=b+b;
cout<<j<<k;
getch();
}
output
10
2 true
output
A Class in C++
Class is a user define data type.
Class is a collection of objects of similar type.
Class Declarations.
class name
{
Data types;
Member functions
};
What is a class ?
A class is
An abstract datatype similar to a C structure.
A representation of objects and the sets of operations that can
be applied to such objects.
Definition of a class
e.g.,
Class A
{
int i ;
char *strng;
Void f (int , char *);
int g() ;
};
Data
Functions
Public area
Entry
allowed
Data
Functions
Synonyms
Operations - "method selectors," "method
interfaces," "messages," or "methods",
services,member function, Instance Method
Object - instance, class instance, surrogate,
entity.
Class - type
Base Class - Super Class, Parent Class.
Derived Class - subtype, subclass, Child
class.
Practice Questions 1
Q1 Identify the drawback of using
procedure-oriented programming, if any:
a) Data is hidden from external functions
b) New functions can be added whenever
necessary
c) Does not reflect real world problems
d) All of the above
Practice Questions 2
Q2 Which one of the following OOP
concepts enables reusability of
components?
a) Inheritance
b) Encapsulation
c) Polymorphism
d) All of the above
Practice Questions 3
Q3 The concept of hierarchical
classification is related to:
a) Abstraction
b) Inheritance
c) Function overloading
d) None
Practice Questions 4
Q4 Comments in C++ starts with
_______ symbol.
a) //
b) \\
c) **
d) None of the above
Practice Questions 5
Q5 return is an example of a
a) Keyword
b) Function
c) Statement
d) Comment
Practice Questions 6
Q6 The declaration of global variables
must be made
a)inside the function
b) outside the function
c) in a function header line
d) None of the above
Practice Questions 7
Q7 Consider the following code:
cout<< Welcome;
This is an example of
a) Return type
b) Function
c) Both a and c
d) C++ statement
Answers
Q1 c
Q2 a
Q3 b
Q4 a
Q5 a
Q6 b
Q7 d
Thank You
Please forward your query
To :bminocha@amity.edu
Cc: manoj.amity@panafnet.com
Session Outline
Tokens
Expression
Decision Control Structures
Loop Control Structures
Practice Questions & answers
C++ TOKENS
Tokens are the smallest individual units in a
program.
Tokens are the various C++ program elements
which are identified by the compiler.
Various C++ Tokens are as:
Keywords
Identifiers
Constants
Operators
Special characters (#,?)
KEYWORDS
IDENTIFIERS
Identifiers refers to the names of variables, functions,
arrays, class etc created by the programmer.
Rules for writing identifiers:
Only alphabetic characters, digits and underscores are
permitted.
The name cannot start with a digit.
Uppercase and lowercase letters are distinct(C++ is a
case sensitive). Like RESULT variable is not the same
as the result variable or the Result variable. These are
three different variable identifiers.
A declared keyword cant be used as a variable name.
VARIABLES
Declaration of variables
The integer data types short, long and int can be
either signed or unsigned based on the range of
numbers needed
Signed types can represent both +ve and ve
values,
unsigned types can only represent +ve values (and
zero)
unsigned short int num; // only +ve values
signed int balance; // +ve & -ve values
CONSTANTS
Constants refers to the fixed values that do not change
during the execution of a program.
QUALIFIERS
Qualifiers are the additional attributes to the data
type.
Eg. 12345L // long integer constant
7865435UL // unsigned long integer
Expressions
An expression is a combination of constants , variables
and operators to form an executable statement which
computes a value.
The resultant value must be of valid data type that can
be assigned to a variable.
For example :
sum=a+b;
In the given statement ,the expression a+b consists of
an operator + and operands a and b. The result of this
expression will be assigned to variable sum.
C++ Expression
(ab)/(c+d)
( a b ) / (c + d )
4 x2 + 3x + 5
4 *x*x +3*x +5
(sin2x cos2x)1/3
X2 + y2
2 cos x
(x * x + y * y) / (2 * cos (x))
Operators
An operator is a special symbol that specifies what
Operators
C++
provides
a
rich
set
of
operators.
Some of C++ operators are inherited from C language while
many other new operators are introduced in to it.
Operators Inherited from C
Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operators
Assignment Operators
Conditional Operators
Unary Operators
Type cast operator
Operators in C++
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Bitwise Operators
5. Increment/Decrement
Operator
6. Assignment Operators
7. Conditional Operators
8. Comma Operator
9. Sizeof Operator
10 Scope Resolution
Operator
11 Type cast operator
3
7
4
5
Arithmetic Operators
The Arithmetic operators are used for mathematical calculations
The arithmetic operators are binary operators that work on any builtin types.
The following data shows 5 arithmetic operators with their meanings.
Operator
Meaning
Addition
Subtraction
Multiplication
Division
Modulus division
Arithmetic Operators:
The operands acted on by arithmetic operators must represent
numeric values. Thus the operands can be integer quantities, floating
point quantities or characters. The Arithmetic operators when used
with characters ,operate on ASCII values of the characters.
If a=7 and b=3
(Integer)
a+b
10
12.50000
a-b
8.500000
a*b
21
21.00000
a/b
5.250000
a%b
Not applicable as
per condition
Integer Division
Integer division produces an integer result
Truncates the result
Examples
3 / 2 evaluates to 1
4 / 6 evaluates to 0
10 / 3 evaluates to 3
MOD :: Produces the remainder of the division
Examples
5 % 2 evaluates to 1
12 % 4 evaluates to 0
4 % 5 evaluates to 4
Sample program
#include<iostream.h>
int main()
{
int months,days;
cout << enter the days ;
cin >> days;
months = days/30;
days = days%30;
cout << months=<<months;
cout << days= <<days;
return 0;
}
Output:
Enter the days 365
months = 12, days = 5
Operator Precedence
Example
20 - 4 / 5
(4
((4
((4
((4
(20 -((4
(20 -((4
Answer 17
* 2
/
/
/
/
/
/
5)
5)
5)
5)
5)
5)
*
*
*
*
*
3 * 5
2)
2)
(3 * 5)
2)
((3 * 5) % 4)
2))
((3 * 5) % 4)
2)) + ((3 * 5) % 4)
% 4
Relational Operators
We often compare two quantities and depending on their relation
take certain decision.
Comparing the age of two person, price of two items.
Relational operators are used to check relation between two
operands.
In other words, the operators used to make comparisons between
two operands are called Relational Operators.
Relational operators are binary operators and hence require two
operands.
The value of relational expression is either true or false.
If It is 1(non zero) the specified relation is true and 0(zero) If the
specified relation is false.
Relational Operators
Operator Operation
Symbol Performed
Use
Result
<
less than
Exp1<exp2
<=
Exp1<=exp2
>
Greater than
Exp1>exp2
>=
Exp1>=exp2
==
Equal to
Exp1= =exp2
!=
Not equal to
Exp1 != exp2
Relational Operators:
Operators
First Group
<,<=,>,>=
Second Group
==, !=
Examples
If i=2, f=3.5 where I is integer type variable and f
is floating type variable
(i+f)>=5
will give result true and return
value 1.
f>3
Will interpret it to be true and
result is 1.
Logical Operators:
Logical operators are used to combine one or more relational
expressions that results in formation of complex expressions known
as logical expressions.
Like Relational operators, the logical operators evaluate the result of
logical expressions in terms of Boolean values that can only be true
(non zero) or false(zero) according to the result of the logical
expression.
Operator
Operation Performed
Use
&&
Logical AND
||
Logical OR
Expr1 || Expr 2
Logical NOT
! (expr)
Logical Operators:
The following table shows the operation of Logical AND ,logical
OR and Logical NOT
Expr1
Expr2
Expr1 &&
EXpr2
Expr1 ||
Expr2
! (Expr 1)
False
False
False
False
True
False
True
False
True
True
True
False
False
True
False
True
True
True
True
False
Logical Operators:
Examples
Consider an example where x has an integer
value 3 and y has a character value b then
(x==3) && (y==b)
True
False
(x>4) || (y=a)
False
! (x==3)
False
Bitwise Operators:
C++ provides an extensive bit manipulation
operators for programmers who want to communicate directly with
the hardware. These operators are used for testing bits or shifting
them either right to left or left to right. The Bitwise operators are
Operator
&
|
Meaning
Bitwise AND
Bitwise OR
Bitwise exclusive OR
<<
>>
~
Shift left
Shift right
ones complement
Assignment Operator:
Assignment operator (=) is the most commonly used binary
operator in C++. It evaluates the operand on right hand side and
then assigns the resulting value to a variable on the left hand side.
The right operand can be a variable, constant ,function call or
expression. The general form of representing assignment operator
is :: variable = expression/constant/function call
For example ::
A=3 ; // constant
X=y+10; // expression
Consider a statement x=y=z=3;
Such type of statement in which a single value is given to a
number of variables is called multiple assignment statement.
Shorthand Operator
a=a+1
a+=1
a=a-1
a-=1
a=a*(n+1)
a*=n+1
a=a/(n+1)
a/=n+1
a=a%b
a%=b
m++;
-- m;
m--;
or
#include<iostream.h>
#include<conio.h>
void main()
{
int i=1;
printf(i=%d\n,i);
printf(i=%d\n,++i);
printf(i=%d\n,i);
getch();
}
#include<iostream.h>
#include<conio.h>
void main()
{
int i=1;
printf(i=%d\n,i);
printf(i=%d\n,i++);
printf(i=%d\n,i);
getch();
}
Output1(No change)
2(Alteration before
execution)
2 (No change)
Output1(No change)
1(No change because
alternation after execution)
2 (New incremented value
by 1)
e.g
7==5 ? 4 : 3 // returns 3, since 7 is not equal to 5.
7==5+2 ? 4 : 3 // returns 4, since 7 is equal to 5+2.
5>3 ? a : b // returns the value of a, since 5 is
greater than 3.
#include<iostream.h>
#include<conio.h>
void main()
{
int a=10 ,b=5,c;
c=a>b?a:c;
cout<<c=<<c;
getch();
}
output:
cout<<sizeof (a);
// 2
cout<<sizeof (b);
//4
cout<<sizeof (c);
//8
cout<<sizeof (d);
//1
getch();
}
output: a=10 20
Language Constructs
Control Structures
IfElse if ladder
In the programs involving multiple test conditions ,
the nested if-else statements makes the program
very difficult to write and understand especially if they
are nested more deeply because as the number of
test conditions go on increasing ,care must be taken
to match multiple if-else constructs. In order to solve
the problem ,there is another way to write the same
statements using if else-if ladder.
The Syntax of if else if ladder is shown in next slide.
68
69
LOOPs
LOOPs
In order to understand the concept of loops , let us
consider a simple program which calculates the cube
of first 3 natural numbers.
#include <iostream.h>
#include <conio.h>
int main()
{
int a,b,c;
a=1;
cout << Cube of 1= << a*a*a;
b=1;
LOOPs (contd..)
b=2;
cout << Cube of 2= << b*b*b;
c=3;
cout << Cube of 3= << c*c*c;
getch();
return 0;
}
But if we want to find out the cubes first 10000 natural
nos. then we would have to repeat the steps again
and again which would be cumbersome and time
consuming process.
Loop Structures
Loop structures allow you to execute one or more lines
of codes repetitively. Many tasks consist of trivial
operations that must be repeated over and over again,
and looping structures are an important part of any
programming language.
C++ supports the following Loop statements.
dowhile Loop
whileloop
forloop
Equivalent to:
// something
while( condition) {
// something
}
76
Equivalent to:
for( ; condition ; ) {
// do something
}
78
Practice Questions
Q1 What will be the value ox x after the
following two operations::
a = 10, b = 15
x=(a<b) ? a :b
Practice Questions
Q2 If x=2,y=4,z=10 then compute the
following expression:
a) x < y + z
2 < 4 +10
2< 14
true (1)
Practice Questions
Q3 If x=2,y=4,z=10 then compute the
following expression:
a) y + z = = x - y
Practice Questions
Q4 Which loops body is executed
atleast once?
Practice Questions
Q4 What is the difference between
if (i= = j) and if (I = j) ?
Practice Questions 7
Q5 ++x is an example of
prefix operator
postfix operator
Thank You
Please forward your query
To :bminocha@amity.edu
Cc: manoj.amity@panafnet.com
Session Outline
for loop
Functions
Storage classes
Reference variable
Parameter passing mechanism
Function overloading
Inline function
Class
Friend function
For Loop
The for Next loop is one of the oldest loop
structures in programming languages. do Loop works
well when we dont know how many times we need to
execute the statements in the loop. When we know
we must execute a specific no. of times ,however a
for loop is a better choice.
This is a loop with an in-built counter. The syntax is:
for (initialization ; condition; increment/decrement)
{
statements;
}
ForNext Loop
where
initialization expression is used to initialize the loop
control variable.
Condition is a relational or logical expression that
determines the number of iterations desired and
whether the loop should continue iterating or not.
The Increment/decrement expression modifies the
value of the loopcontrol variable each time the loop is
executed.
Functions
Functions are building blocks of the programs.
They make the programs more modular and
easy to read and manage.
All C++ programs must contain the function
main( ).
The execution of the program starts from the
function main( ).
Function
There are two kinds of functions
1. library functions or built-in functions
2.user defined functions
Library functions string functionstrcpy(),strcmp,strcat .
mathematical functions-pow,sqrt,sin(x) etc
Functions
The general form of the function is: return_type function_name(parameter list)
{
body of the function
}
Functions
The function consists of two parts function
header and function body. The function
header is:
return_type function_name(parameter);
Functions
For example,
int factorial(int n, float j)
is the function header of the function
factorial.
The return type is of integer which means
function should return data of type integer.
The parameter list contains two variables
n and j of type integer and float
respectively.
Functions
Three things to remember
Function Declaration
Function Calling
Function Definition
Function Declaration
A call to the function cannot be made unless
it is declared. The general form of the
declaration is:return_type function_name(parameter list);
Function
For example function declaration
int factorial(int n1,float j1);
Another method
int factorial(int , float);
Arguments contain the actual value which is to be
passed to the function when it is called should
correspond with the data types of the parameters.
Types of Function
Function with no argument and no return
type
Function with argument and no return type
Function with no argument and return type
Function with argument and return type
Function
The Return Statement and Return values
A return statement is used to exit from the
function where it is.
It returns the execution of the program to the
point where the function call was made.
It returns a value to the calling code.
The general form of the return statement is:return expression;
Function
The expression evaluates to a value which
has type same as the return type specified
in the function declaration. For example
the statement,
return(n);
If a function has return type as void then
return statement does not contain any
expression. It is written as:
return;
//programtoaddtwonumbersusingfunctionswith
argumentandnoreturntype.
#include<stdio.h>
#include<conio.h>
voidadd(int,int);
voidmain()
{
intc,d;
printf(Entertwonumbers:);
scanf(%d%d,&a,&b);
add(a,b);
getch();
}
voidadd(intc,intd)
{
inttemp;
temp=c+d;
printf(%d,temp);
}
//programtoaddtwonumbersusingfunctionswith
argumentandreturntype.
#include<stdio.h>
#include<conio.h>
intadd(int,int);
voidmain()
{
intc,d,sum;
printf(Entertwonumbers:);
scanf(%d%d,&a,&b);
sum=add(a,b);
printf(%d,sum);
getch();
}
intadd(intc,intd)
{
intsum;
sum=c+d;
return(sum);
}
//programtoaddtwonumbersusingfunctionswithno
argumentsbutreturntype.
#include<stdio.h>
#include<conio.h>
intadd();
voidmain()
{
intsum;
sum=add();
printf(%d,sum);
getch();
}
intadd()
{
inta,b,sum;
printf(Entertwonumbers:);
scanf(%d%d,&a,&b);
sum=a+b;
return(sum);
}
//programinwhichafunctionacceptsnoargumentsandreturns
novalue.
#include<stdio.h>
#include<conio.h>
voidfunc1();
voidfunc2();
voidmain();
{
func1();
func2();
func1();
getch();
}
voidfunc1()
{
inti;
for(i=1;i<10;i++)
printf(%d,i);
printf(\n);
}
voidfunc2()
{
intj;
for(j=1;j<10;j++)
printf(*);
printf(\n);
}
Reference Variable
Provides an alternative name for a previously defined
variable.
Reference variable is created as follows
Datatype &reference name = variable name
void main()
{
int m=10;
f(m);
}
When the function call f(m) is executed ,the following initialization
occurs.
int &x=m;
x becomes an alias of m after executing the statement f(m)
Such function calls are known as call by reference.
#include<iostream.h>
#include<conio.h>
int x=5,y=10;//global variable
int main()
{
int z=15//local variable of main()
void abc();
abc();
cout<<z=<<z;
cout<<\nx=<<x;
abc();
getch();
}
void abc()
{
int w;
w=x+y;
cout<<\nw=<<w;
}
#include<iostream.h>
#include<conio.h>
int x=10; //Global variable
int main()
{
int x=5; //local variable in function main()
cout<<local x=<<x; //accessing local variable
cout<<\n Global x=<<::x; //accessing global variable
getch();
} outputlocal x =5
Global x=10
Automatic Variable
Automatic variable(s) are declared inside a
block or function in which they are to be
used.In other words,their scope is limited to
only the block or function where they are
declared.
Automatic variables are called so because
they are created (i.e assigned memory
automatically when the control enters the
block or function and are destroyed (i.e
release memory) automatically when the
control exits from the function.
void abc()
{
auto int j=25;
cout<<\n In function j=<<j;
}
Output:
In innermost block j=20
In function j=25
In outer block j=15
Declaration of automatic variable
auto int x=1; //or int x=1;
auto float z; // or float z; z is not initialized to
any value in the declaration so it contains
a garbage value.
Extern variable
The global variable can be accessed by all
the functions that follows its definition in a
source file.These variable can be used to
share information in a program that
expands across multiple files .
If a global variable is defined in some file
and you want to use this variable in some
other file in your multifile program then
declare such variable as extern variable
using the keyword extern.
Static variables
A static variable when declared within a
function retains its value between the
successive function calls.
The scope of static variables declared
inside the function is same as that of
automatic variable and its lifetime is same
as that of global variable except that it
comes into existence when the first
invocation is made to the function
containing it.
Register variables
Automatic variables are normally stored in
memory but in order to speed up the
memory access to the variable ,we store it
in register using register storage class
specification.
A register variable can be declared as
register int counter=1;
By default ,it is initialized to a garbage value,
same as that of automatic variable.
}
Here x is passed by value that means if we change
the value of x in f(), there will be no effect on the
value of argument that is sent at the time of f()
call.
This is called as pass-by-value
Pass by reference
When we write a function like
f ( int& x ) {
cout >> value of X in f() before change : >> x;
x =3;
cout >> value of X in f() before change : >> x;
}
Here x is passed by reference and not by value
that means if we change the value of x in f(),
there will be change in the value of argument
that is sent at the time of f() call. This is called as
pass-by-reference
Function Overloading
Function overloading is the practice of
declaring the same function with
different signatures. The same function
name will be used with different number
of parameters and parameters of
different type. But overloading of
functions with different return types are
not allowed.
Function Overloading
A function is overloaded when same name
is given to different function. However, the
two functions with the same name will
differ at least in one of the following.
a) The number of parameters
b) The data type of parameters
c) The order of appearance
Function Overloading
In general functions are overloaded when :
1. Functions differ in function
signature.
2. Return type of the functions is the
same.
#include <iostream>
class arith {
public:
void calc(int num1)
{
cout<<"Square of a given number: " <<num1*num1 <<endl;
}
void calc(int num1, int num2 )
{
cout<<"Product of two whole numbers: " <<num1*num2 <<endl;
}
};
void main() //begin of main function
{
arith a;
a.calc(5);
a.calc(6,7);
}
Function Overloading
If an exact match is not found ,the
complier uses the integral promotion to the
actual argument such as
float to double
Function Overloading
Where ambiguity arises
long square(long n);
double square(double x);
square(10);
will cause error because int argument can be
converted to either long or double (ambiguity)
Inline Function
Inline functions are functions where the
call is made to inline functions, the actual
code then gets placed in the calling
program.
Inline Function
What happens when an inline function is
written?
When the program is compiled, the code
present in function body is replaced in the
place of function call
Inline Function
Inline function eliminates the cost of calls
to small function
The general format of inline function is as
follows:
inline datatype function_name(arguments)
Inline Function
#include <iostream.h>
int multi(int);
void main( )
{
int x;
cout << \n Enter the Input Value: ;
cin>>x;
cout<<\n The Output is: << multi(x);
}
inline int multi(int x1)
{
return 5*x1;
}
Inline Function
Inline functions will save time and are
useful if the function is very small. If the
function is large, use of inline functions
must be avoided.
The inline directive will be totally of no use
when used for functions which are:
recursive
long
composed of loops
Introduction to CLASS
Class: A Class is a user defined data type
to implement an abstract object. Abstract
means to hide the details. A Class is a
combination of data and functions.
Data is called as data members and
functions are called as member functions.
Data Members
Data member or member functions may be
public, private or protected.
Public means data members or member
functions defining inside the class can be used
at outside the class.( in different class and in
main function)
Data Members
Private means data members and member
functions cant be used outside the class.
Protected means data member and
member functions can be used in the
same class and its derived class (at one
level) (not in main function).
Data Members
PRIVATE
PUBLIC
void main()
{
student s;
cout<<enter the rollno.:;
cin>>s.rollno;
cout<<enter the name:;
gets(s.name);
cout<<rollno:<<s.rollno;
cout<<\nname:;
puts(s.name);
}
void main()
{
student s;
cout<<enter the rollno.:;
cin>>s.rollno;
cout<<enter the name:;
gets(s.name);
cout<<rollno:<<s.rollno;
cout<<\nname:;
puts(s.name);
}
#include<iostream.h>
#include<stdio.h>
class student
{
int rollno;
char name[20];
public:
void getdata();
void putdata();
};
void student :: getdata()
{
cout<<enter the rollno.:;
cin>>rollno;
cout<<enter the name:;
gets(name);
}
Solution:
#include<iostream.h>
#include<stdio.h>
class student
{
int rollno;
char name[20];
public:
void getdata();
void putdata();
};
void student :: getdata()
{
cout<<enter the rollno.:;
cin>>rollno;
cout<<enter the name:;
gets(name);
}
void student: :: putdata()
{
cout<<rollno:<<rollno;
cout<<\nname:;
puts(name);
}
void main()
{
student s[10];
int i: // index variable
for ( i = 0; i< 10; i++)
{
s[i].getdata ( );
}
for (i = 0 ; i < 10 ; i ++)
{
s[i].putdata( );
}
}
rollno 2 bytes
name- 20 bytes
marks- 2 bytes
24 bytes
Friend function
In principle, private and protected
members of a class cannot be accessed
from outside the same class in which they
are declared.
However, this rule does not affect friends.
Friends are functions or classes declared
with the friend keyword.
Friend Function
A friend function has full access rights to
the private members of the class.
invoked like normal function
Cant access member names directly and
has to use an object name and dot
membership operator with each member
name.
Friend Function
Declared in either public or the private part
of a class
Object as its arguments
Class sample
{
int a,b;
Friend Function
public: void setdata()
{ a=25;
b=40;
}
friend float mean(sample s);
};
float mean (sample s)
{ return float (s.a+s.b)/2.0;
}
void main()
{sample x;
x.setvalue();
cout<<mean value=<<mean(x)<< \n;
getch();
}
1.
by reference
by value
globally
locally
What
is
function
overloading
function
from
itself
Thank You
Please forward your query
To :bminocha@amity.edu
Cc: manoj.amity@panafnet.com
Session outline
Inline Functions
Class
Array of class objects
Memory Allocation of objects
Friend function
Static data member and Static functions
Default Arguments
Constructor (Constructors in Array of Objects, Constructor overloading,
Copy Constructor)
Destructor
Inline Function
Inline functions are functions where the
call is made to inline functions, the actual
code then gets placed in the calling
program.
Inline Function
What happens when an inline function is
written?
When the program is compiled, the code
present in function body is replaced in the
place of function call
Inline Function
Inline function eliminates the cost of calls
to small function
The general format of inline function is as
follows:
inline datatype function_name(arguments)
Inline Function
#include <iostream.h>
int multi(int);
void main( )
{
int x;
cout << \n Enter the Input Value: ;
cin>>x;
cout<<\n The Output is: << multi(x);
}
inline int multi(int x1)
{
return 5*x1;
}
Inline Function
Inline functions will save time and are
useful if the function is very small. If the
function is large, use of inline functions
must be avoided.
The inline directive will be totally of no use
when used for functions which are:
recursive
long
composed of loops
Introduction to CLASS
Class: A Class is a user defined data type
to implement an abstract object. Abstract
means to hide the details. A Class is a
combination of data and functions.
Data is called as data members and
functions are called as member functions.
Introduction to CLASS
Class: A Class is a user defined data type
to implement an abstract object.
Abstract means to hide the details.
A Class is a combination of data and
functions.
Data is called as data members and
functions are called as member functions.
Data Members
Data member or member functions may be
public, private or protected.
Public means- data members or member
functions defining inside the class can be used
at outside the class.( in different class and in
main function)
Private means -data members and member
functions cant be used outside the class.
Protected means data member and member
functions can be used in the same class and its
derived class (at one level) (not in main
function).
Data Members
PRIVATE
PUBLIC
void main()
{
student s;
cout<<enter the rollno.:;
cin>>s.rollno;
cout<<enter the name:;
gets(s.name);
cout<<rollno:<<s.rollno;
cout<<\nname:;
puts(s.name);
}
void main()
{
student s;
cout<<enter the rollno.:;
cin>>s.rollno;
cout<<enter the name:;
gets(s.name);
cout<<rollno:<<s.rollno;
cout<<\nname:;
puts(s.name);
}
void putdata()
{
cout<<rollno:<<rollno;
cout<<\nname:;
puts(name);
}
};
void main()
{
student s; Calling member function
s.getdata();
s.putdata();
getch();
}
void main()
{
student s[10];
int i: // index variable
for ( i = 0; i< 10; i++)
{
s[i].getdata ( );
}
for (i = 0 ; i < 10 ; i ++)
{
s[i].putdata( );
}
}
rollno 2 bytes
name- 20 bytes
marks- 2 bytes
24 bytes
Friend function
In principle, private and protected
members of a class cannot be accessed
from outside the same class in which they
are declared.
However, this rule does not affect friends.
Friends are functions or classes declared
with the friend keyword.
Friend Function
A friend function has full access rights to the
private members of the class.
invoked like normal function
Cant access member names directly and has
to use an object name and dot membership
operator with each member name.
Friend Function
Declared in either public or the private part
of a class
Object as its arguments
class Product
{
static int count;
int number;
public:
void getdata(int a)
{
number=a;
count++; }
void getcount()
{
cout<< count= <<count<<endl;
}
};
void main()
{
Product a, b, c;
a.getcount();
b.getcount();
c.getcount();
a.getdata(100);
b.getdata(200);
c.getdata(300);
cout<<after reading data<<\n;
a.getcount();
b.getcount();
c.getcount();
}
Class Test
{
int code;
static int count;
public:
void setcode()
{
code= ++count;
}
void showcode()
{
cout<< code= <<code;
}
static void showcount()
{
cout<<count=<<count<<\n;
} };
Output count = 2
count = 3
code=1
code=2
code=3
Default Arguments
Default argument is useful in situations
where a argument has the same value in
most function calls.
When the desired value is different from
the default value, the desired value can be
specified explicitly in function call. This
changes the default value of the argument
to be overridden for the duration of
function call.
Default Arguments
e.g- Consider example of a bank which
introduces a new money deposit scheme where
rate of interest is fixed to 5.5% per annum.
If we want to calculate the simple interest on
amount deposited by different customers under
this scheme, we have to make a function SI()
containing three parameters Principal(P),Rate of
Interest r and Time period t .On calling this
function for different values, we find the values
of arguments r and t remain the same for each
time, we need to pass only one argument.
Default Arguments
#include<iostream.h>
#include<conio.h>
float SI(float p,float r=5.5,float t=1.0);// function
declaration
void main()
{
float k;
k=SI(10000); //equivalent to k=SI(10000,5.5,1.0);
cout<<simple interest is=<<k<<endl;
k=SI(15000,6.0,0.5);
cout<<simple interest=<<k;
getch();
}
Default Arguments
float SI(float p,float r,float t)
{
float sil=(p*r*t)/100;
return sil;
}
Output- Simple interest=550
Simple interest=720
Constructor
A constructor is a special member function
having same name as that of the class to
which it belongs.
It is used to initialize some valid values
and allocate resources to the data
members of an object.
It is executed automatically when an
object of a class is created.
It does not have any return data type, not
even void.
Class classname
{
.
public:
classname(parameter list); // constructor
declaration .
};
Classname:: classname(parameter list)
//constructor definition.
{
}
They can also be defined inside the class as other
member functions.
#include<iostream.h>
class Rectangle
{
private:
int len, br;
public:
Rectangle()
{
len=5, br=4;
}
int area()
{
return (len*br);
}
};
void main()
{
Rectangle r1;
cout<<Area of
rectangle = ;
cout<<r1.area();
}
Output- Area of
rectangle = 20
Parameterized constructors
class Rectangle
{
private:
int len, br;
public:
Rectangle(int a, int b)
{
len=a, br=b;
}
int area()
{
return (len*br);
}
};
void main()
{
Rectangle r1(5,4);
Rectangle r2(8,6);
cout<< \n Area of rectangle1
= << r1.area();
cout<<\n area of
rectangle2=<<r2.area();
}
Output:
Area of rectangle 1 =20
Area of rectangle 2= 48
Constructor Overloading
It allows a class to have more than one
constructors that have same name but
differ in terms of number of parameters or
parameters datatype or both.
#include<iostream.h>
Class Rectangle
{
private:
int len, br;
public:
Rectangle()
{
len=0, br=0;
}
Rectangle(int a)
{
len=br=a;
}
Rectangle(int a, int b)
{
len=a, br=b;
}
int area()
{
return (len*br);
} };
void main()
{
Rectangle r1;
Rectangle r2(5);
Rectangle r3(7,8);
cout<<\nArea of first
rectangle =<< r1.area();
cout<<\n Area of
square=<< r2.area();
cout<<\n area of second
rectangle<<r3.area();
}
class Rectangle
{
private:
int length, breadth;
public:
Rectangle(int a, int b)
{
length=a, breadth=b;
}
void showarea()
{
cout<<area is
<<length*breadth;
}
};
void main()
{
Rectangle r[3]={Rectangle
(5,6), Rectangle(4,2),
Rectangle(5,3)};
cout<< displaying areas of
rectangle\n
for(int i=0;i<3;i++)
{
r[i].showarea();
}
}
Copy Constructor
It is a constructor that creates a copy of an
existing object.
It creates a new object using an existing
object of the same class and initialize each
data member of newly created object with
corresponding data members of existing
object.
class counter
{
int count;
public: counter(int c)
{ counter=c;}
counter(counter &ob)
{
cout<<copy const.
invoked;
count=ob.count;
}
void show()
{cout<<count= <<
count;}
};
void main()
{ counter c1(10);
counter c2(c1); //or
counter c2=c1;
c1.show();
c2.show();
getch();
}
Destructor
A destructor is a member function which helps
to deallocate the memory allocated to an object.
It has the same name as that of a const. but
preceded by a tilde(~) symbol.
It is executed automatically when objects of a
class is destroyed.
Like constructor, it does not have any return
data type and not even void.
A destructor does not accept any parameters.
A class can have only one destructor and hence
cannot be overloaded.
Syntax:
class classname
{
.
public:
~ classname(); //destructor declaration
};
classname:: ~classname() //destructor definition
{.
}
class counter
{
int id;
public:
counter(int i)
{
id =i;
cout<< constructor of object with
id << id <<runs;
}
~counter()
{
cout<<\n object with id <<id<<
destroyed;
}};
void main()
{
counter c1(1);
counter c2(2);
counter c3(3);
cout<<end of main();
}
Friend Constructor
Copy constructor
Parameterized constructor
Default constructor
Call by value
Call by pointers
Default arguments
Call by reference
Answers:
1A
2C
3A
4 B,D
5A
6C
Contents
Exception Introduction
Exception handling
Try, catch
Throw
Exception specification
#include <iostream>
int main() {
double a, b, c; // Request two numbers from the user
cout << "Please provide two numbers\n"; cout << "First
Number: ";
cin >> a;
cout << "Second Number: ";
cin >> b;
// Multiply the numbers and display the result
c = a * b;
cout << "\n" << a << " * " << b << " = " << c << "\n\n";
return 0;
}
try ,catch,throw
1.
}
catch (Argument) {
// Catch the exception
try {
.
if (condition)
throw;
.
These statements
are not executed if
.
throw is executed.
}
catch(...) {
catch statement1;
catch statement2;
..
}
try {
// code here
}
catch (int param) {
cout << "int exception";
}
catch (char param) {
cout << "char exception";
}
catch (...) {
cout << "default exception";
}
Exception specifications
C++ allows you to specify the list of exceptions that a
function can throw.This specifiction is known as
exception specification or a throw list .It ensures that
function will not throw other than listed exception in the
exception specification.
The exception specification can take the following form:
Datatype functionname(parameter list) throw (type list)
{
//function body
}
void main()
{
cout<<start of main;
try
{
func_test(1);
}
catch(int )
{
cout<<int type exception
catched;
}
catch(char)
{
cout<<char type
exception catched;
}
Thank You
Please forward your query
To: bminocha@amity.edu.
Cc : manoj.amity@panafnet.com
88
Session Outline
SINGLE LEVEL
MULTI LEVEL
MULTIPLE
HYBRID
HIERARCHICAL
void B::getab()
{
a=5;
b=10;
}
int B::geta()
{
return a;
}
void B::show()
{
cout<<a=<<a;
}
void D::multi()
{
c=b*geta();
}
B
D
void D::display()
{
cout<<geta();
cout<<b=<<b;
cout<<c=<<c;
}
void main()
{
D d;
d.getab();
d.multi();
d.show();
d.display();
d.b=20;
d.multi();
d.display();
getch(); }
Outputa=5
a=5
b=10
c=50
a=5
b=20
c=100
Note- When the base class is publicly inherited, public
members of the base class become public of the derived
class.
#include<iostream.h>
#include<conio.h>
class B
{
int a;
public:
int b;
void getab();
int geta();
void show();
};
class D:private B
{
int c;
public:
void multi();
void display(); };
void B::getab()
{
a=5;
b=10;
}
int B::geta()
{
return a;
}
void B::show()
{
cout<<a=<<a;
}
void D::multi()
{
c=b*geta();
}
B
D
void D::display()
{
cout<<geta();
cout<<b=<<b;
cout<<c=<<c;
}
void main()
{
D d;
d.getab(); //wont work
d.multi();
d.show(); //wont work
d.display();
d.b=20; //wontt work ;b has
become private
d.multi();
d.display();
getch(); }
Output
a=5
b=10
c=50
a=5
b=10
c=50
Note-When a base calss is privately inherited by a derived class,public
members of the base class become private members of the derived
class and
therefore the public members of the base class can only be accessed by
the menber functions of the derived class.They are inaccessible to the
objects of the derived class
Multilevel Inheritance
The class A serves as a base class for the derived class B, which in
turn serves as a base class for the derived class C.
A program showing multilevel
inheritance
class student
{
protected:int rollno;
public:void getnumber(int a)
{
rollno=a;
}
void printnumber()
{
cout<<rollno=<<rollno;
};
class test:public student
{
protected:float sub1,sub2;
public:
student
test
result
void display()
{
total=sub1+sub2;
putnumber();
putmarks();
cout<<total=<<total;
} };
void main()
{
result r1;
r1.getnumber(20);
r1.getmarks(75.5,59.5);
r1.display();
getch();
}
Outputrollno=20
marks in sub1=75
marks in sub2=59.5
total =134.5
Multiple Inheritance
Aclasscaninherittheattributesoftwoormoreclasses.
A program showing multiple
inheritanceclass M
{
Int m;
public:
void getm(int x)
{
m=x;
}
};
class N
{
int n;
public:
void getn(int y)
{
n=y;
}
Outputm=10
n=20
m*n=200
public:
void display()
{
cout<<abcd;
A
}
};
void main()
{
p p1;
p1.display();
/*Derived calss
function will be
executed . */
getch();
}
Ambiguity Resolution
In the previous program if we want to call the display functions
of classes M and N also we have to call them in main class
void main()
{
P p1;
p1.display();
p1.M::display();
p1.N::display();
}
This is solving of
operator(::).
ambiguity
by
using
scope
resolution
void main()
{
P p;
p.display();
}
output - class M
Hybrid Inheritance
Itisacombinationofmultipleandmultilevelinheritance.
A program showing hybrid inheritancepublic:
void get_marks(float x,float y)
class student
{
{
protected:
marks1=x;
int rollno;
marks2=y;
public:
}
void get_rollno(int a)
void put_marks()
{
{
rollno=a;
cout<<marks1=<<marks1<<\n;
}
cout<<marks2=<<marks1<<\n;
void put_rollno()
}
{
cout<<rollno = <<rollno<<\n;
};
}
class sports
};
{
class test:public student
protected: int score;
{
protected:float marks1,marks2;
public:
void get_score(int c)
{
score=c;
}
void put_score()
{
cout<<score=<<score<<\n\n;
}
};
class result:public test,public sports
{
int total;
public:
void display()
{
total=marks1+marks2+score;
put_rollnumber();
put_marks();
put_score();
cout<<total=<<total; }
void main()
{ result r1;
r1.get_rollno(10);
r1.get_marks(27.5,33.0);
r1.get_score(6.0);
r1.display(); getch(); }
Student
Test
Result
Sports
Output:
rollno=10
marks1=27.5
marks2=33
score=6
Total=66.5
PARENT 1
PARENT 2
CHILD
Program
classstudent
{
protected:
int rollno;
public:
voidgetrollno(int a)
{
rollno=a;
}
voidputrollno()
{
cout<<rollno=<<rollno<<\n
;
}
};
classtest:public virtualstudent
{
protected:
floatmarks1,marks2;
public:
voidgetmarks(int m1,intm2)
{
marks1=m1;
marks2=m2;
}
voidputmarks()
{
cout<<marks1=<<marks1<<\n;
cout<<marks2=<<marks2<<\n;
}
};
classsports:publicvirtualstudent
{
protected:
floatscore;
public:
voidgetscore(ints)
{
scores;
}
voidputscore()
{
cout<<score=<<score;
}
};
STUDENT
TEST
total=marks1+marks2+score;
putrollno();
putmarks();
putscore();
cout<<total =<<total<<\n;
}
};
SPORTS
RESULT
CONSTRUCTOR IN DERIVED
CLASS
class alpha
{
int x;
public:
alpha(int i)
{
x=i;
cout<<alpha
initialized;
}
void showx()
{
cout<<x=<<x;
}
};
class beta
{
float y;
public:
beta(float j)
{
y=j;
cout<<beta
initialized;
}
void showy()
{
cout<<y;
}
};
void shownm()
{
cout<<m;
cout<<n;
}
};
void main()
{
gamma g(5,10.75,20,30);
g.showx();
g.showy();
g.shownm();
}
Outputbeta initialized
alpha initialized
gamma initialized
x=5
y=10.75
m=20
n=30
stack()
{
top=0;
}
void push(int var)
{
st[++top]=var;
}
int pop()
{
return st[top--];
}
};
void main()
{
stack2 s1; //here base constructor called first
//then derived class constructor
s1.push(11);
s1.push(12);
s1.push(13);
cout<<\ndeleted item is<<s1.pop();
cout<<\ndeleted item is<<s1.pop();
cout<<\ndeleted item is<<s1.pop();
getch();
}
Output:
deleted item is 13
deleted item is 12
deleted item is 11
Execution of constructor
Method of inheritance-order of execution
Class B: public A
{
}
Order of execution-A(): Base Constructor
B(): Derived constructor
What Changes:
We can extend the semantics of the
operator that is being overloaded.
But we cannot change the Syntax
associated with that particular operator,
i.e., the grammatical rules that govern its
use such as the number of operands,
precedence and associativity cannot be
changed.
The original meaning of the operator
being overloaded is not lost.
Example:
Overloading Unary Operator(-ve):
class space
{ int a, b;
public:
void input(int x,int y);
void display();
void operator-();
};
void main()
{
space S;
S.input(15,-5);
cout<<S(Before Overloading): ;
S.display();
-S;
//operator-(S);
cout<<S(After Overloading): ;
S.display();
getch();
}
Example:
Overloading Binary Operator(+):
When overloading a binary operator:
the left operand is passed implicitly to the
function, and
the right operand is passed as an
argument.
temp.y = y + c.y;
//return complex((x + c.x),(y + c.y));
return (temp);
}
void complex :: display()
{
cout<<x<<+ i <<y<<endl;
}
void main()
{
complex C1, C2 , C3;
C1 = complex(2.1,4.1);
C2 = complex(3.1,5.1);
cout<<C1= <<C1.display();
cout<<C2= <<C2.display();
C3= C1 + C2;
cout<<C3= <<C3.display();
getch();
Output
5.2+9.2
Output
5.2+9.2
Concatenate 2 Strings
using logical AND &&:
class strcon
{
char str[15];
public:
strcon
{
strcpy(str, );
strcon(char a[])
{ strcpy(str,a); }
void display()
{ cout<<str;
}
strcon operator&&(strcon s)
{
strcon t;
strcpy(t.str,str);
strcat(t.str,s.str);
return t;
void main()
{
strcon obj1(epan);
strcon obj2(Amity University);
cout<<String one: ;
obj1.display();
cout<<String two: ;
obj2.display();
strcon obj3;
obj3 = obj1 && obj2;
cout<<Concatenated String is: ;
obj3.display();
}
Output
epanAmity University
Type Conversion
Converting one built- in data type to another built-in data type.
Type conversion can occur in number of situations like in
an assignment statement ,
in arithmetic expressions involving different data types and
in returning value from the function in which the type of the
expression differs from the return type.
#include<iostream.h>
#include<conio.h>
void main()
{
int a=5;
float b=7.6;
double c;
c=a+b;
cout<<c;
getch();
}
Hence the variable a is of int data type and b is of float data type
.So,during the evaluation of the expression a+b ,the data type of
the variable a is converted from int data type to that of float data
type and stored in temporary float variable which is created
automatically..Now,both the temporary variable and variable b is
to added have same data type so they are added and result
obtained is a float value which is again stored in a new temporary
variable which is created during its execution.
void main()
{
float f;
int c;
cout<<enter in f;
cin>>f;
c=5/9*(f-32);
cout<<temp <<c;
getch();
}
By using type casting: c= float(5)/9 + (f-32);
Datatype Conversions
Conversion from basic type to class
type.
Conversion from class type to basic
type
Conversion from one class type to
another class type
void main()
{
int duration=85;
time t1=duration; //int to
//class
t1.display();
}
Program
Class amount
{ float p,r;
int t;
public:
amount()
{}
void get(float pr, float ra, int ta)
{
p=pr;
r=ra;
t=ta; }
Operator float()
{
float s1;
s1=(p*r*t)/100;
return s1;
} };
void main()
{
amount obj;
obj.get(6.0,7.0,8);
float si;
si=obj; // class obj to float
//data type
cout<<si;
getch();
}
void show()
{
cout<<\nMoney in
Rs.<<rs;
} };
Class dollar
{
double dol;
public:
dollar(double doll)
{
dol=doll;
}
Operator rupee()
{
double rs1=dol*dollval;
return (rupee(rs1));
}
void show()
{
cout<<dol;
}};
void main()
{
dollar d1(3);
d1.show();
rupee r1=d1;
r1.show();
getch();
}
Output3
Money in Rs. 132.6
Conversion function in
destination class
# include<iostream.h>
#include<conio.h>
Class dollar
{
double dol;
public:
dollar(double doll)
{ dol=doll; }
void show()
{ cout<<Money in dollar<<dol; }
double retdol()
{return dol; } };
Class rupee
{
double rs;
public:
rupee(dollar d)
{
rs= d.retdol()*dollval; }
void show()
{ cout<<Money<<rs;}};
void main()
{
dollar d1(3);
d1.show();
rupee r1= d1; //Conversion
r1.show(); }
Answers:
1B
2B
3D
4C
Thank You
Please forward your query
To :bminocha@amity.edu
Cc : manoj.amity@panafnet.com
By - Sonia Saini
Copyright Amity University
Session outline
SINGLE LEVEL
MULTI LEVEL
MULTIPLE
HYBRID
HIERARCHICAL
void B::getab()
{
a=5;
b=10;
}
int B::geta()
{
return a;
}
void B::show()
{
cout<<a=<<a;
}
void D::multi()
{
c=b*geta();
}
B
D
void D::display()
{
cout<<geta();
cout<<b=<<b;
cout<<c=<<c;
}
void main()
{
D d;
d.getab();
d.multi();
d.show();
d.display();
d.b=20;
d.multi();
d.display();
getch(); }
Copyright Amity University
Outputa=5
a=5
b=10
c=50
a=5
b=20
c=100
Note- When the base class is publicly inherited, public
members of the base class become public of the derived
class.
Copyright Amity University
#include<iostream.h>
#include<conio.h>
class B
{
int a;
public:
int b;
void getab();
int geta();
void show();
};
class D:private B
{
int c;
public:
void multi();
Amity University
};
voidCopyright
display();
void B::getab()
{
a=5;
b=10;
}
int B::geta()
{
return a;
}
void B::show()
{
cout<<a=<<a;
}
void D::multi()
{
c=b*geta();
}
B
D
void D::display()
{
cout<<geta();
cout<<b=<<b;
cout<<c=<<c;
}
void main()
{
D d;
d.getab(); //wont work
d.multi();
d.show(); //wont work
d.display();
d.b=20; //wontt work ;b has become private
d.multi();
d.display();
getch(); }
Copyright Amity University
Output
a=5
b=10
c=50
a=5
b=10
c=50
Note-When a base calss is privately inherited by a derived class,public
members of the base class become private members of the derived
class and
therefore the public members of the base class can only be accessed by
the menber functions of the derived class.They are inaccessible to the
objects of the derived class
Multilevel Inheritance
The class A serves as a base class for the derived class B, which in
turn serves as a base class for the derived class C.
A program showing multilevel
inheritance
class student
{
protected:int rollno;
public:void getnumber(int a)
{
rollno=a;
}
void printnumber()
{
cout<<rollno=<<rollno;
};
class test:public student
{
protected:float sub1,sub2;
public:
student
test
result
void display()
{
total=sub1+sub2;
putnumber();
putmarks();
cout<<total=<<total;
} };
void main()
{
result r1;
r1.getnumber(20);
r1.getmarks(75.5,59.5);
r1.display();
getch();
}
Copyright Amity University
Outputrollno=20
marks in sub1=75
marks in sub2=59.5
total =134.5
Multiple Inheritance
Aclasscaninherittheattributesoftwoormoreclasses.
A program showing multiple
inheritanceclass M
{
Int m;
public:
void getm(int x)
{
m=x;
}
};
class N
{
int n;
public:
void getn(int y)
{
n=y;
} Copyright Amity University
Outputm=10
n=20
m*n=200
public:
void display()
{
cout<<abcd;
A
}
};
void main()
{
p p1;
p1.display();
/*Derived calss
function will be
executed . */
getch();
}
Ambiguity Resolution
In the previous program if we want to call the display functions
of classes M and N also we have to call them in main class
void main()
{
P p1;
p1.display();
p1.M::display();
p1.N::display();
}
This is solving of
operator(::).
ambiguity
by
using
scope
resolution
void main()
{
P p;
p.display();
}
output - class M
Hybrid Inheritance
Itisacombinationofmultipleandmultilevelinheritance.
A program showing hybrid inheritancepublic:
void get_marks(float x,float y)
class student
{
{
protected:
marks1=x;
int rollno;
marks2=y;
public:
}
void get_rollno(int a)
void put_marks()
{
{
rollno=a;
cout<<marks1=<<marks1<<\n;
}
cout<<marks2=<<marks1<<\n;
void put_rollno()
}
{
cout<<rollno = <<rollno<<\n;
};
}
class sports
};
{
class test:public student
protected: int score;
{
protected:float marks1,marks2;
Copyright Amity University
public:
void get_score(int c)
{
score=c;
}
void put_score()
{
cout<<score=<<score<<\n\n;
}
};
class result:public test,public sports
{
int total;
public:
void display()
{
total=marks1+marks2+score;
put_rollnumber();
put_marks();
Copyright Amity University
put_score();
cout<<total=<<total; }
void main()
{ result r1;
r1.get_rollno(10);
r1.get_marks(27.5,33.0);
r1.get_score(6.0);
r1.display(); getch(); }
Student
Test
Result
Sports
Output:
rollno=10
marks1=27.5
marks2=33
score=6
Total=66.5
PARENT 1
PARENT 2
CHILD
Program
classstudent
{
protected:
int rn;
public:
voidgetrollno(int a)
{
rollno=a;
}
voidputrollno()
{
cout<<rollno=<<rollno<<\n
;
}
};
classtest:public virtualstudent
{
protected:
floatmarks1,marks2;
public:
voidgetmarks(int m1,intm2)
{
marks1=m1;
marks2=m2;
}
Copyright Amity University
voidputmarks()
{
cout<<marks1=<<marks1<<\n;
cout<<marks2=<<marks2<<\n;
}
};
classsports:publicvirtualstudent
{
protected:
floatscore;
public:
voidgetscore(ints)
{
scores;
}
voidputscore()
{
cout<<score=<<score;
}
};
STUDENT
TEST
total=marks1+marks2+score;
putrollno();
putmarks();
putscore();
cout<<total =<<total<<\n;
}
};
SPORTS
RESULT
void main()
{
result r1;
r1.getrollno(678);
r1.getmarks(30.5,25.5);
r1.getscore(7.0);
r1.display();
getch();
}
Output- rollno=678
marks1=30.5
marks2 = 25.5
score=7
total =63
Copyright Amity University
Template
In function overloading ,we use the same name
for different implementations of the function.
Overloaded functions are distinguished by
means of different parameter list.
Problem with function overloading is that in the
program we not only have to define a separate
function for each data type but also if new type is
added later on, then new functions have to be
written for each one
Templates
Function Templates
Function templates are the generic functions
which can handle different data types without
the need of writing separate code for each of
them.Thus it reduces lot of manual effort in
development ,testing and
debugging of
programst.
Template parameter
A template parameter is a special kind of parameter
that can be used to pass a type as argument.
As regular function parameters can be used to pass
values to a function, template parameters allow to pass
also types to a function.
These function templates can use these parameters as if
they were any other regular type to write a code for
generic data type or class.
// function template
#include <iostream>
#include<conio.h>
template <class T>
T Max (T a, T b)
{
T result;
result = (a>b)? a : b;
return (result);
}
int main ()
{
int i=5, j=6, k;
long l=10, m=5, n;
k= Max<int>(i,j); // create a function for int type
n=Max<long>(l,m); // create a function for long
//type
cout << k << endl;
cout << n << endl;
return 0;
}
Output is
6
10
45
#include<iostream.h>
#include<conio.h>
template <class T>
void display(T a,T b,char operation)
{
switch(operation)
{
case +
:cout<<a<<operation<<b<<=<<a+b<<endl;
break;
case - :cout<<a<<operation<<b<<=<<a-b<<endl;
break;
case * :cout<<a<<operation<<b<<=<<a*b<<endl;
break;
case / :cout<<a<<operation<<b<<=<<a/b<<endl;
break;
default: cout<<undefined operation;
}
}
46
void main()
{
clrscr();
display(20,40.+);
display(3.5,1.5,);
getch();
}
Output:
20+40=60
3.5-1.5=2.0
47
Class Template
Like function template ,we can create generic classes using class
template that provide same functionality for different data types.
C++ class templates are normally used in the container classes such
as stacks,queues,vectors,lists etc.
Once the code is written as a class template,it can support multiple
data types.
Consider an example of stack data structure in which items can be
added and removed from the top in LIFO (last in first out) order.
A stack may store items of any data type but not a mixture of data
types. The code used for maintaining stack of integers can also work
for stack of float or character or double types.
Instead of creating separate stack class for different data types,we can
create a template for a stack class and use it to define stacks that
can store different data types.
49
voidmain()
{
clrscr();
stack<int>s1;
s1.push(10);
s1.push(20);
cout<<elementtobepopped<<s1.pop();
stack<float>s2;
s2.push(5.5);
s2.push(10.7);
cout<<\nelementtobe
popped<<s2.pop());
getch();
}
The statement
Template specialization
At times we want to define a different
implementation for a template when a
specific type is passed as template
parameter
We can always declare a specialization of
that template for that particular data type
as the need be.
// template specialization
#include <iostream>
// class template:
template <class T>
class mycontainer {
T element;
public:
mycontainer (T arg) {
element=arg;
}
T increase () {
return ++element;
}
};
Here
first line is the generic template,
second one is the template specialization.
Remember
When we declare specializations for a template class,
we must also define all its members, even those exactly
equal to the generic template class, because there is no
"inheritance" of members from the generic template to
the specialization.
61
63
Contents
Exception Introduction
Exception handling
Try, catch
Throw
Exception specification
#include <iostream>
int main() {
double a, b, c; // Request two numbers from the user
cout << "Please provide two numbers\n"; cout << "First
Number: ";
cin >> a;
cout << "Second Number: ";
cin >> b;
// Multiply the numbers and display the result
c = a * b;
cout << "\n" << a << " * " << b << " = " << c << "\n\n";
return 0;
}
try ,catch,throw
1.
}
catch (Argument) {
// Catch the exception
79
try {
.
if (condition)
throw;
.
These statements
are not executed if
.
throw is executed.
}
catch(...) {
catch statement1;
catch statement2;
..
}
try {
// code here
}
catch (int param) {
cout << "int exception";
}
catch (char param) {
cout << "char exception";
}
catch (...) {
cout << "default exception";
}
Exception specifications
C++ allows you to specify the list of exceptions that a
function can throw.This specifiction is known as
exception specification or a throw list .It ensures that
function will not throw other than listed exception in the
exception specification.
The exception specification can take the following form:
Datatype functionname(parameter list) throw (type list)
{
//function body
}
Program to demonstrate
exception specification
#include<iostream.h>
#include<conio.h>
void func_test(int val) throw(int,char)
{
if(val==0)
throw a; //throws char type
//exception
if(val==1)
throw 10; //throws int type exception
}
88
void main()
{
cout<<start of main;
try
{
func_test(1);
}
catch(int )
{
cout<<int type
exception catched;
}
catch(char)
{
cout<<char type
exception catched;
}
89
A.
B.
C.
D.
Answers1 a
2c
3d
4a
5c
6d
7a
Thank You
Please forward your query
To :ssani@aiit.amity.edu
CC: manoj.amity@panafnet.com
Contents
Streams
Stream classes
Unformatted I/0 operations
Formatted I/O operations
File Handling
Open function mode
Opening a file using constructor
Closing a file
Example programs of reading and writing
string,character I/0,Copy one file to another.
Reading and writing objects
File poniters (seekp,seekg,tellg,tellp)
Preprocessor directives
C++ Streams
Streams
A stream in C++ is treated as an object of a particular
class.C++ has a number of predefined streams which
are automatically opens when the programs execution
starts.These
predefined
streams
include
cin,cout,cerr,clog which plays a central role in console
I/0 operations .These predefined streams perform the
following functions
cin(console input) The cin object represent the input
stream connected to the standard input device (usually
keyboard) from where a progam normally reads the
input.
cout(console output) The cout object represent the
output stream connected to the standard output device
(usually monitor) from where a progam normally reads
the input.
ios
pointer
istream
streambuf
ostream
output
input
iostream
istream_withassign
iostream_withassign
ostream_withassign
Unformatted I/O operationscin and cout are predefined objects that support inputting
and outputting of data of various types.To accomplish
this ,the operators << and >> are overloaded in the
istream and ostream classes respectively. In addition to
<< and >> operators ,numerous other member
functions can also be used for performing input and
output operations.
istream member functions-istream class consists of
get(ch),
get(),
get(str,Max),
get(str,MAX,delim),
getline(str,MAX,delim),
read(str,Max).
#include<iostream.h>
#include <conio.h>
Outputint main()
{
Entera string :Amity University
const int MAX=80;
String is Amity University
char str[MAX];//array of character
cout<<\n enter a string
cin.get(str,MAX);
cout<<string is =<<str;
getch();
return 0;
}
#include<iostream.h>
#include <conio.h>
int main()
{
const int MAX=80;
char str[MAX];//array of character
cout<<\n enter a string
cin.get(str,MAX,*);
cout<<string is =<<str;
getch();
return 0;
}
OutputEnter a string:
Share Index is growing
Buy IPCI at current price
*
getline (str,MAX,delim)
The purpose of getline is similar to that of
get(str,MAX,delim) for inputting multiline string.
In getline if we skip the delimit then by default it
takes\n and therefore can input only a single
value.
#include<iostream.h>
#include <conio.h>
int main()
Output:
{
const int MAX=11;
enter a string:Stock Index
char str[MAX];//array of character string is Stock Index
cout<<\n enter a string
cin.read(str,MAX);
int count=cin.gcount();
str[count]=\0;
cout<<string is =<<str;
getch();
return 0;
}
write(str,MAX)
The purpose of write function is to output the MAX number
of characters of the character array str.
The process of displaying using write function does not
stop even when the NULL character (\0) is
encountered.
Due to this property,if MAX is greater than the length of str
then it may display unwanted character beyond the
maximum length of string.
#include<iostream.h>
#include<conio.h>
#include<string.h>
int main()
{
char str[]=Streams;
int len1=strlen(str)
for(int i=1;i<=len1;i++)
{
cout.write(str,i);
cout<<\n;
}
for(i=len1-1;i>0;i--)
{
cout.write(str,i);
cout<<\n;
}
return 0; }
Output
S
St
Str
Stre
Strea
Stream
Streams
Stream
Strea
Stre
Str
St
s
Task
width()
precision()
fill()
setf()
unsetf()
cout.width(4);
cout<<124;
#include<iostream.h>
int main()
{
#
#
cout.fill(#);
cout.width(6);
cout<<204;
cout.width(4);
cout<<34;
return 0;
}
precision(p)#include<iostream.h>
int main()
6
.
{
cout.precision(3);
cout<<6.7291<<endl;
return 0;
}
Flag(arg1)
Bit-field(arg2)
Left-justified output
ios::left
ios::adjustfield
Right-justified output
ios::right
ios::adjustfield
ios::internal
ios::adjustfield
Scientific notation
ios::scientific
ios::floatfield
ios::fixed
ios::floatfield
Decimal base
ios::dec
ios::basefield
Octal base
ios::oct
ios::basefield
Hexadecimal base
ios::hex
ios::basefield
#include<iostream.h>
#include<conio.h>
void main()
{
cout.fill(*);
cout.setf(ios::left,ios::adjustfield);
cout.width(15);
cout<<Table 1<<\n;
}
output:
T
* * * * * * **
#include<iostream.h>
#include<conio.h>
void main()
{
cout.fill(*);
cout.precision(3);
cout.setf(ios::internal,ios::adjustfield);
cout.setf(ios::scientific,ios::floatfield);
cout.width(15);
cout<<-12.34567<<\n;
getch();
}
- * * * * * 1 . 2 3 5 e + 01
Meaning
ios::showbase
ios::showpos
ios::showpoint
ios::unitbuf
ios::stdio
7 5
2 5
1 5 . 5
cout.setf(ios::showpoint); //display
//trailing zeros.
cout.setf(ios::showpos); // show +sign
#include<iostream.h>
#include<conio.h>
void main()
{
cout.setf(ios::showpoint);
cout.setf(ios::showpos);
cout.precision(3);
cout.setf(ios::fixed,ios::floatfield);
cout.setf(ios::internal,ios::adjustfield);
cout.width(10);
cout<<275.5<<\n;
+
2 7 5 .
getch();
}
5 0 0
Meaning
Equivalent
Setw(int w)
Width( )
Setprecision(int d)
Precision( )
Setfill(int c)
Fill()
Setiosflags(long f)
Setf( )
Resetiosflags(long f)
Unsetf( )
Endl
\n
Output-
n
1
2
3
4
5
Inverse_of_n
1.0000e+000
5.0000e-001
3.3333e-001
2.5000e-001
2.0000e-001
Sum_of_terms
1.0000
1.5000
1.8333
2.0833
2.2833
(Code)
return output
}
File Handling
C++ provides the following classes to
perform output and input of characters
to/from files:
1. ofstream: Stream class to write on files
2. ifstream: Stream class to read from files
3. fstream: Stream class to both read and
write from/to files.
We need to know:
how to "connect" file to program
how to tell the program to read data
how to tell the program to write data
ios
istream
streambuf
ostream
iostream
ifstream
fstream
ofstream
filebuf
fstreambase
A sample code
// basic file operations
#include <iostream.h>
#include <fstream.h>
int main () {
ofstream myfile;
myfile.open ("example.txt");
myfile << "Writing this to a file.\n";
myfile.close();
return 0;
}
open function
In order to open a file with a stream object i.e. an object
of type ofstream we use its member function open():
open (filename, mode);
Where
filename - is a null-terminated character sequence of
type const char * (the same type that string literals have)
representing the name of the file to be opened,
mode - is an optional parameter with a combination of
the following flags:
Modes
ios::in
ios::out
ios::binary
ios::ate
ios::app
ios::trunc
Class
ofstream
ios::out
ifstream
ios::in
fstream
ios::in | ios::out
Step 2.
Using the file stream object
After the file stream is opened successfully
with desired opening mode, we can use
the object to read/write data to the file
For example, if I need to open a file for
output operations and want o write some
data to file, we will write a code lines like
.
// create an object of ofstream type
ofstream myfile;
// open the stream for file example.txt.
// note no open mode is specified so
// default will be used i.e. ios::out here
// as it is an objetc of ofstream class
myfile.open ("example.txt");
// use the myfile object to write to file.
// note the use of << to write to file, in the same
// way as with cout.
myfile << "Writing this to a file.\n";
Syntax close()
The code will be like
myfile.close();
Where myfile is a stream object already opened with the
open member function.
Once this member function is called, the stream object
like myfile here can be used to open another file,
The file is available again to be opened by other
processes.
Example programs of
Character i/o
Writing/reading string.
Read/write object.
WRITING STRING:
#include<fstream.h>
void main()
{
ofstream out(test.txt) //creates file.
out.open(test.txt);
out<<Amity University;
out<<AIIT Noida;
out.close();
getch();
}
READING STRING:
void main()
{
const int MAX=80;
char buffer[MAX];
ifstream in(test.txt);
while(in) or
while(in eof() != 0)
{
in.getline(buffer.MAX);
cout<<buffer;
}
CHARACTER I/O
writing character by character.
#include<fstream.h>
#include<string.h>
{
char str[] = Amity University;
ofstream out(test.txt);
for(int j=0; j< strlen (str); j++)//for char. by char.
out.put(str[j])
//write it to file.
getch();
}
void main()
{
person p1;
p1.getdata();
ofstream out(abc.txt);
out.write((char*)&p1,sizeof(p1));
getch();
}
// address of object
to be return.
void main()
{
person p1;
ifstream in(abc.txt);
in.read((char*)&p1,sizeof(p1));
p1.putdata();
}
fstream file;
file.open(abc.txt,ios::app | ios::in | ios::out);
do
{
cout<<persons data;
p1.getdata();
file.write((char*)&p1,sizeof(p1));
cout<<another person(y/n)?;
cin>>ch;
}
while(ch==y);
file.seekg(0); //cursor go to starting of file.
file.read((char*)&p1,sizeof(p1));
while(!file.eof())
or
while(file)
{
cout<<person;
p1.show();
file.read((char*)&p1,sizeof(p1));
}
}
tellg()
Get position of the get pointer.
Returns the absolute position of the get pointer.
The get pointer determines the next location in
the input sequence to be read by the next input
operation.
tellp
Get position of put pointer
Returns the absolute position of the put
pointer.
The put pointer determines the location in
the output sequence where the next output
operation is going to take place.
seekg()
Set position of the get pointer
Sets the position of the get pointer.
The get pointer determines the next location
to be read in the source associated to the
stream.
istream& seekg ( streampos pos );
istream& seekg ( streamoff off, ios_base::seekdir dir );
seekp
ostream& seekp ( streampos pos );
ostream& seekp ( streamoff off, ios_base::seekdir dir );
putpointer
-seekp()
-tellp()
Beg
cur
End
seekg(4,ios::cur)
// it moves the get pointer to
4 position forward from the current position.i.e b
seekg(-3,ios::end) b
seekg(9,ios::beg) b
seekg(5)
t
void main()
{
person p1;
ifstream in;
in.open(abc.txt);
in.seekg(0,ios::end);
//go to 0 byte from end.
int endpos = in.tellg();
int n = endpos/sizeof(p1);
cout<<there are<<n<<persons in file;
cout<<enter person number;
cin>>n;
int pos=(n-1)*sizeof(p1);
in.seekg(pos);
in.read((char*)&p1,sizeof(p1));
p1.showdata(); }
Preprocessor
A unique feature of c language is the preprocessor. A
program can use the tools provided by preprocessor to
make his program easy to read, modify, portable and
more efficient.
Preprocessor is a program that processes the code
before it passes through the compiler. It operates under
the control of preprocessor command lines and
directives.
Preprocessor directives are placed in the source
program before the main line before the source code
passes through the compiler it is examined by the
preprocessor for any preprocessor directives.
If there is any appropriate actions are taken then the
source program is handed over to the compiler.
Preprocessor directives
Preprocessor directives follow the special
syntax rules and begin with the symbol #
#undef
Undefines a macro
#include
#ifdef
#endif
#ifndef
#if
#else
iostream
istream
ostream
fstream
Answers1C
2C
3D
4B
5C
6C
Thank You
Please forward your query
To :bminocha@amity.edu
Cc: manoj.amity@panafnet.com