Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 151

Object Oriented Programming with C++

UNIT -1

Definition: OOPs:-
Oops is an Object Oriented Programming which is a way to modularize programs by
creating partitioned memory area for both data and functions.

FEATURES OF OOPs:
• Emphasis is on data rather than procedure.
• Programs are divided into what are known as objects.
• Data structures are designed such that they characterize the objects.
• Functions that operate on the data of an object are ties together in the data structure.
• Data is hidden and cannot be accessed by external function.
• Objects may communicate with each other through function.
• New data and functions can be easily added whenever necessary.
• Follows bottom up approach in program design.
Organization of data and function in oops:

PROCEDURE-ORIENTED PROGRAMMING (POP)


In the procedure oriented approach, the problem is viewed as the sequence of things
to be done such as reading, calculating and printing such as Cobol, Fortran and C.

1
Object Oriented Programming with C++

FEATURES OF POPs:
• Emphasis is on doing things (algorithms).
• Large programs are divided into smaller programs known as functions.
• Most of the functions share global data.
• Data move openly around the system from function to function.
• Functions transform data from one form to another.
• Employs top-down approach in program design.

OBJECT ORIENTED Vs PROCEDURE ORIENTED


S.No Object oriented programming Procedure Oriented programming
1. The program is written as a collection of The program is written as a logical structure.
objects which communicate with each
other.
2. The basic entity is object. Each computation The flow of the execution of the object is
is performed using objects only. dependent on the structure of the program.

3. Data is given more importance. Code is given more importance.

4. Can handle very complex programs. Can handle up to moderately complex


programs.
5. More data security. Less data security.
6. More code reusability. Less code reusability.
7. Flexibility is more. Flexibility is less.
8. Abstraction is more. Abstraction is less.
9. This is a bottom up approach. This is a top down approach.

BASIC CONCEPTS OF OOPS:


2
Object Oriented Programming with C++

The basic concepts of oops are:


1. Objects
2. Class
3. Data abstraction
4. Encapsulation
5. Polymorphism
6. Inheritance
7. Dynamic binding
8. Message passing

1. OBJECTS:
 Objects are the basic run time entities.
 It has certain properties and method.
 It may represent a person, a place, a bank account, a table of data or any
item that the program has to handle.
 It may also represent user-defined data such as vectors, time and lists.
 Objects take up space in the memory and have an associated address.
 Each class can have a number of objects.

Example:
Object : Employee
Data:
Name
Address
Salary
Functions:
Working time
Total salary
Pending

2. CLASS:
 A class is a collection of objects of similar types.
 Objects are the variable of the type class.
 Class is a user defined data type.
 Once a class has been defined, we can create any number of objects to that
class.
 Each object is associated with the data of type class.

3
Object Oriented Programming with C++

 For examples, Mango, Apple and orange are members of class fruit.
 Classes are user-defined types that behave like built-in types. If fruit has been
defined as a class, then the statement
fruit mango;
will create an object mango belonging to the class fruit.
 Class is similar to structure in c.

3. DATA ABSTRACTION:
 Abstraction refers to the act of representing essential features without
including the background details or explanation.
 The attributes are sometimes called as data members.
 The functions that operate on these data are called as methods or member
function.
 The classes which use the concept of data abstraction are known as Abstract
Data Types (ADT).
Example: Flight which is invented based on the fly of birds.

4. ENCAPSULATION:
 The wrapping up of data and function into a single unit (called class) is
known as encapsulation.
 The data is not accessible to the outside world, and only those functions
which are wrapped in the class can access it.
 These functions provide the interface between the object’s data and the
program.
 This insulation of the data from direct access by the program is called data
hiding or information hiding.
5. POLYMORPHISM:
 Polymorphism is a Greek term.
 Polymorphism means the ability to take more than one form.
 It allows us to have more than one function with the same name in a
program.
 A single function name can perform the several task is called function
overloading.
 The process of making operator to exhibit different behaviours in different
instance is called operator overloading.
Example:

4
Object Oriented Programming with C++

6. INHERITANCE:
 Inheritance is the process by which objects of one class acquire the properties
of objects of another classes.
 It supports the concept of hierarchical classification.
 In OOP, the concept of inheritance provides the idea of reusability.
 This means that we can add additional features to an existing class without
modifying it.

7. DYNAMIC BINDING:

 Binding refers to the linking of a procedure call to the code to be executed in


response to the call.
 Dynamic binding or Late binding means that the code associated with a
given procedure call is not known until the time of the call at run time.
 Static binding or Early binding means that the code associated with a given
procedure call is known at the time of call at compile time.
 It is associated with polymorphism and inheritance.

8. MESSAGE PASSING:
 Objects can communicate one another by sending and receiving information.
The steps are as follow:
5
Object Oriented Programming with C++

1. Creating classes that define object and their behavior,


2. Creating objects from class definitions, and
3. Establishing communication among objects.
 Object has a life cycle. They can be created and destroyed.

BENEFITS OF OOPs

The advantages are:


1. Through inheritance, we can eliminate redundant code extend the use of existing
classes.
2. We can build programs from the standard working modules that communicate with
one another that lead to saving of development time and higher productivity.
3. The principle of data hiding helps the programmer to build secure program.
4. It is possible to have multiple instances of an object to co-exist without any
interference.
5. It is possible to map object in the problem domain to those in the program.
6. It is easy to partition the work in a project based on objects.
7. The data-centered design approach enables us to capture more detail of a model can
implemental form.
8. Object-oriented system can be easily upgraded from small to large system.
9. Message passing techniques for communication between objects makes to interface
descriptions with external systems much simpler.
10. Software complexity can be easily managed.

APPLICATIONS OF OOPS
The applications of OOPs include:
• Real-time system
6
Object Oriented Programming with C++

• Simulation and modeling


• Object-oriented data bases
• Hypertext, Hypermedia, and expertext
• AI and expert systems
• Neural networks and parallel programming
• Decision support and office automation systems
• CIM/CAM/CAD systems

PRINCIPLES OF OOP
The principles that make language Object Oriented are
 Encapsulation,
 Data Abstraction,
 Polymorphism and
 Inheritance.
OBJECT ORIENTED LANGUAGE
Based on the features, they can be classified into the following two categories:
1. Object-based programming languages, and
2. Object-oriented programming languages.
Object-based programming is the style of programming that primarily supports
encapsulation and object identity. Major feature that are required for object based
programming are:
• Data encapsulation
• Data hiding and access mechanisms
• Automatic initialization and clear-up of objects
• Operator overloading
Languages that support programming with objects are said to the objects-based
programming languages. They do not support inheritance and dynamic binding. Ada is a
typical object-based programming language.
Object-oriented programming language incorporates all of object-based programming
features along with two additional features, namely, inheritance and dynamic binding.
Object-oriented programming can therefore be characterized by the following statements:
Object-based features + inheritance + dynamic binding
Introduction of C++
 C++ is an object-oriented programming language.
 It was developed by Bjarne Stroustrup at AT&T Bell Laboratories in Murray
Hill, New Jersey, USA, in the early 1980’s.
7
Object Oriented Programming with C++

 C+ + is a superset of C.
 The most important facilities that C++ adds on to C are classes, inheritance,
function overloading and operator overloading.
Application of C++
C++ is a versatile language for handling very large programs; it is suitable for virtually any
programming task including development of editors, compilers, databases, communication
systems and any complex real life applications systems.
 C++ allows us to create hierarchy related objects.
 C++ is able to map the real-world problem properly
 C++ programs are easily maintainable and expandable.

STRUCTURE OF C++ PROGRAM


It is a common practice to organize a program into three separate files.
 The class declarations are placed in a header file.
 The definitions of member functions go into another file.
 Finally, the main program that uses the class is placed in third file which
“includes” the previous two files as well as any other file required.

Include Files
Class declaration
Member functions definitions
Main function program

 This approach is based on the concept of client-server model as shown in


below figure.
 The class definition including the member functions contain the server that
provides services to the main program known as client.
 The client uses the server through the public interface of the class.

The client-server model

8
Object Oriented Programming with C++

Documentation: It contains comment lines which give the details of the program such as
author details, created date, name of the program, etc.

// used to make the statement comment

Example: //program to add two numbers

Include files: It contains header files used as a linking section. The pre-processor directive
#include is used here.

Example: #include<iostream.h>

Class declaration and definition It is used to define and declare the class and its
members.

Example:
class a
{ int a ,b;
public:
add ()
{
int c= a+b;
}
};

Macro definition:
It is used to assign symbolic name to constants.
Example: #define pi 3.14
Global variable declarations:
Variable accessed by all function can be declared here.

int a; //global variable declaration


main ()
9
Object Oriented Programming with C++

{
// body of the main function
}

Main function : Each and every program must contain main function where each execution
starts from here.
Example:
main()

cout <<”hello”;

Steps in execution of c++ program


1. Creating the source program
2. Compiling the source program
3. Linking the program with user defined function and standard library function
4. Executing the program
The insertion operator << (Common Output - cout) :
 The insertion operator ( << ) points to the ostream object wherein the information is
inserted. A statement like :
cout << "hello" << "world";
The extraction operator >> (Common Input- cin) :
 cin is an istream object from which information can be extracted.
 This stream is normally connected to the keyboard.
 cin is used to insert the information or the value of a variable.
 This works same as scanf() works in C language.
Syntax : cin >> variable value;

A simple c++ program


Here cout<<is used for output operation, cin>> is used for input operation.

Example: #include<iostream.h>
int main()
10
Object Oriented Programming with C++

{
int a,b,c;
clrscr();
cout<<”Enter a and b value”;
cin>>a>>b;
c=a*b;
cout<<”c=”<<c;
getch();
return 0;
}

TOKENS

Each and every individual unit in C++ program is known as tokens.


Example:. Variables, constants, keyboards

Types of tokens
The tokens are classified into following types
1. Keywords
2. Constant
3. Variables
4. Special symbol
5. Operator
6. Identifies
Identifiers
 Name of the variables, functions, arrays, classes etc is said to be identifiers.
 An identifier is formed with a sequence of letters (including ‘_ ‘) and digits.
 The first character must be a letter.
 Identifiers are case sensitive, i.e., first_name is different from First_name.

Examples: Valid Identifiers: myname, jaas, name123

Invalid Identifiers

 12B Invalid variable name since its starts with a number.


 Basic pay Invalid variable name since it has a space
 ABC,1 Invalid variable name since , is a special character

Rules for naming identifiers:


1. Only alphabetic characters, digits, and underscore are permitted

11
Object Oriented Programming with C++

2. Name cannot start with a digit


3. Upper case and lower case are different
4. Declared keyword cannot be used as identifier name

Constants: Constants refer to values that do not change during the execution of the
program.

Example: 1998 Integer constant

25.789 Floating point constant

“Hello World” String constant

‘a’ Character constant

123- Decimal constant

0567- Octal constant

0x568a Hexadecimal constant

0.0083 Real constant

\a\b Backslash Character Constant

Types of the Constant

Constants

Numeric Constants Character Constants

Integer Real Single String Constants


Constants Constants Character

Constants
Decimal Octal constant Hexadecimal
constant constant

Keywords: The reserved word with fixed meaning is called keyword.

12
Object Oriented Programming with C++

Variables
 A variable is a data name that may be used to store a value.
 It will not remain constant during execution.
 It follows the same rule as identifiers naming.
Example: int a= 10
Declaration of variable: Providing variable name in program is known as variable
declaration. Before using a variable in a program we must declare it.

Syntax: data_type variable_name;

Example: float avg;


char option;
Dynamic initialization of variable: The value of the variable can be declared at run time is
said to be dynamic initialization of the variable
Example: int n= strlen(string);
float avg = sum/5;

Reference variable:
 It provides an alternative name for previously defined variables.
 A reference variable must be initialized at the time of declaration.
 A major application of reference variable is in passing arguments to function.
Syntax: datatype& reference variable= variable name;

Example: float total;


float &sum=total;

13
Object Oriented Programming with C++

Call bf reference mechanism:


The call by reference method of passing arguments to a function copies the reference of an
argument into the formal parameter.
Example:
void f(int &x)
{
x=x+10;
}
int main()
{
int m=10;
f(m);
----
}
Special symbols: The symbol such as @,&,#,(,),[,]…. are called special symbols.

Example: Stack_pop();

Operators: The symbol that perform certain logical operations are called operator.

Example: =,==,!=,<,>.

DATA TYPES

The type of the data can be determined by the data types.

1. Basic data type: The modifiers signed, unsigned, long, short may be applied to
character and integer based data type. It is also called as built in data types.

14
Object Oriented Programming with C++

Type Bytes Range


char 1 -128 to 127
unsigned char 1 0 to 255
signed char 1 -128 to 127
int 2 -32768 to 32767
unsigned int 2 0 to 65535
signed int 2 -32768 to 32767
short int 2 -32768 to 32767
unsigned short int 2 0 to 65535
signed short int 2 -32768 to 32767
long int 4 -2147483648 to 2147483647
signed long int 4 -2147483648 to 2147483647
unsigned long int 4 0 to 4294967295
Float 4 3.4 E – 38 to 3.4 E+38
double 8 1.7E – 308 to 1.7 E+ 308
long double 10 3.4 E – 4932 to 1.1 E+49-32

2. User defined data type


i. Structures
 A structure is a collection of elements of different data type.

 A structure in C++ can be declared as

struct student
{
char name[12];
int rollno;
float totmark;
};
ii. Union
 A union is a user defined data type.
 It is a collection of elements of different data type.
 Unions provide a way to manipulate different kinds of data in single area of storage.
 Unions allow only one variable to refer at a time; all union variables cannot be
accessed simultaneously.
Syntax: union u1
{
int i;
float f;
char c;
} u1;

iii. Class

15
Object Oriented Programming with C++

 A class is a way to bind the data and its associated functions together.
 The keyword ‘class’ is used to declare a class.
The general form of a class declaration is:
class class_name
{
private:
variable declarations;
function declarations;
public:
variable declarations;
function declarations;
};
Example
class item
{
int number;
float cost;
public:
void getdata(int a, flaot b);
void putdata(void);
};
iv. Enumeration Data Type
 Enumeration is another user defined type.
 It provides a way for attaching names to numbers
 The ‘enum’ keyword automatically enumerates a list of words by assigning those
values 0, 1, 2 and so on.
Syntax:
enum enum-name{enumeration values} ;
Example:
enum shapes{circle,square,triangle};
Where circle will be assigned to the value 0
square will be assigned to the value 1
triangle will be assigned to the value 2

3. Derived data type


 Array – collection of elements of same type. Example: char name[10];
16
Object Oriented Programming with C++

 Function-performs a specific task Example: add();


 Pointer- holds the address of another variable. Example: int a, *ptr; ptr=&a;

SYMBOLIC CONSTANTS
The constants which declared using the qualifier const or enum is called symbolic constant.
There are 2 ways to create symbolic constant:
1. Using the qualifier const.
2. Defining a set of integer constant using enum keyword
Example: const int size=10;
char name[size];
Example program:
#include <iostream>
const int a = 100; // Const Variable
class Test
{
public:
void display() const // Const Function
{
cout << "Value of a in the const function is " << a;
}
};
int main ()
{
Test t1;
t1.display();
cout << a;
return 0;
}
OPERATORS IN C++
It is a special symbol that performs certain logical operations. Example: +,-,*,\,<,>,<=……..
are basic operators. The operators in c++ are
1. Scope resolution operator.(::)
2. Member dereferencing operator.(::*,*=>,->*)
3. Memory management operator.(new,delete)
4. Manipulator operator,(endl, setw)
5. Typecast operator.

17
Object Oriented Programming with C++

1. Scope resolution operator:


 To access a global variable when there is a local variable with same name.
 Blocks and scope can be used in constructing program.
 The same variable name can be used to have different meaning in different
blocks.
 The scope of variable extends from the point of its declaration till the end of the
blocks.
 A variable declared inside the block is said to be local to the block.
 Scope resolution operator (::) can be used to uncover the hidden variable.
 This operator allows access to the global version of variable.
 A major application of the scope resolution operator in the classes is to identify
the class which a member function belongs.

Syntax: :: variable name;


