Object Oriented Programming With C++
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:
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.
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:
8. MESSAGE PASSING:
Objects can communicate one another by sending and receiving information.
The steps are as follow:
5
Object Oriented Programming with C++
BENEFITS OF OOPs
APPLICATIONS OF OOPS
The applications of OOPs include:
• Real-time system
6
Object Oriented Programming with C++
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.
Include Files
Class declaration
Member functions definitions
Main function program
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.
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.
{
// 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”;
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
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.
Invalid Identifiers
11
Object Oriented Programming with C++
Constants: Constants refer to values that do not change during the execution of the
program.
Constants
Constants
Decimal Octal constant Hexadecimal
constant constant
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.
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;
13
Object Oriented Programming with C++
Example: Stack_pop();
Operators: The symbol that perform certain logical operations are called operator.
Example: =,==,!=,<,>.
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++
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
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++
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.
19
Object Oriented Programming with C++
Using new operator, we can create memory space for any data-type including user-
defined type such as array, structure, class.
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.
Example: delete p;
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;
Example: cout<<setw(5)<<a;
1 2 3
Example: avg=sum/float(i);
const-cast dynamic-cast
static-cast reinterpret-cast
21
Object Oriented Programming with C++
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.
3. Float expression: After all conversion, this produces floating point result.
Example: x+y 5\2 5*float(10)
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
22
Object Oriented Programming with C++
IMPLICIT CONVERSION
Whenever data types are mixed in an expression, C++ performs the automatic conversion. It
is known as implicit (or) automatic type conversion.
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++
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
24
Object Oriented Programming with C++
25
Object Oriented Programming with C++
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++
False
test
condition-1
True
False
test
condition-2
True
False
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++
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
Statement-5
Each compound statement of a switch case should contain break statement to exit
from case.
Easy to use.
29
Object Oriented Programming with C++
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
Syntax:
do
Action-1;
}while(condition);
Action-2;
Example:
main()
{
int i=0;
do
cout<<’value of i=”<<i;
i++;
}while(i<10);
Flowchart
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:
Function Prototype:
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);
}
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).
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.
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
FUNCTION OVERLOADING
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,
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;
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.
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;
}
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
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.
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
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.
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 ( .*)
Conditional operator (? :)
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.
Examples:
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
The unary operators operate on a single operand and following are the examples of Unary
operators.
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;
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.
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.
{
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.
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.
class AB
{
public:
};
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
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.
Dynamic Polymorphism
The associated function call is made dynamically at runtime is called run time
polymorphism.
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.
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.
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
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
E) cin
It is the method to take input any 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
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 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
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.
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.
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;
}
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:
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.
Syntax: Stream-object-open(“filename”,mode);
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();
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
Syntax:
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
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;
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:
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)
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.
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[])
Eg:
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
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:
#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
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.
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.
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;
Catching Mechanism
The code for handling exceptions is included in catch blocks.
#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
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
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.
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.
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
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
OUTPUT:
=========
Area of Triangle: 25
Area of Square: 50
#include<iostream.h>
#include<conio.h>
class matrix
int m,n;
public:
void get()
cin>>m;
cin>>n;
void sum()
int i, j;
cin>>a[i][j];
}
cin>>b[i][j];
c[i][j]=a[i][j]+b[i][j];
cout<<c[i][j]<<"\t ";
cout<<”\n>
};
int main()
matrix cp;
matrix cp1;
cp.get( );
cp.sum( );
cp1.get();
getch( );
return 0;
OUTPUT:
=========
5 5
5 5
2.1
2.1
2.1
2.1
3.2
3.2
3.2
5.3 5.3
5.3 5.3
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
#include<iostream.h>
#include<conio.h>
#include<fstream.h>
#include<stdio.h>
#include<stdlib.h>
void main()
clrscr();
ofstream ifilet;
gets(fname1);
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)
{
getch();
exit(EXIT_FAILURE);
}
ifilet.open(fname3);
if(!ifilet)
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 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..!!