Example:
#include<iostream.h>
int x=30; // Global x
int main()
{
int x = 10; // Local x
cout<<"Value of global x is"<<::x;
cout<<"\nValue of local x is"<< x;
return 0;
}
Output: Value of global x is 30
Value of local x is 10
Example:
#include<iostream.h>
int m=10; //global variable
void main()
{
int m=20;
{
int k=m;
int m=30;
cout<<”\n inner block”;

18
Object Oriented Programming with C++

cout<<”\n k=”<<k;
cout<<”\n m=”<<m;
cout<<”\n ::m=”<<::m;
}
cout<<”\n outer block”;
cout<<”\n m=”<<m;
cout<<”\n ::m=”<<::m;
}
Output: inner block
k=20
m=30
::m=10
outer block
m=20
::m=10
2. Member dereferencing operator :
In C++ , a class contains data and function as member, we can access class member
through pointers. Three pointers to member operator are:
a. ::*- to declare a pointer to a member of class.
b. *- to access a member using the object name and a pointer to that member.
c. ->*- to access a member using pointer to the object & a pointer to that member.
3. Memory management operator:
 New and delete are memory management operator that perform the tasks of
allocating and freeing the memory respectively.
 Also known as free store operator as these operators manipulate memory on free
store.
 An object can be created by using new and destroyed by using delete.

New: The new operator can be used to create objects of any type.

Syntax: pointer-variable= new data-type;

Here pointer-variable is a pointer of type data-type. It allocates sufficient memory to hold


a data object of type data –type and returns the address of the object.

Example: p= new int;


q= new float;
We can also initialize the memory using the new operator.

19
Object Oriented Programming with C++

pointer-variable= new data-type(value);

Example: int *p=new int (25);

Using new operator, we can create memory space for any data-type including user-
defined type such as array, structure, class.

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

Example: int *a= new int [10];


p=new int [3][4][5];
Advantages of new over malloc function:
 It automatically computes the size of the data object. We need not use the sizeof
operator
 It automatically returns the correct pointer type, so no need to use type-cast.
 It is possible to initialize the object while creating the memory space.
 New and delete can be overloaded.

Example: #include<iostream.h>
int main()
{
int *a= new int;
*a=100;
cout<<”\a=”<<*a;
delete a;
return 0;
}
delete operator: It is used to destroy the memory allocated by the new operator.

Syntax: delete ptr-variable;

Example: delete p;

To free a dynamically allocated array, use the following syntax:

Syntax: delete[size]ptr-variable;

Example: delete[]p;

4. Manipulators: Manipulators are operators that are used to format the data display.
Most commonly used manipulators are endl and setw.

20
Object Oriented Programming with C++

endl:
 used in output statement.
 moves to new line.
 Same effect as \n.

Example: cout<<”m=”<<endl<<”n=”<<endl<<”p=”<<endl;

After execution the output format will be:


m
n
p
setw:
 It specifies field width for printing a value.
 It is right justified.

Example: cout<<setw(5)<<a;

if a=123 setw will set the width as follows.

1 2 3

Type cast operator: It is used to convert the value to a selected type.


Syntax: type-name (expression);

Example: avg=sum/float(i);

ANSI C++ adds the following new-cast operators:

 const-cast  dynamic-cast
 static-cast  reinterpret-cast

EXPRESSIONS AND THEIR TYPES


The combination of operators, constant and variables are arranged as per the rules of
language to form an expression.

Example: x+y+3=0; x=4


It may also include function calls which return values.

21
Object Oriented Programming with C++

Example: a=(b+c)\3; x=sqrt(9)


It may contain one or more operands and zero or more operators to produce a value.

TYPES
1. Constant expression
2. Integral expression
3. Float expression
4. Pointer expression
5. Relational expression
6. Logical expression
7. Bitwise expression
8. Special Assignment expressions
1. Constant expression: It contains only the constant value.

Example: 15, 20+5, ’g’

2. Integral expression: After all conversions, it produces integer result.


Example: m 2*5-2 m*’x’

3. Float expression: After all conversion, this produces floating point result.
Example: x+y 5\2 5*float(10)

4. Pointer expression: It produces address value.


Example: &m Ptr Ptr+1

5. Relational expression: It produces the result as bool type which takes either zero or
one. Also known as Boolean expression.
Example: a<b a==b

6. Logical expression: It combines two or more relational expression and produces bool
type result.
Example: (a>b)&&(a>c) (x==10)||(y==5)

7. Bitwise expression: It is used to manipulate data at bit level. It is used for testing
and shifting bits.
Example: x>>3 y<<1 2&3

8. Special assignment expression:


i. Chained assignment expression
Example: x=(y=10) (Or) x=y=10
ii. Embedded assignment expression:
Example: x=(y=50)+100

22
Object Oriented Programming with C++

iii. Compound assignment expression: It is the combination of assignment operator with


a binary arithmetic operator.
Syntax: Variable1 operator = variable;
Example: x+=10 which is equal to x=x+10

IMPLICIT CONVERSION
Whenever data types are mixed in an expression, C++ performs the automatic conversion. It
is known as implicit (or) automatic type conversion.

Example: int m; m=5+2.75; where result of m will be int –data type

Waterfall model of type conversions

Operator precedence: The priority of the operator can be decided here. The groups are
listed in the order of decreasing precedence.
Operator precedence and associativity

23
Object Oriented Programming with C++

Operator overloading: It allows us to assign values multiple meaning to an operator.

Example: input /output operator >>and << are examples of operator overloading.
Operators that can’t be overloaded are:
1.Member access operator (.,.*)
2.Conditional operator (?:)
3.Scope resolution operator (::)
4.Sizeof operator (sizeof)
CONTROL STRUCTURES
To make the flow of statements control, we are using control structures .They are
1. Sequence[straight line]
2. Selection[branching\ decision making]
3. Looping[repetition\iteration]

Control structures

Selection Sequence Loop

If-else Switch Do-while While, for

Sequence structure: It executes in straight line.

24
Object Oriented Programming with C++

Selection structure: Based on certain decision, the particulars statement is executed.

Looping: Based on condition the statement must be repeated more times.

25
Object Oriented Programming with C++

DECISION MAKING STATEMENTS


‘if’ Statement: -
a. Simple ‘if’ Statement: -
Syntax : if(test condition)
{
Block Statement-1
}
Statement-2
Block Diagram

True
test Block Statement-1
condition

False

Statement-2

Example:
main()
{
int a=20,b=30;
if(a>b)
cout<<”a is greater”;
cout<<”end”;
}
b. ‘if...else’ Statement: -
Syntax:
if(test condition)
{
Block Statement-1
}
else
{
Block Statement-2
}

Block Diagram

26
Object Oriented Programming with C++

Example:
main()
{
int a=20,b=30;
if(a>b)
cout<<”a is greater”;
else
cout<<”b is greater”;
}
c. Nested ‘if...else’ Statement: -
Syntax:
if(test condition-1)
{
Block Statement-1
}
else if(test condition-2)
{
Block Statement-2
}
else if(test condition-3)
{
Block Statement-3
}
else
{
Block Statement-4
}
Statement-5
Example if(percentage >=70)
{
cout<<“Distinction\n”;
}
else if(percentage >= 60)
{
cout<<“First Class\n”;
}
27
Object Oriented Programming with C++

else if(percentage >= 50)


{
cout<<“Second Class\n”;
}
else if(percentage >=40)
{
cout<<“Pass Class\n”;
}
else
{
cout<<“Fail\n”;
}
FLOWCHART

False
test
condition-1
True

False
test
condition-2
True

False

Block Statement-1 test


condition-3
True

Block Statement-2

Block Statement-3

Block Statement-4

Statement-5

‘switch’ Statement: -
Switch case statements are used to execute only specific case statements based on the
switch expression. This is a multiple or multi-way branching decision making statement.

Syntax:
switch(variablename)
{
28
Object Oriented Programming with C++

case v1 : Block Statement-1


break;
case v2 : Block Statement-2
break;
case v3 : Block Statement-3
break;
default : Block Statement-4
break;
} Statement-5

Here if the value of variable= = v1 then ‘Block Statement-1’ will be executed. If variable= =
v2 then ‘Block Statement-2’ will be executed. If at last no match found for the variable then
default statement is executed. Here we have to put the ‘break’ statement to complete the
execution of ‘switch’ .

variable
for
match

= =V1 = =V2 = =V3 default

Block Block Block Block


Statement-1 Statement-2 Statement-3 Statement-4

Statement-5

Rules for declaring switch case:


 The case label should be integer or character constant.

 Each compound statement of a switch case should contain break statement to exit
from case.

 Case labels must end with (:) colon.

Advantages of using switch case:

 Easy to use.

 Easy to find out errors.

29
Object Oriented Programming with C++

 Debugging is made easy in switch case.

 Complexity of a program is minimized.

Consider the following example of the ‘switch’ statement

cin>>ch;
switch(ch)
{
case ‘v’:
cout<<”color is violet”;
break:
case ’i’:
cout<<”color is indigo”;
break;
case ‘b’:
cout<<”color is blue”;
break;
default:
cout<<”end”;
}

30
DECISION MAKING AND LOOPING
while statement: An entry controlled loop

Syntax: while(condition)
{
Action1;
}
Action-2;
Example:
main()
{
int i=0;
while(i<10)
{
cout<<” value of i=”<<i;
i++;
}
}
Flowchart

Do-while statement: An exit controlled loop.

Syntax:

do

Action-1;

}while(condition);

Action-2;

Example:

main()

{
int i=0;

do

cout<<’value of i=”<<i;

i++;

}while(i<10);

Flowchart

For statement: An entry controlled loop.

Syntax:
for(initialization ;condition ;inc\dec)
{
Action-1;
}
Action-2;
Example:
main()
{
int i;
for(i=0;i<10;i++)
{
cout<<value of i=”<<i;
}
}
Flowchart
UNIT- I QUESTIONS
2-marks:
1. Define oops.
2. List the basic concepts of oops.
3. What is data abstraction?
4. Define encapsulation.
5. What is polymorphism?
6. What is inheritance?
7. What is dynamic binding?
8. What are the steps involved in message passing?
9. Write the applications of oops.
10. What is c++?
11. What are the types of object oriented language?
12. What is tokens and list them?
13. Write the rules for naming identifiers.
14. Define Constant.
15. What is reference variable?
16. What is the use of scope resolution operator?
17. What are the member dereferencing operators?
18. Write the advantage of new operator.
19. Write note on control structure.
20. List the operators that cannot be overloaded.

5/10-marks:
1. Write note on features of oops.
2. Differentiate between pop and oop.
3. Write note on benefits of oops.
4. Write note on structure of c++ with an example program.
5. Write note on tokens.
6. Write note on data types.
7. Write note on scope resolution operator.
8. Write note on expression.
9. Write note on looping statements.
10. What are the basic concepts of oops? Explain them.
11. Explain operators in c++.
12. Write on memory management operators with an example.
13. Explain control structures in details.

UNIT-II

FUNCTION:

 Functions are reusable code segment that perform specific task.


 Functions are the basic building blocks of C++.
 Functions provide modular structure to a program.
 Functions help to divide a larger program into number of smaller units which is the
basis of top down approach.
Advantages of Functions
 Functions provides Reusability
 Reduce the size of program
 Functions give modular structure to a program
 Writing functions make programming easy

Need for a Function


 A larger program becomes difficult to understand.
 For this reason functions are used.
 Reduction in program size is another reason for using functions.
 The functions code is stored in only one place in memory, even though it may be
executed as many times as a user needs.
The main function:
 The main( ) function is the starting point for the execution of a program.
 The definition of main( ) is
main( )
{
main program statements
}
 In C++, the main( ) returns a value of int to the operating system.
 The functions that have a return value should use the return statement for termination.
 The main( ) function in C++ is defined as,
int main( )
{
………
………
return 0;
}

Function Prototype:

 Function Prototype is a declaration statement in the calling program.


 It gives the details such as number, type of argument & its return type.
 When a function is called, compiler ensures that proper argument & return type is
returned correctly.

Syntax: type fun-name(argument list);

Example: float volume(int, flo; at h, float r);

The function can be called using the syntax fun-name(argument values);

Example: volume(10, 12.5, 25.5)


Function definition as the following general form.
Syntax: type function name (argument list)
{
function body
}
Example: float volume(int a, float b,float c)
{
float v=a*b*c;
return;
}
CALL BY REFERENCE

 Function call which passes argument by reference is known as call by Reference.


 When we pass arguments by reference, the formal arguments in the called function
becomes aliases to the actual argument in the calling function.
 This means that when the function working with its own arguments, it is actually working
on the original data.
Example:
void swap(int &a,int &b)
{
int t=a;
a=b;
b=t;
}
The function call: swap(m,n);
where m&n are integer variable which might exchange the value of m&n using the reference
variable a&b.

Function definition:
void swap(int *a,int *b)
{
int t;
t=*a;
*a=*b;
*b=*t
}
This can be called by swap (&x ,&y) ; //call by passing address of variable.
RETURN BY REFERENCE: Function can also return a reference.
#include <iostream>
int num; // Global variable
int& test(); // Function declaration
int main()
{
test() = 5;
cout << num;
return 0;
}
int& test()
{
return num;
}
Output
5

In program above, the return type of function test() is int&. Hence, this function returns a reference
of the variable num.
The return statement is return num;. Unlike return by value, this statement doesn't return value of
num, instead it returns the variable itself (address).
So, when the variable is returned, it can be assigned a value as done in test() = 5;
This stores 5 to the variable num, which is displayed onto the screen.

INLINE FUNCTION
An inline function is a function that is expanded in a line when it is invoked.
Syntax:
inline function - header
{
function body
}
Example:
inline double cube(double a)
{
return (a*a*a);
}

This inline function can be invoked as c= cube (3.0);


d= cube (2.5+1.5);
 All inline function must be defined before they called.
 The inline keyword sends a request not a command to the compiler.
 The compiler may ignore the request if the function definition in too complicated and
compiler treat it as normal function.

The inline function does not work for the following situations:
 For functions returning values and having a loop or a switch or a goto statement.
 For functions that do not return value and having a return statement.
 For functions having static variable(s).
 If the inline functions are recursive (i.e. a function defined in terms of itself).

Advantage of inline function:


 Better than a macro.
 Function call overheads are eliminated.
 Program becomes more readable.
 Program executes more efficiently.
Example:
#include<iostream.h>
#include<conio.h>
inline float mul(float x,float y)
{
return(x*y);
}
inline float cube(float x)
{
return(x*x*x);
}
void main()
{
float a=2.0;
float b=3.0;
clrscr();
cout<<"\nMultiplication value is:"<<mul(a,b);
cout<<"\n\nCube value is :"<<cube(a)<<"\t"<<cube(b);
getch();
}
Output:
Multiplication Value is: 6.00
Cube Value is: 8.000 and 9.000

DEFAULT ARGUMENT
 A default parameter is a function parameter that has a default value provided in
function declaration that is automatically assigned by the compiler if the function call
doesn’t provide a value for the argument.
 The function assigns a default value to the parameter which does not have a matching
argument in the function.
 Default values are specified when the function is declared.

For Example consider the following function declaration.

int add(int x , int y=100,int z=200);


Here we can note that the default value to the parameter is assigned as an ordinary variable
initialization. Thus all the function calls given below are valid.

m=add(15); //two argument missing


m=add(10,20); //one argument missing
m=add(10,20,30)
The following point has to be noted while writing functions with default arguments.
 A function can take default arguments only as indicated in the previous
Example (int y =100 is a default parameter)
 A default parameter is used only when a parameter is missing.
 Default parameters should be assigned from right to left.
The following function declarations are wrong
int add(int x=100,int y,int z) //default parameters should be assigned from left to right
int add(int x,int y=100,int z) //default parameters should be assigned from left to right
Examples
int mul(int i, int j=5, int k=10); // legal
int mul(int i, int j=5, int k); // illegal
int mul(int i=3, int j=5, int k=10); // legal
int mul(int i=3, int j, int k=10); // illegal
Advantages:
 We can use default argument to add new parameter to the excession.
 Default argument can be used to combine similar function into one.

Example: #include<iostream.h>
int main()
{
float amt;
float value (float p,int n,float r=0.15);
amt = value(500.0,5)
cout<<"final value ="<<amt;
return 0;
}
float value(float p, int n,float r);
{
float sum;
sum =p*n*r;
return(sum);
}
Output: final value=375

CONST ARGUMENT

 A C++ function may have constant arguments.


 These arguments are treated as constant.
 These values cannot be modified by the function.
 For making the arguments constant to a function, an argument to a function can be
declared using the keyword const in the function prototype.
 The qualifier const tells the compiler that the function should not modify the argument.
 If you are changing the argument it will show an error.
 This argument should be a pointer (or) reference argument.
Example: int strlen(const char *p);

FUNCTION OVERLOADING

 Overloading refers to the use of same things for different purpose.


 Function overloading means that the use of same function name to create a function that
performs different tasks.
 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.
 The number of parameters
 The data type of parameters
 The order of appearance
 These three together are referred to as the function signature.
Example: int add (int);
float add();
double add (int , int);
Example:
#include<iostream.h>
int add(int);
float add (int,float);
float add (int,float,float);
int main()
{
cout<<add(10)<<endl;
cout<<add(2,3.5) <<endl;
cout<<add(2,2.5,2.5) <<endl;
return 0;
}
int add (int a)
{
return (a+10);
}
float add (int a,float b)
{
return(a*b);
}
float add (int a,float b,float c()
{
return(a+b+c);
}

MATH LIBRARY FUNCTION


The most used math functions are included under the header file math.h. Few are
CLASS AND OBJECT
What is a class ?
 Class is a collection of similar types of objects
 Class consists of Data members and methods.
 A class is an abstract data type similar to 'C' structure.
Specifying a Class

 A class is a way to bind the data and its associated functions together. A class
specification has two parts:

1. Class declaration
2. Class function definitions
 The class declaration describes the type and scope of its members.
 The class function definitions describe how the class functions are implemented.
 In the class declaration, member functions and variables can be given different
access restrictions:
public: access from any function,
protected: access from this class’s and sub-class functions only,
private: access from this class’s functions only,

The general form of a class declaration is:


class class_name
{
private:
variable declarations;
function declarations;
public:
variable declarations;
function declarations;
};

 The class declaration is similar to a struct declaration.


 The body of a class is enclosed within braces and terminated by a semicolon.
 The class body contains the declaration of variables and functions. These functions
and variables are collectively called class members.
 The class members are usually grouped under two sections private and public.
These keywords private and public are known as visibility labels. These keywords
are followed by a colon.
 The class members that have been declared as private can be accessed only from
within the class.
 The public members can accessed from outside the class also.
 The use of the keyword private is optional.
 By default the members of a class are private.
 The variables which declared inside the class are known as data member.
 The functions which declared inside the class are called as member functions.
 The binding of data and functions together into a single class-type is referred to as
encapsulation.

Data Hiding of a Class

Example:
class A
{
int a,b;
pubilc:
void add()
{
int c=a+b
}
};
Creating Objects
 Once a class has been declared, we can create variables of that type by using the class
name.
 The declaration of object in C++ is similar to declaration of variables .
 To create an object; use the class name as type specifier.
Syntax: <class name> objectname ;
Example: item x;

Creates a variable x of type item. In C++, class variables are known as objects. Therefore x
is called an object of type item. It may possible to declare more than one object in one statement.
Example: item x, y, z;

Accessing Class Members

Once an object of a class has been created, the program can reference its public members by
using the dot operator in the same way as that structure members are accessed.

Syntax: object name . functionname(arguments);


objectname.variablename;
The class members can be accessed by using dot operator.
Example: x.getdata(100, 56.6);
x.putdata( );
MEMBER FUNCTION
The function within a class is said to be member function. The member functions can be
defined in two places:
1.Inside class definition
2.Outside class definition
Inside Class Definition:
 When a member function is defined inside a class, we do not require placing a membership
label along with the function name.
 We use only small functions inside the class definition and such functions are known as
inline functions.

Example:
class item
{
int number;
public:
void getdata(int a);
void putdata()
{
cout<<number<<endl;
}
};
Outside Class Definition:
 Member functions that are declared inside a class have to be defined separately outside the
class. Their definitions are very much like normal functions.
Syntax
return_type class-name::function_name (argument list)
{
Function body
}
Here the operator :: is known as scope resolution operator helps in defining the member
function outside the class.
Example:
void item:: getdata(int a)
{
number=a;
}
void item:: putdata()
{
cout<<number<<”\n”;
}
Characteristics of member functions
 Several different classes can use the same function name. The ‘membership label’ will
resolve their scope.
 Member functions can access the private data of the class. A non-member function cannot
do so.
 A member function can call another member function directly, without using the dot
operator.
Example Program Using Class and Object:
# include<iostream.h>
class test
{
int x;
pubilc:
void get() // Function defined inside class
{
cin>>x;
}
void dis();
};
void test :: dis() // Function defined outside class
{
cout<<"x="<<x;
}
int main()
{
integer obj;
cout<<"Enter a value";
obj.get();
obj.dis();
return 0;
}

Output: Enter a value 36


x=36

Making an outside function Inline


We can define a member function outside the class definition and still make it inline by just
using the qualifier inline in the header line of function definition.
Syntax:
inline return type class name:: function name(arg)
{
function body;
}
Example:
class item
{
----
pubilc:
void get data(int,int); //declaration
};
inline void:: item get data (int x,int y) //definition
{
a=x;
b=y;
}

NESTING OF MEMBER FUNCTION


A member function can be called by using its name inside another member function of the same
class. This is known as nesting of member functions.
Example: #include <iostream.h>
class set
{
int m,n;
public:
void input(void);
void display(void);
void largest(void);
};
int set :: largest(void)
{
if(m >= n)
return(m);
else
return(n);
}
void set :: input(void)
{
cout << "Input value of m and n"<<"\n";
cin >> m>>n;
}
void set :: display(void)
{
cout << "largest value=" << largest() <<"\n"; //nesting of member function
}
int main()
{
set A;
A.input();
A.display();
return 0; }
PRIVATE MEMBER FUNCTION
 The member function which is declared in private section is called as Private member
function.
 A private member function can only be called by another function that is a member of its
class.
 Even an object cannot invoke a private function using the dot operator.
Example class sample
{
int m;
void read(void);
public:
void update(void);
void write(void);
};
If s1 is an object of sample, then
s1.read(); //won’t work; objects cannot access private members
The function read() can be called by the function update() to update the value of m.
void sample:: update()
{
read(); //simple call; no object used
}
ARRAY WITHIN A CLASS
We can declare an array inside a class as its member.
Example:
#include<iostream.h>
const int m=5;
class array
{
int a[m]; //Array within Class
public:
void setval(void);
void display(void);
};

void array : :setval( )


{
cout<<”Enter Elements”;
for(int i=0;i<=m;i++)
{
cin>>a[i];
} }
void array : :display( )
{
cout<<”Array Elements are”;
for(int i=0;i<=m;i++)
{
cout<<a[i];
}}
int main( )
{
array obj;
obj.setval( );
obj.display( );
return 0;
}
OUTPUT:
Enter Elements
4
3
2
1
5
Array Elements are
4
3
2
1
5
ARRAY OF OBJECTS
Array of variable that are of the type class are called as array of objects.

Syntax: class_ type array_name[size];

Example:
#include<iostream.h>
class item
{
char sname[10]; // Character Array within Class
public:
void getdata();
void putdata();
};
void item::getdata()
{
cin>>sname;
}
void item::putdata()
{
cout<<sname<<"\n";
}
int main()
{
item a[5]; // Array of objects
cout<<"Enter 5 student names";
for(int i=0; i<5; i++)
a[i] .getdata();
cout<<"Entered names are";
for(int i=0; i<5; i++)
a[i].putdata();
return 0;
}

Output
Enter 5 student names
Arun
Kavi
Jaas
Sri
Ram
Entered names are
Arun
Kavi
Jaas
Sri
Ram

MEMORY ALLOCATION FOR OBJECTS


 The memory space for object is allocated when they are declared and not when the class is
specified.

 Since all the objects belonging to that class use the same member functions, no separate
space is allocated for member functions when the objects are created.

 Memory space is allocated separately to each object for their data members because
member variables store different values for different objects of a class.

STATIC DATA MEMBERS


A data member of a class can be qualified as static.
Characteristics of Static Data Member
 It is initialized to zero when the first object of its class is created. No other initialization is
permitted.
 Only one copy of that member is created for the entire class and is shared by all the objects
of that class, no matter how many objects are created.
 It is visible only within the class, but its lifetime is the entire program.
 Static variables are normally used to maintain values common to the entire class.
Example
#include <iostream.h>
class item
{
static int count;
int number;
public:
void getdata(int a)
{
number = a;
count ++;
}
void getcount(void)
{
cout << "Count: ";
cout << count <<"\n";
}
};
int item :: count;
int main()
{
item 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();
return 0;
}
Output
Count: 0
Count: 0
Count: 0
After reading data
Count: 3
Count: 3
Count: 3
STATIC MEMBER FUNCTIONS
Like static member variable, we can also have static member function. A member function that is
declared static has the following properties:
• A static function can have access to only static members declared in the class.
• A static member function can be called the class name as follows:
class-name :: function-name();
Example:
#include <iostream.h>
class test
{
static int count; //static member variable
int code;
public:
void setcode()
{
code=++count;
}
void showcode(void)
{
cout << "object number:"<<code<<’\n”;
}
static void showcount(void) //static member function
{
cout << “count:”<<count <<"\n";
}
};
int test :: count;
int main()
{
test t1,t2;
t1.setcode();
t2.setcode();
test::showcount(); //accessing static function
test t3;
t3.setcode();
test::showcount();
t1.showcode();
t2.showcode();
t3.showcode();
return 0
}
Output
Count: 2
Count: 3
object number: 1
object number: 2
object number:3

OBJECTS AS FUNCTION ARGUMENTS

Like any other data type, an object may be used as a function argument. This can be done
in two ways:
 A copy of the entire object is passed to the function (Pass by Value)
 Only the address of the object is transferred to the function (Pass by Reference)

Example:

include<iostream.h>
class test
{
int a,b,c;
public:
void getdata()
{
cout<<”Enter a and b values:”;
cin>>a>>b;
}
void sum(test);
};
void test::sum(test t)
{
c=t.a+t.b;
cout<<”Sum=”<<c;
}
int main()
{
test x,y;
x.getdata();
y.sum(x); // object as function argument by pass by value method
return 0;
}

FRIEND FUNCTION
 C++ allow the common function to be made friendly with both the classes thereby
allowing the function to have access to the private data of these classes such a function
need not be a member of these classes.
 To make on outside function friendly to a class we have to simply declare this function as
a friend of the class as shown below.
 The function declaration should be preceded by the keyword friend. The function
definition does not use either keyword friend or the scope operator ::
 The functions that are declared with the keyword friend are known as friend
functions.
 A function can be declared as a friend in any number of classes.
Syntax:
class ABC
{
.....
.....
public:
.....
.....
friend void xyz(void);
};
Special Characteristics of Friend Functions
 The function that is declared as friend will not fall in the scope of the class it was declared.
 A friend declaration can be placed in either the private or the public part of a class
declaration
 Like a member function, a friend function is explicitly declared in the declaration of the
class of which it is a friend
 A friend function can access private data members of that class.
 A friend function will be called without the object.
 Usually friend function takes object as an argument.
Example:

include<iostream.h>
class sample
{
int a,b;
public:
void set()
{
a=10;
b=20;
}
friend int dis(sample s);
};
int dis (sample s)
{
return int(s.a+s.b);
}
int main()
{
sample x;
x.set();
cout<<"sum ="<<dis(x);
return 0;
}
OUTPUT sum =30
FRIEND FUNCTION BETWEEN CLASSES
In C++ it is possible to declare member function of one class as a friend function of other class in
this case we say that the two classes are friendly to each other and this concept is called as friend
class.
This can be specified as
class Z
{
……
friend class X; // all member functions of X are friends to Z.
…….
};
To create friendly classes need to create a function that is friend to both the classes. Further we
need to do forward declaration of the class that is going to define later.
Example:
#include <iostream.h>
class ABC; // forward declaration
class XYZ
{
int x;
public:
void setvalue(int i)
{
x = i;
}
friend void max( XYZ, ABC);
};
class ABC
{
int a;
public:
void setvalue( int i)
{
a = i;
}
friend void max(XYZ, ABC);
};
void max ( XYZ m, ABC n) // Definition of friend
{
if (m.x >= n.a)
cout << m.x;
else
cout <<n.a;
}
int main (void)
{
ABC abc;
abc.setvalue(10);
XYZ xyz;
xyz.setvalue(20);
max(xyz,abc);
return 0;
}
Output
20

RETURNING OBJECTS

A Function can not only receive objects as arguments but also can return objects.
First, declare the function as returning a class type. Second, return an object of that type using
the normal return statement.
Example
#include<iostream.h>
class complex
{
float x;
float y;
public:
void input(float a, float b)
{
x=a;
y=b;
}
friend complex sum(complex,complex);
void show(complex);
};
complex sum(complex c1, complex c2)
{
complex c3;
c3.x = c1.x+c2.x;
c3.y=c1.y+c2.y;
return(c3);
}
void complex :: show(complex c)
{
cout<<c.x<<”+”<<c.y<<”\n”;
}
int main( )
{
complex A, B, C;
A.input(3.1,5.6);
B.input(2.7,1.2);
C=sum(A,B);
cout<<”A=”;
A.show(A);
cout<<”B=”;
B.show(B);
cout<<”C=”;
C.show(C);
return 0;
}
Output
A= 3.1+5.6
B=2.7+1.2
C=5.8+6.8
CONST MEMBER FUNCTIONS
 Class member functions may be declared as const. When this is done, that method
cannot modify the object that invokes it.
 The purpose of declaring a member functions as const is to prevent it from modifying
the object that invokes it.
Example
int fun() const;
void mul(int,int) const;

POINTERS TO MEMBERS
 Pointers to members allow referring to non-static members of class objects.
 It is possible to take the address of a member of a class and assign it to pointer.
 The address of a member can be obtained by applying the operator & to a fully
qualified class member name.
 A class member pointer can be declared using the operator ::* with the class name.
Example
class A
{
int m;
public:
void show( );
};
 We can define pointer to member m as
int A ::* ip=&A::m
 The ip is act as class member in that it must be invoked with class object.
A::* means pointer to member of class A.
&A::m means the address of m member of class A.
 The dereferencing operator ->* is used to access a member when we use pointer to both
object and the member.
 The dereferencing operator .* is used when the object itself used with member pointer.
(Objectname .* pointer- to- member function) (10)
(pointer-to-object) ->* pointer-to-member function) (10)
Example
#include<iostream.h>
class data
{
public:
int a;
void print()
{
cout<<”a=”<<a;
}
};
int main()
{
data d, *dp;
dp=&d; // pointer to object
int data :: *ptr=&data ::a; //pointer to data member
d.*ptr=10;
d.print();
dp->*ptr=20;
dp->print();
return 0;
}
OUTPUT
a=10
a=20
LOCAL CLASSES
Classes that are defined and used inside a function or a block are called local classes.

Example:
void test(int a)
{
--------
---------
class stud
{
-----
------
};
stud s1(a);
-----
-----
}
CONSTRUCTOR
 A constructor is a special member function whose name is same as class name and its task
is to initialize the object of its class.
 The constructor is invoked whenever an object of its associated class is created. It is called
constructor because it constructs the values of data members of the class.
Syntax:

class A
{
-------
------
public:
A(); // constructor
--------
--------
}
A constructor function have some special characteristics
 It should have the same name as that of the class.
 It should not have any return type.
 Constructors can take default arguments
 Constructors can be dynamically initialized.
 Constructors cannot be virtual
 It should be declared in the public section.
 Constructors are invoked automatically when the objects are created.
 They cannot be inherited.
Types of constructor:
1. Default constructors
2. Parameterized constructors
3. Copy constructors

Default Constructor: A constructor with no argument is called as the default constructor.


Example:
#include<iostream.h>
class A
{
int x;
public:
A() //Default Constructor
{
x=10;
}
void dis()
{
cout<<x;
}
};
int main()
{
A a;
a.dis();
return 0;
}
Output: 10
Parameterized Constructor: A constructor with arguments is called as parameterized
constructor. This can be done in two ways:
 By calling constructor explicitly
 By calling constructor implicitly
Example

A a=A(0,100); // explicit call


A a(0,100); // implicit call

Syntax:
A(type arg1,type arg2,.........type arg n)
{
member1=arg1;
member2 =arg2;
-----
-----
member n=arg n;
}
Example:
#include<iostream.h>
class A
{
int x;
public:
A(int y) //parameterized constructor
{
x=10;
}
void dis ()
{
cout<<x;
}
};
int main()
{
A a(10),b(20);
a.dis();
b.dis();
return 0;
}
OUTPUT 10
20
Copy Constructor: A constructor which initializes an object with another object is called as copy
constructor. The constructor takes a reference to the class type &the values of the members of the
reference object are assigned to the member of the class.
General Form
A(A&a)
{
statement;
}
Example:
#include<iostream.h>
class A
{
int x;
public:
A(A&a) //copy constructor
{
x=a.x;
}
A(int y) //parameterized constructor
{
y=x;
}
void dis()
{
cout<<x;
}
};
int main()
{
A b(10),c(20);
b.dis();
c.dis();
return 0;
}
Dynamic Constructor:
The constructor which allocates memory and initialized object during run time is called
dynamic constructor.

Example:
class vector
{
int *a;
public:
vector (int n)
{
a=new int [n];
}
};
MULTIPLE CONSTRUCTORS IN A CLASS/ OVERLOADED CONSTRUCTOR
A class can have more than one constructor when used a proper constructor will be in depending
on the signature of the constructor.

Example:
#include<iostream.h>
class A
{
int x;
public:
A() //default constructor
{
x=10;
}
A(int y) //parameterized constructor
{
x=y;
}
A(A&a) //copy constructor
{
x=a.x;
}

void dis()
{
cout<<x;
}
};
int main()
{
A b,c(20),d(c);
b.dis();
c.dis();
d.dis();
return 0;
}
const OBJECT: We may create and use constant objects using const keyword before object
declaration.
Example: const matrix X(m,n)
Whenever const objects try to invoke non-const member functions, the compiler generates error.

CONSTRUCTOR WITH DEFAULT ARGUMENT


We can also assign default arguments in a constructor function. The constructor that contains
default value to an argument is called as constructor with default argument.
Example:
class test
{
------
------
public:
test (int a, int b=30);
};
DESTRUCTOR
A destructor is a member function having same name as that of its class preceded by ~(tilde) sign
and which is used to destroy the objects that have been created by a constructor.
Characteristics of destructor:
 Never takes any arguments
 Will not return any values
 Destructors cannot be overloaded
 Destructors can be made virtual.
 Can’t be inherited
Example:
#include<iostream.h>
class test
{
public:
test ()
{
cout<<"object created\n";
}
~test ()
{
cout<<"object destroyed\n";
}
};
int main()
{
test t1 ,t2;
return 0;
}
OUTPUT:
object created
object created
object destroyed
object destroyed

UNIT –II-QUESTIONS
2 MARKS
1. What is function? Write syntax for function prototype.
2. What is inline function? Write it syntax.
3. Write the situation where inline function doesn’t work.
4. Write the advantages of inline function.
5. What is default argument? Write the advantage of the default argument.
6. What is const argument?
7. What is function overloading?
8. List few math library functions.
9. What is the use of ceil and floor functions?
10. What is class? How will you specify it?
11. What is object? How will you access class members?
12. Define data member and member function.
13. How will you define member function outside the class?
14. Write the characteristics of member function.
15. What is nesting of member function?
16. What is private member function?
17. Write the properties of static member function?
18. How will you pass object as function argument?
19. What is friend function?
20. What is const member function?
21. What is a local class?
22. What is constructor?
23. Write the characteristics of constructor.
24. What is default constructor?
25. What is parameterized constructor?
26. What is copy constructor?
27. What is dynamic constructor?
28. What is const object?
29. What is constructor with default argument?
30. What is destructor? Write its characteristics.
31. Write the difference between constructor and destructor.

5/10 marks
1. Write note on functions.
2. Explain Inline function in detail.
3. Explain default arguments.
4. Write note on function overloading.
5. Write note on classes and object.
6. Explain defining member function in detail.
7. Write note on nesting of member function.
8. Write note on array within class.
9. Write note on array of object.
10. Write note on static data member.
11. Write note on static member function.
12. Write note on object as function argument.
13. Write note on returning object.
14. Write note on pointer to members.
15. Explain constructor and its types in detail.
16. Explain multiple constructors.
17. Write note on constructor with default arguments.
18. Write note on destructor.
UNIT III
Operator overloading
 Operator overloading refers to the multiple definitions of an operator and giving special
meaning to an existing operator.
 The mechanism of giving special meaning to an operator is known as operator overloading.
Almost all operators in C++ can be overloaded, except the following few operators.
 Class member access operators ( .*)

 Scope Resolution operator ( :: )

 Size operator( sizeof)

 Conditional operator (? :)

Defining Operator Overloading

The general form of a member operator function is shown here:

return-type class-name::operator op(arg-list)

Function Body

The return type is the operator function’s return type. The operator being overloaded is
substituted for op. For example, if the operator + is being overloaded, the operator function name
would be operator +.
Operator functions must be either member functions (non-static) or friend functions.

Unary operator Binary operator

Member function No argument One Argument

Friend function One Argument Two argument

Examples:

vector operator+(vector); //vector addition

vector operator-(); //unary minus

friend vector operator+(vector, vector) //vector addition

The process of overloading involves the following steps:

 Create a class that defines the data type that is to be used in the overloading operation

 Declare the operator function operator op( ) in the public part of the class. It may be either
a member function or a friend function

 Define the operator function to implement the required operations.

Overloaded operator functions can be invoked by expressions such as

op x or x op for unary operators and

x op y for binary operators op x (or x op) would be interpreted as

operator op(x) for friend functions and

x.operator op(y) in case of member function.

OVERLOADING UNARY OPERATORS

The unary operators operate on a single operand and following are the examples of Unary
operators.

 The increment (++) and decrement (--) operators.

 The unary minus (-) operator.

 The logical not (!) operator.

Example

#include <iostream.h>
class space
{
int x, y, z;
public:
void getdata(int a, int b, int c);
void display(void);
void operator-(); //overloaded unary minus
};
void space::getdata(int a, int b, int c)
{
x=a;
y=b;
z=c;
}

void space::display(void)
{
cout<<x<<”\n”;
cout<<y<<”\n”;
cout<z<<”\n”;
}
void space:: operator-()
{
x=-x;
y=-y;
z=-z;
}
int main()
{
space S;
S.getdata(10,-20, 30);
cout<<"S:";
S.display();
-S; //activates operator-() function
cout<<"S:";
S.display();
return 0;
}
Output
S: 10 -20 30
S: -10 20 -30
OVERLOADING BINARY OPERATORS

Binary operators can be overloaded just as easily as unary operators. The same mechanism
can be used to overload a binary operator. A statement like
a = add(b, c);
can be replaced by a natural looking expression
a = b + c;

Example (Overloading + using member functions)


#include<conio.h>
class complex
{
int a, b;
public:
void getvalue()
{
cout << "Enter the value of Complex Numbers a,b:";
cin >> a>>b;
}
complex operator+(complex ob)
{
complex t;
t.a = a + ob.a;
t.b = b + ob.b;
return (t);
}
void display()
{
cout << a << "+" << b << "i" << "\n";
} };
void main()
{
clrscr();
complex obj1, obj2, result;
obj1.getvalue();
obj2.getvalue();
result = obj1 + obj2;
cout << "Input Values:\n";
obj1.display();
obj2.display();
cout << "Result:";
result.display();
getch(); }
Sample Output:
Enter the value of Complex Numbers a, b
4 5
Enter the value of Complex Numbers a, b
2 2
Input Values
4 + 5i
2 + 2i
Result
6 + 7i
Example: Overloading + using friend functions
#include<conio.h>
class complex
{
int a, b;
public:
void getvalue()
{
cout << "Enter the value of Complex Numbers a,b:";
cin >> a>>b;
}
void display()
{
cout << a << "+" << b << "i" << "\n";
}
friend complex operator +(complex,complex);
};
complex operator +(complex obj1,complex obj2)
{
complex t;
t.x=obj1.x+obj2.x;
t.y=obj1.y+obj2.y;
return t;
}
void main()
{
clrscr();
complex obj1, obj2, result;
obj1.getvalue();
obj2.getvalue();
result = obj1 + obj2;
cout << "Input Values:\n";
obj1.display();
obj2.display();
cout << "Result:";
result.display();
getch();
}
Sample Output:
Enter the value of Complex Numbers a, b
4 5
Enter the value of Complex Numbers a, b
2 2
Input Values
4 + 5i
2 + 2i
Result
6 + 7i
Rules for operator overloading
1. Only existing operator can be overloaded. New operators cannot be created.
2. The overloaded operator must have at least one operand that is of user defined data type.
3. We can’t change the basic meaning of an operator
4. Overloaded operators follow the syntax rules of the original operators. They can’t be
overridden.
5. There are some operators that can’t be overloaded.
 Class member access operators ( .*)
 Scope Resolution operator ( :: )
 Size operator( sizeof)
 Conditional operator (? :)
6. We can’t use friend functions to overload certain operators. However, member functions
can be used to overload them.
 Assignment operator =
 function call operator ()
 subscripting operator []
 class member access operator ->
7. Unary operators overloaded by means of member function take no explicit arguments and
return no explicit values, but, those overloaded by means of the friend function, take one
reference argument (the object of the relevant class).
8. Binary operators overloaded through a member function, take one explicit argument and
those which are overloaded through a friend function take two explicit arguments.
9. When using binary operators overloaded through a member function, the left hand
operand must be an object of the relevant class.
10. Binary arithmetic operators such as +,-,* and / must explicitly return a value. They must
not attempt to change their own arguments.

TYPE CONVERSIONS

Type conversion or typecasting refers to changing an entity of one data type into another. It is
used to convert one data type into another data type automatically.

Implicit Type Conversion: Implicit type conversion is an automatic type conversion by the
compiler. The type conversions are automatic as long as the data types involved are built-in types.

Example

int y;

float x=123.45;

y = x;

In this example the float variable x is automatically gets converted to int. Thus the fractional part
of y gets truncated.
Explicit Type Conversion: Automatic type conversion for user defined data types is not supported
by the compiler hence the conversion routines have to be specified explicitly. Three types of
situations might arise in the data conversion between incompatible types.
 Conversion from basic type to class type.
 Conversion from class type to basic type
 Conversion from one class type to another class type.

Basic to Class Type


This is done by using constructors in the respective classes. In these types the ‘=’ operator is
overloaded.
Example
The following program converts integer to the class type “length”
class length
{
int cm,m;
public:
length(int n) //Constructor
{
m=n/100;
cm=n%100;
}
};
void main()
{
int n;
cin >> n;
length obj = n; //Integer to class type
}
The constructor used for type conversions take a single argument whose type is to be converted.
Class to Basic Type
Overloaded casting operator is used to convert data from a class type to a basic data type.
Syntax:
operator typename()
{
statements.....
}
This function converts a class type to specified type name.
For example operator int() converts the class object to integer data type.
Conditions for a casting operator function
 It must be a class member.
 It must not specify a return type.
 It must not have any arguments.
Example
The following example cast the object of type “time” to basic data types (int and float)
class time
{
int min,sec;
public:
time(int n)
{
min = n/60;
sec=n%60;
}
operator int() //Casting Operator
{
int x;
x= min * 60 + sec;
return x;
}
operator float() //Casting Operator
{
float y;
y = min + sec/60;
return y;
}
};
void main()
{
time t1(160);
int n = t1; //Conversion
float x = t1; //Conversion
}
One Class to another Class Type
The Constructors helped us to define the conversion from a basic data type to class type and the
overloaded casting operator helped to define the conversion from a class type to basic data type.
Now to convert from one class type to another class type these both help us to do.
Example
The following program converts the class type length1 to type length2
class length2; //forward declaration
class length1
{
int m,cm;
public:
length1(int n)
{
m=n/100;
cm=n%100;
}
operator length2() //from length1 type to length2 type
{
int x= m*100 + cm;
length2 tempobj(x);
return tempobj;
}
};
class length2
{
int cm;
public:
length2(int n)
{
cm=n;
}
operator length1() //from length2 type to length1 type
{
length1 tempobj(cm);
return tempobj;
}
};
void main()
{
int x= 125;
length2 obj1(x);
length1 obj2= obj1;
}
INHERITANCE
The mechanism of deriving a new class from an old one is called inheritance (or
derivation). The old class is referred to as the base class and new one is called the derived class.
Different Forms of Inheritance
There are various forms of inheritance.
1. Single inheritance
2. Multilevel inheritance
3. Hierarchical inheritance
4. Multiple inheritance
5. Hybrid inheritance

Defining Derived Class


A derived class is defined by specifying its relationship with the base class using visibility mode.
The general form of defining a derived class is:
class derived_class : visibility_mode base_class
{
// members of derived class
};
The colon indicates that the derived_class is derived (inherits some property) from base_class.
The visibility-mode can be either private or public or protected. If no visibility mode is specified,
then by default the visibility mode is considered as private.
Single Inheritance: A derived class with only one base class is known as Single Inheritance.

Example:
#include <iostream.h>
class A
{
public:
void showA()
{
cout<<”Base Class”;
}
};
class B: public A
{
public:
void showB()
{
cout<<”\nDerived Class”;
}
};
int main()
{
B b;
b.showA();
b.showB();
return 0;
}
Output:
Base Class
Derived Class

Multilevel Inheritance: Multilevel Inheritance is a method where a derived class is derived from
another derived class.

The class A serves as base class for the derived class B which in turn serves as a base class for
derived class C. The class B is known as intermediate base class. The chain ABC is known as
inheritance path.

Example:
#include <iostream.h>
class A
{
public:
void showA()
{
cout<<”Base Class”;
}
};
class B: public A
{
public:
void showB()
{
cout<<”\nIntermediate Base Class”;
}
};
class C: public B
{
public:
void showC()
{
cout<<”\nDerived Class”;
}
};
int main()
{
C c;
c.showA();
c.showB();
c.showC();
return 0;
}
Output:
Base Class
Intermediate Base Class
Derived Class

Multiple Inheritance: Multiple Inheritance is a method by which a class is derived from more than
one base class. It allows to combine the features of several existing classes for defining new classes.

Syntax for derived a class with multiple base classes:

class D: visibility B-1, visibility B-2…

{
Body of D

where visibility may be either public or private. The base classes are separated by commas.

Example Program:

#include <iostream.h>
class M
{
int m;
public:
void getm ()
{
m=10;
}
};
class N
{
int n;
public:
void getn(int)
{
n=20;
}
};
class P: public M, public N
{
public:
void display( );
};
void P :: display(void)
{
cout<<”m=”<<m<<”\n;
cout<<”n=”<<n<<”\n;
cout<<”m*n=”<<m*n<<”\n;
}
int main ()
{
P p;
p.display( );
return 0;
}
Output
m=10
n=20
m*n=200
Hierarchical Inheritance: Hierarchical Inheritance is a method of inheritance where one or more
derived classes is derived from common base class.

Hierarchical classification of students

Example:

#include <iostream.h>
class A
{
public:
void showA()
{
cout<<”DEPARTMENT OF BCA\n”;
}
};
class B: public A
{
public:
void showB()
{
cout<<”III BCA”;
}
};
class C: public A
{
public:
void showC()
{
cout<<”II BCA”;
}
};
class D: public A
{
public:
void showD()
{
cout<<”I BCA”;
}
};
int main ()
{
B b;
b. showB();
C c;
c. showC();
D d;
d.showD();
return 0;
}
Output:
Department of BCA
III BCA
Department of BCA
II BCA
Department of BCA
I BCA
In the above example the three derived classes B, C, D uses a single base class A. Thus three classes
are inherited from a single class.
Hybrid Inheritance: "Hybrid Inheritance" is a method where one or more types of inheritance are
combined together and used.

Example:
#include<iostream>
int a,b,c,d,e;
class A
{
public:
void getab()
{
cout<<"\nEnter a and b value:";
cin>>a>>b;
}
};
class B:public A
{
public:
void getc()
{
cout<<"Enter c value:";
cin>>c;
}
};
class C
{
public:
void getd()
{
cout<<"Enter d value:";
cin>>d;
} };
class D:public B,public C
{
public:
void result()
{
getab();
getc();
getd();
e=a+b+c+d;
cout<<"\n Addition is :"<<e;
}
};
int main()
{
D d1;
d1.result();
return 0;
}
Output
Enter a and b value: 5 10
Enter c value: 15
Enter d value: 20
Addition is :50
VIRTUAL BASE CLASS
 When two or more objects are derived from a common base class, we can prevent
multiple copies of the base class being present in an object derived from those
objects by declaring the base class as virtual when it is being inherited. Such a base
class is known as virtual base class.
 This can be achieved by preceding the base class’ name with the word virtual.
 The duplication of inherited members due to multiple paths can be avoided by
making the common base class as virtual base class.

Example:
class A
{
public:
int i;
};
class B : virtual public A
{
public:
int j; };
class C: virtual public A
{
public:
int k;
};
class D: public B, public C
{
public:
int sum;
};
int main()
{
D ob;
ob.i = 10; //unambiguous since only one copy of i is inherited.
ob.j = 20;
ob.k = 30;
ob.sum = ob.i + ob.j + ob.k;
cout << “Value of i is : ”<< ob.i<<”\n”;
cout << “Value of j is : ”<< ob.j<<”\n”;
cout << “Value of k is :”<< ob.k<<”\n”;
cout << “Sum is : ”<< ob.sum <<”\n”;
return 0;
}
Abstract Base classes (C++ only)
An abstract class is one that is not used to create objects.
An abstract class is a class that is designed to be specifically used as a base class. An
abstract class contains at least one pure virtual function. We declare a pure virtual function by
using a pure specifier (= 0) in the declaration of a virtual member function in the class declaration.

Example of an abstract class:

class AB

{
public:

virtual void f() = 0;

};

Function AB::f is a pure virtual function. A function declaration cannot have both a pure
specifier and a definition.

Polymorphism
Polymorphism means ‘one name having multiple forms’. The polymorphism
implementation in C++ can be shown as

Static Polymorphism or Compile Time Polymorphism


Static polymorphism refers to the binding of functions that is the associated function call is
made at the time of compilation is called compile time polymorphism.

It is also called early binding because the calls are already bound to the proper type of
functions during the compilation of the program or static binding or static linking.

Compile time polymorphism is implemented using the overloaded functions or operators.

Dynamic Polymorphism
The associated function call is made dynamically at runtime is called run time
polymorphism.

It is also called late or dynamic binding.

Run time polymorphism is implemented using the virtual functions.

Pointer
A pointer is a variable whose value is the address of another variable. Like any variable or
constant, we must declare a pointer before we can work with it.
General form of a pointer variable declaration:
type *var-name;

Here, type is the pointer's base type; it must be a valid C++ type and var-name is the name
of the pointer variable.
Example:
int *ip; // pointer to an integer
double *dp; // pointer to a double
float *fp; // pointer to a float
char *ch // pointer to character
Example program:
#include <iostream.h>
int main ()
{
int var = 20; // actual variable declaration.
int *ip; // pointer variable
ip = &var; // store address of var in pointer variable
cout << "Value of var variable: ";
cout << var << endl;
cout << "Address stored in ip variable: ";
cout << ip << endl;
cout << "Value of *ip variable: ";
cout << *ip << endl;
return 0;
}
Output:
Value of var variable: 20
Address stored in ip variable: 0xbfc601ac
Value of *ip variable: 20

this Pointer
 C++ uses a unique keyword called this to represent an object that invokes a
member function.

 this is a pointer that points to that object for which this function was called.

 this pointer is automatically passed to a member function when it is called.

Example program:
#include<iostream>
class This_Pointer
{
int a;
public:
void setData(int a)
{
this->a = a;
}

void printData()
{
cout<<"The value of a is"<<a<<endl;
}
};
int main()
{
This_Pointer tp;
tp.setData(10);
tp.printData();
return 0;
}
Output:-
The value of a is 10
Explanation of the program
In this program, the 'a' is a private member of the class This_Pointer. Also, the arguments received
by the member function printData() is also a. Hence, if we do not use this pointer explicitly both
the 'a' will be considered as data members.

VIRTUAL FUNCTIONS
 Polymorphism mechanism is supported in C++ by the use of virtual functions.
 The concept of virtual function is related to the concept of dynamic binding. The term
Binding refers to binding of actual code to a function call.
 Dynamic binding also called late binding is a binding mechanism in which the actual
function call is bound at run-time and it is dependent on the contents of function pointer at
run time.
 A virtual function is a function in a base class that is declared using the keyword virtual.
 When we use the same function name in both the base and derived classes, the function in
base class is declared as virtual using the keyword virtual preceding its normal declaration.
 When a function is made virtual, c++ determines which function to use at run time based
on the type of object pointed to by the base pointer rather than the type of the pointer. Thus
by making the base pointer to point to different objects to execute different versions of the
virtual functions.
Example Program:
#include<iostream.h>
class Base
{
public:
void display( )
{
cout<<”\n Display Base”;
}
virtual void show( )
{
cout<<”\n Show Base”;
}
class Derived : public Base
{
public:
void display( )
{
cout<<”\n Display Derived”;
}
void show( )
{
cout<< “\n Show Derived”;
}
};
int main( )
{
Base B;
Derived D;
Base *bptr;
cout<<”\n bptr points to Base\n”;
bptr=&B;
bptr -> display( );
bptr -> show( );
cout<<”\n bptr points to Derived\n”;
bptr=&D;
bptr -> display( );
bptr -> show( );
return 0;
}
Output:
bptr points to Base
Display Base
Show Base
bptr points to Derived
Display Base
Show Derived
Rules for virtual functions:
1. The virtual functions must be members of some class
2. They cannot be static members
3. They are accessed by using object pointer
4. A virtual function can be a friend of another class
5. A virtual function in a base class must be defined, even though it may not be used.
6. The prototype of the base class version of a virtual function and all the derived class
versions must be identical.
7. We cannot have virtual constructor but we can have virtual destructor.
8. While a base pointer can point to any type of the derived object, the reverse is not true.
9. When a base pointer points to a derived class, it will not make it to point to the next object
of the derived class.
10. If a virtual function is defined in the base class, it need not be necessarily redefined in the
derived class.
Pure Virtual Functions:
A virtual function equated to zero is called a pure virtual function. It is a function declared
in a base class that has no definition relative to the base class. Such functions are called as “do-
nothing” function.
A class containing pure virtual function called an abstract class.

Example:
virtual void display ( ) = 0;

UNIT –IV
MANAGING CONSOLE I/O OPERATIONS

C++ STREAM
 A stream is a sequence of bytes.
 It represents a device on which input and output operations are performed.
 It can be represented as a source or destination of characters of indefinite length.
 It is generally associated to a physical source or destination of characters like a disk file,
keyboard or console.
 C++ provides standard iostream library to operate with streams.
 Input Stream: The source stream that extracts data from input device and provides that to
the program.
 Output Stream: The destination stream that receives output from the program and can be
sent to the output device.

C++ STREAM CLASSES


The C++ I/O system contains a hierarchy of classes that are used to define various streams to
deal with both the console and disk files. The classes are called stream classes.
 ios acts as a base class for istream, ostream, streambuf.
 streambuf is a pointer and istream ,ostream acts as a base class for the derived class
iostream.
 Here iostream can inherit the attributes of ios through istream and ostream.
 To avoid the duplication ios must be declared as virtual base class assign and
iostream_withassign adds the assignment operator function to these classes.

UNFORMATTED I/O OPERATIONS


These input / output operations are in unformatted mode. The following are operations of
unformatted consol input / output operations:

A) get()

It is a method of cin object used to input a single character from keyboard. But its main
property is that it allows wide spaces and newline character.
Syntax: char c=cin.get();
Example:
#include<iostream>
int main()
{
char c=cin.get();
cout<<c<<endl;
return 0;
}
Output
a

B) put()

It is a method of cout object and it is used to print the specified character on the screen or
monitor.
Syntax: cout.put(variable / character);

Example
#include<iostream>
int main()
{
char c=cin.get();
cout.put(c); //Here it prints the value of variable c;
cout.put('c'); //Here it prints the character 'c';
return 0;
}
Output
a

C) getline(char *buffer,int size)


This is a method of cin object and it is used to input a string with multiple spaces.

Syntax:
char x[30];
cin.getline(x,30);
Example
#include<iostream>
int main()
{
cout<<"Enter name :";
char c[10];
cin.getline(c,10); //It takes 10 charcters as input;
cout<<c<<endl;
return 0;
}
Output
Enter name: kaviyarasi
kaviyarasi

D) write(char * buffer, int n)


It is a method of cout object. This method is used to read n character from buffer variable.
Syntax: cout.write(x,2);
Example
#include<iostream>
int main()
{
cout<<"Enter name : ";
char c[10];
cin.getline(c,10); //It takes 10 charcters as input;
cout.write(c,9); //It reads only 9 character from buffer c;
return 0;
}
Output
Enter name: kaviyarasixxxx
kaviyarasi

E) cin
It is the method to take input any variable / character / string.

Syntax: cin>>variable / character / String / ;

Example:

#include<iostream>
int main()
{
int num;
char ch;
string str;
cout<<"Enter Number"<<endl;
cin>>num; //Inputs a variable;
cout<<"Enter Character"<<endl;
cin>>ch; //Inputs a character;
cout<<"Enter String"<<endl;
cin>>str; //Inputs a string;
return 0;
}
Output
Enter Number
07
Enter Character
h
Enter String
Jaas
F) cout
This method is used to print variable / string / character.
Syntax: cout<< variable / charcter / string;
Example:
#include<iostream>
int main()
{
int num=100;
char ch='X';
string str="Jaas";
cout<<"Number is "<<num<<endl; //Prints value of variable;
cout<<"Character is "<<ch<<endl; //Prints character;
cout<<"String is "<<str<<endl; //Prints string;
return 0;
}
Output
Number is 100
Character is X
String is Jaas

FORMATTED CONSOLE INPUT OUTPUT OPERATIONS

In formatted console input output operations we uses following functions to make output in
perfect alignment. These functions are available in header file <iomanip.h>. iomanip refers input
output manipulations. These features include
 ios class functions and flags
 Manipulators
 User-defined output functions
ios class function and flags
Function Task
To specify the required field size for displaying
width( )
output values
To specify the number of digits to be displayed
precision( )
after the decimal point of a floating value.
To specify a character that is used to fill the
fill( )
unused portion of a field
To specify format flags that can control the form
setf( )
of output display (left & right justification)
unsetf( ) To clear the flags specified
1. width( )

To specify the required field size for displaying an output values


Syntax: cout.width(w); where w is the field width.
Example
cout.width(5);
cout<<534;
cout.width(4);
cout<<23
Output
5 3 4 2 3
2. precision( )

To specify the number of digits to be displayed after the decimal point of a floating value.

Syntax: cout.precision(d); Where d is the number of digits to the right of the decimal point.

Example
cout.precision(3);
cout<<23.465765<<”\n”;
cout<<3.20032<<”\n”;
Output
23.466(rounded to the nearest cent)
3.2(no trailing zeros)
Example
cout.precision(2);
cout.width(5);
cout<<1.2454;
Output
1 2 3
3. fill( )
To specify a character that is used to fill the unused portion of a field with certain character.

Syntax cout.fill(ch); where ch represents the character which is used for filling the
unused positions

Example
cout.fill(‘*’);
cout.width(9);
cout<<2354<<”\n|;
Output:
* * * * * 2 3 5 4

4. setf( )
setf( )is used to set memory flag each of which play a role in formatting the output.
They are defined in the ios class and proceeded by ios::

Syntax: cout.setf(arg1,arg2);
where arg1  any one of formatting flag and arg2 bit field

Format required Flag(arg1) Bit-Field(arg2)


Left-Justified
ios::left ios::adjustfield
output
Right-Justified
ios::right ios::adjustfield
output
Padding after sign
or base
ios::internal ios::adjustfield
Indicator(like
+##20)
Scientific notation ios::scientific ios::floatfield
Fixed point
ios::fixed ios::floatfield
notation
Decimal base ios::dec ios::basefield
Octal base ios::oct ios::basefield
Hexadecimal base ios::hex Ios::basefield
5. unsetf()
unsetf() is used to unset the flags which were by the setf() member function.

Example
cout.unsetf(ios::left);
cout.unsetf(ios::showpoint);

MANIPULATORS
The header file iomanip provides a set of functions called manipulators which can be used
to manipulate the output formats. They provide the same features as that of the ios member
functions and flags.

Syntax
cout<<manip1<<manip2<<manip3<<data;

cout<<manip1<<item1<<manip2<<item2;

Types
 Build in Manipulators
 User defined Manipulators
Build in Manipulators
 Manipulators are used to format the output.
 Included under the header file <iomanip.h>

Manipulators Equivalent
setw(int w) width()

setprecision(int d) precision()

setfill(int c) fill()

setiosflgs(long f) setf( )

resetiosflags(long f) unsetf()
endl “\n”

A) setw(n)
This function is used to set width of the output.
Syntax: cout<<setw(int n);
Example:

#include<iostream>
#include<iomanip>
int main()
{
int x=10;
cout<<setw(20)<<variable;
return 0;
}
Output
10
B)setfill(char)
This function is used to fill specified character at unused space.

Syntax: cout<<setfill('character')<<variable;

Example:
#include<iostream>
#include<iomanip>
int main()
{
int x=10;
cout<<setw(20);
cout<<setfill('#')<<x;
return 0;
}
Output
##################10

D)setprecison(n)
This method is used for setting floating point of the output.

Syntax: cout<<setprecision('int n')<<variable;


Example:
#include<iostream>
#include<iomanip>
int main()
{
float x=10.12345;
cout<<setprecision(5)<<x;
return 0;
}
Output
10.123

E)setiosflags(arg 1, arg,2)
This function is used for setting format flags for output.
Syntax: setiosflags(argument 1, argument 2);

F)resetiosflag(arg 2)
This function is used to reset set flags for output.

Syntax: resetiosflags(argument 2);

DESIGNING OUR OWN MANIPULATORS - USER DEFINED MANIPULATOR

The manipulators defined by the user according to their requirement in the code of the program
are known as the user-defined manipulators. The syntax for designing our own manipulator is:
ostream & m_name (ostream & o)
{
statement 1;
statement 2;
return 0;
}

Example 1
#include<iostream>
#include<iomanip>
ostream & tab (ostream & o)
{
o << “\t”;
return 0;
}
void main()
{
cout<<1<<tb<<2 <<tab <<3;
}
In the above program, programmer created its own manipulator which is equivalent to \t to
format the output of the program. Whenever we calls the tab manipulator, the ‘\t’ is executed and
we get the effect of the tab.
Example 2
ostream& currency (ostream& output)
{
output<<”Rs”;
return output;
}
int main()
{
cout<<currency<<3454;
}
Output Rs 3454
One or more manipulators can be combined together to create a new manipulators.
Example
ostream& combine (ostream& output)
{
output<<setw(6)<<setiosflags(ios::right)<<setprecision(2);
return output;
}

main()
{
cout<<combine<<234.432;
}

WORKING WITH FILES

File
A file is a collection of related data stored in a particular area on the disk.

Working with files generally requires the following kinds of data communication
methodologies:

 Data transfer between console units


 Data transfer between the program and the disk file

The I/O system of C++ handles file operations like,


Input stream
Output stream
Input stream: The stream that supplies data to the program is known as input stream.
Output stream: The stream that receives data from the program is known as output stream.

Classes for file stream operation

The I/O system of c++ contains a set of classes that define the file handling methods.

Class Contents
Filebuf Its purpose is to set the file buffers to read & write
also contain open() and close() as member
fstreambase Provide operations common to the file streams.
fstream, ifstream and ofstream class contain s
open() and close() functions.
ifstream Contains open() with default input mode. Inherits
the functions get(), getline(), read() seekg() and
tellg() functions from istream
ofstream Contain open() withdefault output mode.Inherits
put(),seekp(),tellp() and write() function from
ostream
fstream Provide support for simultaneous input and output
operations. Contains open() with default input
mode.

Opening & closing a file


To open and close a file the following things are needed.
 A name for the file
 Data type and structure of the file
 Purpose (reading, writing data)
 Opening method
 Closing the file (after use)
The file name is a string of characters that make up a valid file name. It may contains two parts.
 Primary name
 Optional period with extension
Example: input.data
test.doc
sample.cpp
A file stream can be defined using the class like ifstream, ofstream and fstream.
A file can be opened in two ways
 Using the constructor function of the class
 Using the member function open() of the function
Opening files using constructor
For opening files using constructors, follow the below steps
 Create a file stream object to manage the stream. The class ofstream is used to create the
output stream and the class ifstream to create the input stream.
 Initialize the file object with the desired output.
Example:
The following statement opens a file named “result” for output

ofstream outfile(“results”); // output only

Similarly, the following statement declares infile as an ifstream object.

ifstream infile(“data”); //input only

The program may contain data like


outfile<<”total”;
outfile<<sum;
infile>>number;
infile>>string;
we can also use the same file name for both reading &writing
Program1
-----------
ofstream outfile(“salary”); //creates outfile and connects “salary” to it.
-----------
Program 2
-----------
ifstream infile(“salary”); //creates infle and connects “salary” to it.
-----------
 Instead of using two programs one for writing data and another for reading data.
 We can also use a single program to do both the operations on a file
Example:
……
……
outfile.close(); //Disconnect salary from outfile
ifstreaminfile(“salary”); //and connect to infile
……
infile.close(); //disconnect salary from infile
Working with constructor // creating files with constructor function
#include<iostream.h>
#include<conio.h>
int main()
{
ofstream outf(“ITEM”);
cout<<”Enter item name:”);
char name[20];
cin>>name;
outf<<name<<”\n”;
cout<<Enter item cost:”);
float cost;
cin>>cost;
outf<<cost<<”\n”;
outf.close();
ifstream inf(“ITEM”);
inf>>name;
inf>>cost;
cout<<”\n”;
cout<<”Item cost:”<<name<<”\n”;
cout<<”Item cost:”<<cost<<”\n”;
inf.close();
return 0;
}
Opening files using open()
The function open() can be used to open multiple files that use the same stream object.
Example:
We may create a single stream object and use it to open each file in turn
Syntax: file-stream-class stream-object;
stream-object.open(“filename”);
Example
ofstreamoutfile;
outfile.open(“DATA1”);
------
------
outfile.close();
outfile.open(“data2”);
------
------
outfile.close();
------
------
The first file is closed before opening the second one. This is necessary because a stream can be
connected to only file at a file.
Working with multiple files //creating files with open() function
#include<iostream.h>
#include<conio.h>
int main()
{
ofstream fout;
fout.open(“country”);
fout<<”UK\n”;
fout<<”India \n”;
fout<<”USA \n”;
fout.close();
fout.open(“capital”);
fout<<”London \n”;
fout<<”Delhi \n”;
fout<<”Washington \n”;
fout.close();
const int N=78;
char line[N];
ifstream fin;
fin.open(“country”);
cout<<”content of country file \n”;
while(file)
{
fin.getline(line,N);
cout<<line;
}
fin.close();
fin.open(“capital”);
while(fin)
{
fin.getline(line,N);
cout<<line;
}
fin.close();
return 0;
}

Various file modes while opening file:

Syntax: Stream-object-open(“filename”,mode);

The default values


ios::in for ifstream functions meaning open for reading only
ios::out for ofstream functions meaning open for writing only
The file mode parameter can take one or more of such constants defined in the class ios.
File mode parameters and their meanings
Parameter Meaning
ios::app Append to end-of-file
ios::ate Go to end-of-file on opening
ios::binary Binary file
ios::in Open file for reading only
ios::nocreate Open fails if the file does not exit
ios::noreplace Open fails if the file already exits
ios::out Open file for writing only
ios::trunc Delete the contents of the file if it exits
Ex:
The mode can combine two or more parameters using the bitwise OR operator(symbol1)
fout.open(“data”,ios::app/ios::nocreate);

Closing a file

When any C++ program terminates, it automatically flushes out all the streams, releases all the
allocated memory and closes all the opened files. But it is good to use the close() function to close
the file related streams and it is a member of ifstream, ofstream and fstream objects.
The structure of using this function is:
void close();

Detecting End of File


 While reading data from a file, if the file contains multiple rows, it is necessary to detect the
end of file.
 This can be done using the eof() function of ios class.
 It returns 0 when there is data to be read and a non-zero value if there is no data.
Example
#include<iostream>
#include<fstream>
int main()
{
string name;
int salary;
ofstream opfile(“data.txt”);
for(int i=1; i<=3; i++)
{
cout<<“Enter name and salary of employee “<<i<<“:”;
cin>>name>>salary;
opfile<<name<<“\t”<<salary;
}
opfile.close();
cout<<“Data stored into file.”<<endl;
cout<<“Reading data from file…”<<endl;
ifstream ipfile(“data.txt”);
while(!ipfile.eof()) //Checking for end of file
{
ipfile>>name>>salary;
cout<<“Name: “<<name<<” Salary: “<<salary<<endl;
}
ipfile.close();
return 0;
}
Input and output for the above program is as follows:
Enter name and salary of employee 1: suresh 7000
Enter name and salary of employee 2: ramesh 8000
Enter name and salary of employee 3: mahesh 9000
Data stored into file.
Reading data from file...
Name: suresh Salary: 7000
Name: ramesh Salary: 8000
Name: mahesh Salary: 9000

FILE POINTERS AND THEIR MANIPULATIONS

 The C++ I/O system supports function for setting a file pointer to any desired position
inside the file or to get the file pointer.
 These allow the programmer to have control over a pointer in the file where read or write
operation takes place.
 These functions are listed below:
Function Member of class Action performed
seekg() ifstream Moves get file pointer to a
specific location
seekp() ofstream Moves put file pointer to a
specific location
tellg() ifstream Returns the current position
of the get pointer
tellp() ofstream Returns the current position
of the put pointer

The seekp() and tellp() are member function of ofstream.


The seekg() or tellg() are member function of ifstream.
The class fstream deals with file in both input and output modes.
Each file has two associated pointers known as the file pointers.
 Input pointer (or get pointer)
 Output pointer (or put pointer)
If we want to open an existing file to add more data, the file is opened in ‘append’ mode. This
moves the output pointer to the end of the file.

Specifying the offset


The seek() function can be used to move a file pointer to a desire location.
The seek() functions seekg() and seekp() can also be used with two arguments

Syntax:

seekg (offset, refposition);

seekg (offset, refposition);

The parameter offset represents the number of bytes the file pointer to be moved from the location
specified by the parameter refposition.

The refposition takes one of the following three constants defined in the ios class

 ios::beg //start of the file


 ios::cur //current position of the pointer
 ios::end //end of the file
Ex:
fout.seekg(0,ios::beg);
fout.seekg(m,ios::beg);
fout,seekg(m+1,ios::end);
Updating a file: Random Access
Updating is a routine task in the maintenance of any data file. The updating would include one or
more following tasks
 Displaying the contents of a file
 Modifying an existing file
 Adding a new item
 Deleting an existing item
This can be easily implemented if a file contains a collection of items/objects of equal lengths.It can
be done by the following statement

int object_length = sizeof(object);

The location of the desired object,say the mth object

int location = m * object_length;

We can also find out the total number of objects in a file using the object_length as follows

int n = file_size/object_length;

Random Access of File Using File Pointer Manipulation


#include<iostream.h>
#include<fstream.h>
int main()
{
fstream fp;
char buf[100];
int pos;
// open a file in write mode with 'ate' flag
fp.open("random.txt", ios :: out | ios :: ate);
cout << "\nWriting to a file ... " << endl;
fp << "This is a line" << endl; // write a line to a file
fp << "This is a another line" << endl; // write another file
pos = fp.tellp();
cout << "Current position of put pointer : " << pos << endl;
fp.seekp(-10, ios :: cur); // move the pointer 10 bytes backward from current position
fp << endl << "Writing at a random location ";
fp.seekp(7, ios :: beg); // move the pointer 7 bytes forward from beginning of the file
fp << " Hello World ";
fp.close(); // file write complete
cout << "Writing Complete ... " << endl;
fp.open("random.txt", ios :: in | ios :: ate); // open a file in read mode with 'ate' flag
cout << "\nReading from the file ... " << endl;
fp.seekg(0); // move the get pointer to the beginning of the file
// read all contents till the end of file
while (!fp.eof()) {
fp.getline(buf, 100);
cout << buf << endl;
}
pos = fp.tellg();
cout << "\nCurrent Position of get pointer : " << pos << endl;
return 0;
}
Output
Writing to a file …
Current Position of put pointer : 40
Writing Complete …
Reading from the file …
This is Hello World is a anot
Writing at random location
Current Position of get pointer : -1

SEQUENTIAL INPUT AND OUTPUT OPERATIONS


The file stream classes support a number of member function for performing the input and output
operations on file.

Function
 put() and get() are designing for handling a single character at a time.
 write() and read() are designed to write and read blocks of binary data.
I/O operations on character
put() and get() functions:
put(): The function put() writes a single character to the stream.
get(): The function get() reads a single character from the stream.
Example Program
#include<iostream.h>
#include<fstream.h>
#include<string.h>
int main()
{
char str[20];
cout<”Enter the string \n”;
cin>>str;
int len=strlen(str);
fstream file;
file.open(“TEXT”, ios::in | ios::out);
for(int i=0;i<len;i++)
file.put(string[i]);
file.seekg(0);
charch;
while(file)
{
file.get(ch);
cout<<ch;
}
return 0;
}
write() and read() function
The write() and read() function to handle the data in binary form .This means that the values are
stored in the disk file in the same format in which they are stored in the internal memory.

The binary input and output functions takes the following form
Syntax:

infile.read((char*) & v, sizeof ((v));

outfile.write((char*) & v, sizeof ((v));

This function takes two arguments. The first is to address of the variable v and the second is the
length of that variable in bytes.

Example:

#include<iostream.h>
#include<fstream.h>
#include<iomanip.h>
const char *filename=”BINARY”;
int main()
{
float height[4]={123.7,123.7,167.5,176.49};
ofstreamoutfile;
outfile.open(filename);
outfile.write((char *) & height, sizeof(height));
outfile.close();
for(int i=0;i<4;i++)
height[i]=0;
ifstreaminfile;
infile.open(filename);
infile.read((char*)&height,sizeof(height));
for(i=0;i<4;i++)
{
cout.setf(ios::showpoint);
cout<<setw(10)<<setprecision(2)<<height[i];
}
infile.close();
return 0;
}
Reading and writing a class object:

 The binary input and output function read() and write() are designed to read & write the
values.
 The function write() copies a class object from memory byte with no conversion.
 The length of object is obtained using the size of operator
Program:
class inventory
{
char name[10];
int code;
float cost;
public:
void readdata(void);
void writedata(void0;
};
void inventory::readdata(void)
{
cout<<”Enter the name”;
cin>>name;
cout<<”Enter the code”;
cin>>code;
cout<<”Enter the cost”;
cin>>cost
}
void inventory::writedata(void)
{
cout<<name<<code<<cost;
}
int main()
{
inventory item[3];
fstream file;
file.open(“stock.DATA”,ios::in|ios::out);
cout<<”Enter the values for 3 items:”);
for(i=0;i<3;i++)
{
item[i].readdata();
file.write((char*)&item[i].sizeof(item[i]));
file.seekg(0);
for(i=0;i<=3;i++)
{
file.read((char*)&item[i]sizeof(item[i]));
item[i].writedata();
}
file.close();
return 0;
}
ERROR HANDLING DURING FILE OPERATIONS
One of the following things may happen when dealing with the files:
o A file which we are attempting to open for reading does not exist.
o A file name used for a new file may already exist.
o We may attempt an invalid operations such as reading past end of the file.
o There may not be any space in the disk for storing more data.
o We may use an invalid file name.
o We may attempt to perform operation when the file is not open for the purpose.
eof(): Return true(non-zero values)if end-of-file is encountered while reading: otherwise returns
false(zero)

fall(): Returns true when an input or output operation has failed.


bad(): Returns true if an invalid operation is attempted or any un-coverable error has occurred.
However, if it is false it may be possible to recover from any other error reported, and continue
operation.

good():Returns true if no error has occurred. This functions may be used in the appropriate places
in the program to locate the status of a file stream.

----
ifstreaminfile;
infile.open(“ABC”);
while(!infile.fail())
{
---
---(process the file)
}
if(infile.eof())
{
--- (terminate program normally)
}
else
if(infile.bad())
{
…. (report fatal error)
}
else
{
infile.clear();
----
}
The function clear() resets the error state so that further operation can be attempted. Here, infile
becomes false(zero) when end of the file is reached(and eof becomes true).
Command-Line Arguments
C++ also supports this command line argument. These arguments are supplied to main function at
the time of invoking the program.

Ex: C > exam data results

exam  name of the file containing the program to be executed.

data and results file name passed to the program as command line arguments

The main() functions without having any arguments can take two arguments.

main(intargc,char *argv[])

argc known as arguments counter represents number of arguments in command line.


argvknown as argument vector is an array of char type pointers that points to command
line argument.

The size of this array will be equal to the value of argc.

Eg:

The command line argument


C:// test ODD EVEN
Where test is file name containing program

argc= 3 and
argv[0] = test
argv[1] = ODD
argv[2] = EVEN

Program

#include<iostream.h>
#include<fstream.h>
#include<conio.h>
int main(intargc char *argv[])
{
int n[9] = {11,22,33,44,55,66,77,88,99}
ofstream f1,f2;
f1.open(argv[1]);
f2.open(argv[2]);
for(int i=0;i<9;i++)
{
if(n[i]%2==0)
f2<<n[i];
else
f1<<n[i];
}
}
f1.close();
f2.close();
ifstream fin;
charch;
for(i=1;i<argc;i++)
{
fin.open(argv[i]);
cout<<argv[i];
do
{
fin.get(ch);
cout<<ch;
}
while(fin);
fin.close();
}
return 0;
}
UNIT – V

Templates
 Generic programming is an approach where generic types are used as parameters in
algorithms so that they work for a variety of suitable data types and data structure.
 A template is a blue print or formula for creating a generic class or function.
 A template can be used to create a family of classes or functions.
 A template can be considered as a kind of macro.
 A template is defined with a parameter that would be replaced by a specified
data type at the time of actual use of class or function, the templates are
sometimes called as parametrized classes or functions.
TYPES: The two types of templates are
1. class template.
2. function template.
Class Templates
 Class template is used to create family of classes with same member function
but different types of data.
 The process of creating a specific class from a class template is called instantiation.
General form:
Template <class T>
class tagname
{ ________
_________
};
Syntax for declaring an object:
tagname <type> object –name;
Example:
#include<iostream.h>
template<class T>
class max
{
T a,b;
public:
max(T first, T second)
{
a=first;
b=second;
}
T getmax()
{
T result;
result = a>b?a:b;
return result;
}
};
A single template to support all data types:
The class created from a class template is called template class.
Syntax: classname <type> objectname(arglist);
Example:
#include<iostream.h>
#include<conio.h>
template <class T>
class data
{
public:
data(T c)
{
cout<<”c= “<<c<<”size in bytes:”<<sizeof(c);
}
};
int main()
{
clrscr();
data <char> h(‘A’);
data <int> i(20);
data <float> j(2.3);
return 0;
}
Output:
c = A size in bytes : 1
c = 20 size in bytes: 2
c = 2.3 size in bytes: 4

Class templates with multiple parameters


The class template may contain one or more parameters of generic data type. The
arguments are separated by comma with template declaration.

General form:
template <class T1, class T2,…>
class classname
{
---
Body of the class
---
};
Syntax for declaring an object :
tagname <type ,type 1 ,type 2 ,…..> object name;
Example:
#include<iostream.h>
template <class T1, class T2>
class data
{
public:
data (T1 a, T2 b)
{
cout<<”\n a=“<<a<<”b= “<<b;
}
};
int main()
{
clrscr();
data <int,float>h(2,2.5);
data <int,char> i(3,’C’);
data <float,int> j(7.5,20);
return 0;
}
Output
a=2 b=2.5
a=3 b=C
a=7.5 b=20
When objects are created, constructor functions automatically called & values are received by
template argument.
Function templates
Function template is used to create a family of functions with different arguments type.
Syntax:

template <class t>


returntype functionname(argument of type T)
{
//body of function
}
The function template is similar to that of the class template except that we are defining functions
instead of classes.
Example:

#include<iostream.h>
template <class T>
void swap(T &x,T &y)
{
T temp = x;
x = y;
y = temp;
}
void fun(int m,int n,float a,float b)
{
cout<<”m and n before swap:”<<”m=”<<m<<”n=”<<n<<”\n”;
swap(m,n);
cout<<”m and n after swap:”<<”m=”<<m<<”n=”<<n<<”\n”;
cout<<”a and b before swap:”<<”a=”<<a<<”b=”<<b<”\n”;
swap(a,b);
cout<<”a and b after swap:”<<”a=”<<a<<”b=”b<<b<”\n”;
}
int main()
{
fun(10,20,11.5,12.5);
return 0;
}
Output
m and n before swap: m=10 n=20
m and n after swap: m=20 n=10
a and b before swap: m=11.5 n=12.5
a and b after swap: m=12.5 n=11.5
Bubble sort using template functions
#include<iostream.h>
template<class T>
void bubble(T a[],int n)
{
for(int i=0;i<n-1;i++)
for(int j=n-1;i<j;j--)
if(a[j]<a[j-1])
{
swap(a[j]a[j-1]);
}
}
template<class X>
void swap(X &a,X &b)
{
X temp = a;
a = b;
b = temp;
}
int main()
{
int x[5] = {10,50,40,30,20};
float y[5] = {1.5,5.5,4.5,3.5,2.5};
bubble(x,5);
cout<<”Sorted x-array:”;
for(int i=0;i<5;i++)
cout<<x[i]<<” “;
cout<<endl;
cout<<”sorted y-array:”;
for(int j=0;j<5;j++)
cout<<y[j]<<” “;
cout<<end;’
return 0;
}
Output
Sorted x-array: 10,20,30,40,50
Sorted y – array: 1.5,2.5,3.5,4.5,5.5
Function templates with multiple parameters
Like template class, we can use more than one generic data type in function template statement,
using a comma-separated list.

Syntax
template<class T1, class t2,….>
returntype functionname(arguments of types T1,T2,…)
{
---
Body of the function
---
}
Example
#includeiostream.h>
#include<string>
template<class T1,class T2>
void display(T1 X,T2 y)
{
cout<<x<<” “<<y<”\n”;
}
int main()
{
cout<<”int and character string…\n”;
display(2000,”EDF”);
cout<<”float and integer….\n”;
display(9.4,1235);
return 0;
}
Output
int and character string
2000 EDF
float and integer
9.4 1235
Overloading of template function
A template function may be overloaded either by template function or ordinary functions of
the name.
Rules for choosing appropriate function when program contains overloaded function:
 Call an ordinary function that has an exact match.
 Call a template function that could be created with an exact match
 Try normal overloading resolution to ordinary functions and call the one that matches.
 In case no match is found, an error will be reported
Note that no automatic conversions are applied to arguments on the template functions.
Example
#include<iostream.h>
#include<string.h>
template <class T>
void show(T c)
{
cout<<”\n Template variable c= “<<c;
}
void show(int d)
{
cout<<”\n Integer variable d= “<<d;
}
int main()
{
clrscr();
show(‘C’);
show(30);
show(21.34);
return 0;
}
Output
Template variable c=C
Integer variable d=30
Template variable c=21.34
Member function templates
 It is also possible to define member function definition outside the class.
 While defining them outside, the function template should define the function and
the templates classes are parameterized by the type argument.
General Form:
template<class T>
return_type class_name<T>:: function_name(arglist)
{
// ……
// function body
// …….
}
Example
template <class T> // defines template
data<T>::data (T c) // It indicates class type T

Program:
#include<iostream.h
#include<conio.h>
template <class T>
class data
{
public:
data(T c);
};
template <class T>
data<T>::data(T c)
{
cout<<”\n”<<”c=”<<c;
}
int main()
{
clrscr();
data<char> h(‘A’);
data<int> i(100);
data<float> j(3.12);
return 0;
}
Output
c=A
c=100
c=3.12
Non-type template argument:
It is also possible to use non-type argument. In addition to the type argument T, we can also
use other arguments such as strings, function names, constant expressions and built-in types.

Example

template<class T, int size>


class array
{
T a[size]; // automatic array initialization
};
int main()
{
array<int,10>a1; //array of 10 integer
array<float,5>a2; // array of float
array<char,10>a3; //array of size 20
----
}
Hence the template supplies the size of the array as an argument implies that the size of the array
is known to the compiler at the compiler time.

EXCEPTION HANDLING

Introduction
The two most common types of bugs are logic error and syntactic error.
 The logic error occurs due to poor understanding of the problem and solution procedure.
Eg: To return average of 2 numbers. Return a+b/2 causes logical error.
The correct statement is return (a+b) /2;
 The syntactic error arises due to poor understanding of language itself.
Eg: To print hello , we must use
printf(“hello”);
and printf(hello) results in syntactic error.
Exception
 Exceptions are run time anomalies or unusual conditions that a program may encounter
while executing.
 Anomalies might include conditions such as
 division by zero,
 access to any array outside of its bounds.
 running out of memory or disk space
 Exception handling provides a type-safe, integrated approach, for copying with the
unusual predictable problem.

Basics of Exception Handling


Exceptions are of two types, namely
 Synchronous exception
 Asynchronous exception
Synchronous Exception: Error such as “out-of-range index”, and “overflow”.
Asynchronous Exception: Error that is caused by events beyond the control of the program.
Purpose of Exception handling
The purpose of exception handling mechanism is to provide means to detect and report an
“exceptional circumstances”.
 Find the problem(hit the exception)
 Inform that an error has occurred(Throw the exception)
 Receive the error information(Catch the exception)
 Take corrective actions(Handle the exception)
The error handling code consists of two segments
1. To detect error and to throw exception
2. To catch the exception and to take appropriate actions
Exception handling mechanism:
It basically has three keywords, namely
 try
 catch
 throw
try
 It is used to preface a block of statements which may generate exceptions.
 This block of statements is known as try blocks.
Example
try
{
if(x!=0)
{
cout<<a/x;
}
else
{
throw(x);
}
}
throw
 When an exception is detected, it is thrown using a throw statement in the try block.
catch
 Catch block catches the exception thrown by the throw statement in the try block and
handles in accordingly.
 Always catch block must follow try block that throws the exception

The block throwing exception

Example:

#include<iostream.h>
int main()
{
int a,b;
cout<<”Enter value for a and b”;
cin>>a>>b;
int x = a-b;
try
{
if(x!=0)
{
cout<<a/x<<”\n”;
}
else
{
throw(x);
}
}
catch(int i)
{
cout<<”Exception occurred:divide by zero\n”;
}
cout<<”END”;
return 0;
}
Function invoked by try block throwing exception
 Exceptions are thrown by functions that are invoked from within the try blocks.
 The point at which the throw is executed is called the throw point.
 Once an exception is thrown to the catch block, control return to the throw point.

Function invoked by try block throwing exception


General Format

Example
#include<iostream.h>
void divide(int x, int y, int z)
{
cout<<”\n Inside the function \n”;
if((x-y)!=0)
{
int R = z/(x-y);
cout<<”Result = “<< R << “\n”;
}
else
{
throw(x-y);
}
}
int main()
{
try
{
cout<<”Inside the try block \n”;
divide(10,20,30);
divide(10,10,30);
}
catch(int i)
{
cout<<”caught the exception \n”;
}
return 0;
}
Output
Inside the try block
Inside the function
Result = -3
Inside the function
Caught the exception

Throwing Mechanism
When an exception is detected, it is thrown using the throw statement

throw(exception);

throw exception;

throw; //used for re-throwing an exception

The operand object exception may be of any type, including constants.

Catching Mechanism
The code for handling exceptions is included in catch blocks.

catch (type arg)


{
//statements for managing exceptions
}
 The type indicates the type of exception that catch block handles.
 The parameter arg is an optional parameter name.
 The catch statement catches an exception whose type matches with the type of catch
argument.
 The catch block is simply skipped if the catch statement does not catch an exception.

Multiple catch statements


 It is possible that a program can have more than one condition to throw an exception.
 We can associate more than one catch statement with a try.
Syntax
try
{
//try block
}
catch(type1 arg)
{
//catch block1
}
catch(type2 arg)
{
//catch block2
}
----
----
catch(typeN arg)
{
//catch blockN
}
 When an exception is thrown the exception handlers are searched in order for an exact
match.
 After executing the handler, a control goes to the first statement after the last catch block
for that try.
 When no match is found, the program is terminated.
Example

#include<iostream.h>
void test(int x)
{
try
{
if(x == 1) throw x;
else if(x==0) throw ‘x’;
else if(x==-1) throw 1.0;
cout<<”End of try block \n”;
}
catch(char c)
{
cout<<”caught a character \n”;
}
catch(int m)
{
cout<<”caught an integer \n”;
}
catch(double d)
{
cout<<”caught a double \n”;
}
cout<<”End of try catch system \n”;
}
int main()
{
cout<<”Testing multiple catches \n”;
cout<<”x==1 \n”;
test(1);
cout<<”x==0 \n”;
test(0);
cout<<”x==-1 \n”;
test(-1);
cout<<”x==2 \n”;
test(2);
return 0;
}
Output
Testing multiple catches
x==1
caught an integer
End of try catch system

x==0
caught a character
End of try catch system

x==-1
caught a double
End of try catch system

x==2
End of try block
End of try catch system

Catch all Exceptions


 We can force a catch statement to catch all exceptions instead of a certain type alone.
 This could be achieved by defining the catch statement using ellipse.

Syntax
catch(…)
{
//statements for processing
//all exceptions
}
Example
#include<iostream.h>
void test(int x)
{
try
{
if(x==0) throw x;
if(x==-1) throw ‘x’;
if(x ==1 ) throw 1.0;
}
catch(…)
{
cout<<”caught an exception \n”;
}
int main()
{
test(-1);
test(0);
test(1);
return 0;
}
Output
caught an exception
caught an exception
caught an exception
Remember catch(...) should always be placed last in the list of handlers. Placing it before other
catch blocks, would prevent those blocks from catching exceptions.

Re-throwing Exception
A handler may decide to throw the exception caught without processing it. In such situation we
may simply invoke throw without only argument.
Syntax: throw;
Example
#include<iostream.h>
void divide(double x, double y)
{
cout<<”Inside function”;
try
{
if(y==0.0)
throw y;
else
cout<<”Division=”<<x/y;
}
catch(double)
{
cout<<”caught double inside function”;
throw;
}
cout<<”End of function”;
}
int main()
{
cout<<”Inside main”;
try
{
divide(10.5,3.0);
divide(20.0,0.0);
}
catch(double)
{
cout<”caught double inside main”;
}
cout<<”End of main”;
return 0;
}
Output
Inside main
Inside function
Division = 5.25
End of Function

Inside function
Caught double inside function
Caught double inside main
End of main
When an exception is re-thrown, it will not be caught by the same catch statement or any other
catch in that group. Rather, it will be caught by an appropriate catch in the outer try/ catch
sequence only.

Specifying Exception
It is possible to restrict a function to throw only certain specified exception.
Syntax
type function(arg-list) throw (type-list)
{
//function body;
}
 The type-list specifies the type of exceptions that may be thrown.
 Throwing any other type of exception will cause abnormal program termination.
 If we wish to prevent a function from throwing any exception, we can make type list empty
by using throw().
Example:
#include<iostream.h>
void test(int x) throw(int,double)
{
if(x==0)throw ‘x’;
else if(x==1) throw x;
else if(x==-1) throw 1.0;
cout<<”End of function block \n”;
}
int main()
{
try
{
cout<<”x==0”;
test(0);
cout<<”x==1”;
test(1);
cout<<”x==-1”;
test(-1);
cout<<”x==2”;
test(2);
}
catch(char c)
{
cout<<caught a character”;
}
catch(int m)
{
cout<<”caught an integer”;
}
catch(double d)
{
cout<<”caught a double”;
} return 0; }
UNIT V
2 Marks
1. What is Generic Programming?
2. Define Template.
3. What is parameterized classes or functions?
4. What is Class template?
5. Define instantiation.
6. Define template class.
7. Define Function template.
8. Write the rules for choosing appropriate function when program contains overloaded
function.
9. What is exception? Write its types.
10. Write the purpose of exception handling mechanism.
11. Write the two segments of error handling code.
12. How will you re-throw an exception?

5/10 Marks
1. Write note on Class Templates.
2. Write note on Class templates with multiple parameters.
3. Write note on Function Templates.
4. Write a C++ program for Bubble sort using template functions
5. Write note on Function templates with multiple parameters.
6. Write note on Overloading of template function.
7. Write note on Member function templates
8. Write in detail about Exception Handling mechanism.
9. Write note on Multiple catch statements
10. Write note on Catch all Exceptions
11. Write note on Re-throwing Exception
12. Write note on Specifying Exception

UNIVERSITY EXAM NOVEMBER 2019


PART - A
ANSWER ALL THE QUESTION
1. Define variable.
2. List out the categories of expression in C++.
3. What is meant by inline function?
4. Define Array.
5. What do you mean by Operator Overloading.
6. Mention the types of Inheritance in C++.
7. Write the purpose of width() and precision() functions.
8. List out the file mode parameters.
9. What are templates?
10. What do you mean by exceptions? What are the types of exceptions?

PART – B
ANSWER ALL THE QUESTION
11. (a) Write a simple program example for exhibit the purpose of Conditional Operator. (Or)
(b) Discuss about do while loop with example.
12. (a) Write a note on Static data members. (Or)
(b)How can you define member functions of a class?
13. (a) Write a program example for Multiple inheritance. (Or)
(b) Write down the rules for Virtual functions.
14. (a) Describe about put() and get() functions. (Or)
(b) Discuss about managing output with manipulators.
15. (a) Write in brief about Class Templates. (Or)
(b) Discuss about Rethrowing an exception with example.
PART – C
ANSWER ANY THREE QUESTIONS
16. Write in detail about
a) Constants
b) Benefits of OOPs
17. What are Parameterized Constructors? Give a program example.
18. Discuss about overloading binary operator.
19. Write a C++ program to copy a content of a file to another file.
20. Write in detail about Exception Handling mechanism.

UNIVERSITY EXAM NOVEMBER 2017


PART - A
ANSWER ALL THE QUESTION
1. What is meant by manipulators? Explain its uses.
2. Define polymorphism briefly.
3. What is the use of constructors? Explain briefly.
4. Illustrate the specification of a class.
5. Define Inheritance.
6. Define an abstract class with an example.
7. Define field width().
8. Give the use of good() function.
9. Define parameterized class or functions.
10. Give the syntax for throwing mechanisms.

PART – B
ANSWER ALL THE QUESTION
11. (a) Explain the basic concepts of OOP. (Or)
(b) How to declare and initialize variable?
12. (a) Write a short note on memory allocation for objects. (Or)
(b)Discuss about constructors defined in a class.
13. (a) Discuss the concepts of inheritance and explain single inheritance. (Or)
(b) Explain pointers to derived classes briefly.
14. (a) Write a short note on updating a file. (Or)
(b) Explain managing output with manipulators.
15. (a) Explain catching mechanism in exception handling. (Or)
(b) Write short note on function templates with general format.
PART – C
ANSWER ANY THREE QUESTIONS
16. Discuss about while, do-while and for statements with their syntaxes.
17. Write a note on function overloading with example.
18. Explain virtual base class in detail.
19. Explain in detail about file pointers and their manipulations.
Write an account on exception handling mechanism.

UNIVERSITY EXAM APRIL/MAY 2016


PART - A
ANSWER ALL THE QUESTION
1. What is an identifier?
2. List at least four new operators added by C++ which aid OOP.
3. What is function overloading?
4. Define object.
5. What is derived class?
6. What is a virtual base class?
7. What is stream?
8. How will you open a file?
9. What is instantiation?
10. What are the two common types of bugs?
PART – B
ANSWER ALL THE QUESTION
11. (a) Explain the hierarchy of C++ data types. (Or)
(b) Explain different types of expressions in C++.
12. (a) Explain about static data members. (Or)
(b)Discuss the concept of Array of Objects.
13. (a) Explain the usage of type conversions. (Or)
(b) Write short notes “this pointer”.
14. (a) Explain the various error handling functions. (Or)
(b) Discuss on command-line argument with an example program.
15. (a) Write short note on function template. (Or)
(b) Write short note on throwing mechanism.
PART – C
ANSWER ANY THREE QUESTIONS
16. Explain different control structures in C++ with an example.
17. Explain the concept of virtual function with an example.
18. Explain in detail about multiple inheritance and its operations.
19. Write a C++ program to create a student file.
20. Explain the concept of exception handling mechanism in C++ with an example program.

UNIVERSITY EXAM NOVEMBER/DECEMBER 2015


PART - A
ANSWER ALL THE QUESTION
1. What do you mean by data hiding?
2. What are known as tokens?
3. What is called inline function?
4. Identify the purpose of ‘endl’.
5. What is the purpose of floor(v)?
6. List out the operators which cannot be overloaded.
7. What do you mean by inheritance?
8. What is called as pure virtual function?
9. Mention the basic purpose of templates.
10. What do you mean by generic programming?

PART – B
ANSWER ALL THE QUESTION
11. (a) Classify and explain the various categories of data types handled with C++. (Or)
(b) Discuss the various features of object oriented programming.
12. (a) How member functions be defined in C++? Explain. (Or)
(b)How arrays within a class be handled in C++? Explain.
13. (a) Discuss the rules to be followed while handling virtual functions. (Or)
(b) With example, explain multilevel inheritance.
14. (a) Describe the various ios format functions. (Or)
(b) How a file be opened? Explain.
15. (a) How class templates are handled in C++? Explain. (Or)
(b) How specifying exceptions be handled in C++? Explain.
PART – C
ANSWER ANY THREE QUESTIONS
16. Write a C++ program to find the average of first n prime numbers.
17. Discuss the special characteristics of the constructors.
18. Write a C++ program which describes overloading binary operators.
19. Write a program which reads a text from the keyboard and displays the following information
on the screen
a)Number of lines
b)Number of words
c)Number of characters
20. Write a function template for finding the maximum value contained in an array.
LAB PROGRAMS
1. PROGRAM TO CREATE A CLASS ARITHMETIC & PERFORM ARITHMETIC
OPERATIONS
#include<iostream.h>
#include<conio.h>
class ARITHMETIC
{
float a;
int b;
int c;
public:
void get();
void add();
void sub();
void mul();
void div();
};
void ARITHMETIC::get()
{
cout<<"Enter Two Values";
cin>>a>>b;
}
void ARITHMETIC::add()
{
c=a+b;
cout<<"add:"<<c<<endl;
}
void ARITHMETIC::sub()
{
c=a-b;
cout<<"sub:"<<c<<endl;
}
void ARITHMETIC::mul()
{
c=a*b;
cout<<"mul:"<<c<<endl;
}
void ARITHMETIC::div()
{
c=a/b;
cout<<"div:"<<c<<endl;
}
main()
{
ARITHMETIC c;
clrscr();
cout<<"Arithmetic Calculations\n";
cout<<"***********************\n";
c.get();
c.add();
c.sub();
c.mul();
c.div();
getch();
return 0;
}
OUTPUT:
==========
Arithmetic Calculations
*****************************
Enter Two Values
20
5
Add: 25
Sub: 15
Mul: 100
Div: 4
2. PROGRAM TO CREATE A CLASS FLOAT & OVERLOAD ALL THE FOUR ARITHMETIC
OPERATORS TO OPERATE ON THE OBJECT FLOAT
#include<iostream.h>
#include<conio.h>
class FLOAT
{
float n;
public:
FLOAT(){ }
void getdata()
{
cout<<"Enter a floating number:";
cin>>n;
}
void putdata()
{
cout<<n<<"\n";
}
FLOAT operator +(FLOAT);
FLOAT operator *(FLOAT);
FLOAT operator -(FLOAT);
FLOAT operator /(FLOAT); };
FLOAT FLOAT::operator +(FLOAT a)
{
FLOAT t;
t.n=n+a.n;
return t;
}
FLOAT FLOAT::operator *(FLOAT b)
{
FLOAT t;
t.n=n*b.n;
return t;
}
FLOAT FLOAT::operator -(FLOAT b)
{
FLOAT t;
t.n=n-b.n;
return t;
}
FLOAT FLOAT::operator /(FLOAT b)
{
FLOAT t;
t.n=n/b.n;
return t;
}
main()
{
clrscr();
FLOAT a,b,c;
cout<<"Arithmetic Calculation Using Operator Overloading\n";
cout<<"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
a.getdata();
b.getdata();
cout<<" Addition of two object :";
c=a+b;
c.putdata();
cout<<" Multiplication of two object:";
c=a*b;
c.putdata();
cout<<" Subtraction of two object :";
c=a-b;
c.putdata();
cout<<" Division of two object :";
c=a/b;
c.putdata();
getch();
return 0; }
OUTPUT:
=========
Arithmetic Calculation Using Operator Overloading
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Enter a float number: 40.5
Enter a float number: 5.5
Addition of two object : 46
Multiplication of two object : 222.75
Subtraction of two object : 35
Division of two object : 7.363636

3. PROGRAM TO CREATE A CLASS STRING & OVERLOAD THE OPERATORS ++ AND ==


TO CONCATENATE TWO STRINGS
#include<iostream.h>
#include<conio.h>
#include<string.h>
class string
{
char str[100];
public:
void get()
{
cout<<"\n Enter string:";
cin>>str;
}
void display()
{
cout<<str;
}
string operator +(string X)
{
string s;
strcat(str,X.str);
strcpy(s.str,str);
return s;
}
};
int main()
{
clrscr();
string s1,s2,s3;
s1.get();
s2.get();
cout<<"\n First string is:";
s1.display();
cout<<"\n\n Second string is:";
s2.display();
s3=s1+s2;
cout<<"\n\n Concatenated string is:";
s3.display();
getch();
return 0;
}
OUTPUT:
==========
Enter string: 2
Enter string: BCA
First string is: 2
Second string is: BCA
Concatenated string is: 2BCA

4. PROGRAM TO CREATE CLASS EMPLOYEE, DERIVE A CLASS PAY FROM THE ABOVE
CLASS AND WRITE A MEMBER FUNCTION TO CALCULATE DA, HRA AND PF & GET
AND DISPLAY THE DETAILS
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
class employee
{
protected:
char enumber[10];
char ename[20];
char dept[50],grade;
float bp;
double salary,da,hra,pf;
public:
void get()
{
cout<<"Enter Employee Number: \n";
cin>>enumber;
cout<<"Enter Employee Name: \n";
cin>> ename;
cout<<"Enter Employee Department: \n";
cin>>dept;
cout<<"Enter Basic Salary: \n";
cin>> bp;
}
void display()
{
cout<<" Employee Details "<<"\n";
cout<<" =================="<<"\n";
cout<<"Employee Number :"<<enumber<<"\n";
cout<<"Employee Name :"<<ename<<"\n";
cout<<"Department :"<<dept<<"\n";
cout<<"Basic Pay :"<<bp<<"\n";
cout<<"Dearness Allowances :"<<da<<"\n";
cout<<"House Rent Allowances :"<<hra<<"\n";
cout<<"Provident Fund :"<<pf<<"\n";
cout<<"Total Salary :"<<salary<<"\n";
cout<<"Grade :"<<grade;
}
};
class pay:public employee
{
public:
void calculate()
{
da=bp*5/100;
hra=bp*10/100;
pf=bp*6/100;
salary=(bp+da+hra)-pf;
if(bp>=50000)
grade='A';
else if((bp>=30000)&&(bp<50000))
grade='B';
else if((bp>=10000)&&(bp<30000))
grade='C';
else if(bp<10000)
grade='D';
}
};
main()
{
clrscr();
employee e;
pay p;
p.get();
p.calculate();
p.display();
getch();
return 0;
}

OUTPUT:
==========
Enter Employee Number:
08ca037
Enter Employee Name:
C.prabu
Enter Employee Department:
BCA
Enter Basic Salary:
7000

Employee Details
=================
Employee Number : 08ca037
Employee Name : C.Prabu
Department : BCA
Basic Pay : 7000
Dearness Allowances : 350
House Rent Allowances : 700
Provident Fund : 420
Total Salary : 7630
Grade :D

5. PROGRAM TO CREATE A CLASS SHAPE WHICH CONSISTS OF TWO VIRTUAL


FUNCTIONS TO CALCULATE AREA AND PERIMETER OF VARIOUS FIGURES
#include<iostream.h>
#include<conio.h>
class shape
{
protected:
double X,Y;
public:
void set_dim(double i,double j=0)
{
X=i;
Y=j;
}
virtual void show_area(void)
{
cout<<"No area computation defined for this class \n";
}
};
class triangle:public shape
{
public:
void show_area(void)
{
cout<<"\n Area of Triangle :"<<X*0.5*Y<<"\n";
}
};
class square:public shape
{
public:
void show_area(void)
{
cout<<"\n Area of Square :"<<X*Y<<"\n";
}
};
class circle:public shape
{
public:
void show_area(void)
{
cout<<"\n Area of Circle :"<<3.14*X*X;
}
};
main(void)
{
clrscr();
shape *p;
triangle t;
square s;
circle c;
cout<<"Area of Different Shapes Using Function Overloading\n";
cout<<"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ \n";
p=&t;
p->set_dim(10.0,5.0);
p->show_area();
p=&s;
p->set_dim(10.0,5.0);
p->show_area();
p=&c;
p->set_dim(9,0);
p->show_area();
getch();
return 0;
}

OUTPUT:
=========

Area of Different Shapes Using Function Overloading


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Area of Triangle: 25

Area of Square: 50

Area of Circle: 254.34

6. PROGRAM USING FUNCTION OVERLOADING TO READ TWO MATRICES & FIND


OUT THE SUM AND DISPLAY THE ABOVE TWO MATRICES

#include<iostream.h>

#include<conio.h>

class matrix

int m,n;

public:

void get()

cout<<”\n Enter Number of Rows \n”;

cin>>m;

cout<<”\n Enter Number of Columns \n”;

cin>>n;

void sum()

int i, j;

float a[10][10], b[10][10], c[10][10];

cout << "\n Enter the elements of first matrix: ";

for (i=0; i<m; i++)

for (j=0; j < n; j++)

cin>>a[i][j];
}

cout << "\n Enter the elements of second matrix: ";

for (i=0; i<m; i++ )

for (j=0; j<n; j++ )

cin>>b[i][j];

for (i=0; i<m; i++)

for (j=0; j<n; j++)

c[i][j]=a[i][j]+b[i][j];

cout<<c[i][j]<<"\t ";

cout<<”\n>

};

int main()

matrix cp;

matrix cp1;

cout<<”\n Enter Integer Matrix: \n”;

cp.get( );

cout<<”\n Addition of Integer Matrix: \n”;

cp.sum( );

cout<<”\n Enter float Matrix: \n”;

cp1.get();

cout<<”\n Addition of Float Matrix: \n”;


cp1.sum( );

getch( );

return 0;

OUTPUT:

=========

Enter Integer Matrix:

Enter Number of Rows: 2

Enter Number of Columns: 2

Addition of Integer Matrix:

Enter the elements of first matrix:

Enter the elements of second matrix:

5 5

5 5

Enter Float Matrix:

Enter Number of Rows: 2

Enter Number of Columns: 2

Addition of Float Matrix:

Enter the elements of first matrix:

2.1

2.1

2.1

2.1

Enter the elements of second matrix:


3.2

3.2

3.2

3.2

5.3 5.3

5.3 5.3

7. PROGRAM TO CONVERT INFIX EXPRESSION INTO POSTFIX EXPRESSION USING


ARRAYS
#include<iostream.h>
#include<math.h>
#include<ctype.h>
char a[30];
int top=-1;
void push(char c)
{
top=top+1;
a[top]=c;
}
char pop()
{
char d;
if(top==-1)
return -1;
else
{
d=a[top];
top=top-1;
return d;
}
}
int priority(char c)
{
if(c=='(')
return 0;
else if
(c=='+' || c=='-')
return 1;
else if
(c=='*' || c=='/')
return 2;
}
int main()
{
char exp[20];
char *e,x;
cout<<"Enter the expression:"<<endl;
cin>>exp;
e=exp;
while(*e!='\0')
{
if(isalnum(*e))
cout<<*e;
else if(*e=='(')
push(*e);
else if(*e==')')
{
while((x=pop())!='(')
cout<<x;
}
else
{
while(priority(a[top])>=priority(*e))
cout<<pop();
push(*e);
}
e++;
while(top!=-1)
{
cout<<pop();
}
}}

OUTPUT:
=========
Enter the expression:
a+b

ab+
8. PROGRAM TO CREATE A CLASS STACK BY USING CONSTRUCTOR TO INITIALIZE
THE TOP OF THE STACK & PERFORM PUSH, POP & CHECK FOR OVERFLOW AND
UNDERFLOW CONDITIONS
# include<iostream.h>
#include<conio.h>
class Stack
{
int top;
public:
int a[10];
Stack()
{
top = -1;
}
void push(int x);
int pop();
void isEmpty();
};
void Stack::push(int x)
{
if(top >= 10)
{
cout << "Stack Overflow \n";
}
else
{
a[++top] = x;
cout << "Element Inserted \n";
}
}
int Stack::pop()
{
if(top < 0)
{
cout << "Stack Underflow \n";
return 0;
}
else
{
int d = a[top--];
return d;
}
}
void Stack::isEmpty()
{
if(top < 0)
{
cout << "Stack is empty \n";
}
else
{
cout << "Stack is not empty \n";
}
}
int main()
{
Stack s1;
s1.push(10);
s1.push(100);
getch();
retuen 0;
}
OUTPUT:
=========
Element Inserted

Element Inserted

9. PROGRAM TO CHECK WHETHER THE GIVEN STRING IS A PALINDROME OR NOT


USING POINTERS
#include<iostream.h>
#include <conio.h>
#include<string.h>
int main()
{
char *a;
int i,len,flag=0;
clrscr();
cout<<"\n Enter the String: ";
cin>>a;
len=strlen(a);
for (i=0;i<len;i++)
{
if(a[i]==a[len-i-1])
flag=flag+1;
}
if(flag==len)
cout<<"\n THE STRING IS PALINDROME";
else
cout<<"\n THE STRING IS NOT PALINDROME";
getch();
return 0;
}
OUTPUT:
=========

Enter the String: prabu


THE STRING IS NOT PALINDROME

Enter the String: malayalam


THE STRING IS PALINDROME

10. PROGRAM TO MERGE TWO FILES INTO SINGLE FILE

#include<iostream.h>

#include<conio.h>

#include<fstream.h>

#include<stdio.h>

#include<stdlib.h>

void main()

clrscr();

ifstream ifiles1, ifiles2;

ofstream ifilet;

char ch, fname1[20], fname2[20], fname3[40];

cout<<”\n Enter first file name (with extension like file1.txt):”;

gets(fname1);

cout<<”\n Enter second file name (with extension like file1.txt):”;

gets(fname2);

cout<<”\n Enter name of file (with extension like file3.txt) which will store the contents of the two
files (fname1 & fname2):”;

gets(fname3);

ifiles1.open(fname1);

ifiles2.open(fname2);

if(ifiles1==NULL || ifiles2==NULL)
{

perror(“\n Error message”);

cout<<\n Press any key to exit….”;

getch();

exit(EXIT_FAILURE);

}
ifilet.open(fname3);

if(!ifilet)

perror(“\n Error message”);

cout<<\n Press any key to exit….”;

getch();

exit(EXIT_FAILURE);

while(ifiles1.eof()==0)

ifiles1>>ch;

ifilet<<ch;

while(ifiles2.eof()==0)

ifiles2>>ch;

ifilet<<ch;

}
cout<<”\n The two files were merged into ”<<fname3<<” file successfully..!!”;

ifiles1.close();

ifiles2.close();

ifilet.close();

getch();

}
OUTPUT:

=========

Enter first file name (with extension like file1.txt): BCA.txt

Enter second file name (with extension like file2.txt): CS.txt

Enter name of file (with extension like file3.txt) which will store the contents of the two files
(fname1 & fname2): BCA & CS.txt

The two files were merged into BCA & CS.txt file successfully..!!

You might also like