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.
2
Object Oriented Programming with C++
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.
3
Object Oriented Programming with C++
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.
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.
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:
5
Object Oriented Programming with C++
8. MESSAGE PASSING:
Objects can communicate one another by sending and receiving information.
The steps are as follow:
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
6
Object Oriented Programming with C++
APPLICATIONS OF OOPS
The applications of OOPs include:
• Real-time system
• 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
7
Object Oriented Programming with C++
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.
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.
9
Object Oriented Programming with C++
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()
{
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;
15
Object Oriented Programming with C++
iii. Class
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
16
Object Oriented Programming with C++
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)
17
Object Oriented Programming with C++
18
Object Oriented Programming with C++
int k=m;
int m=30;
cout<<”\n inner block”;
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:
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.
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.
23
Object Oriented Programming with C++
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
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
}
26
Object Oriented Programming with C++
Block Diagram
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)
{
27
Object Oriented Programming with C++
cout<<“First Class\n”;
}
else if(percentage >= 50)
{
cout<<“Second Class\n”;
}
else if(percentage >=40)
{
cout<<“Pass Class\n”;
}
else
{
cout<<“Fail\n”;
}
FLOWCHART
test False
condition-1
True
test False
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.
28
Object Oriented Programming with C++
Syntax:
switch(variablename)
{
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
Statement-5
Each compound statement of a switch case should contain break statement to exit
from case.
29
Object Oriented Programming with C++
Easy to use.
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”;
}
DECISION MAKING AND LOOPING
while statement: An entry controlled loop
Syntax: while(condition)
{
Action1;
}
Action-2;
Example:
main()
{
int i=0;
while(i<10)
{
30
Object Oriented Programming with C++
Syntax:
do
Action-1;
}while(condition);
Action-2;
Example:
main()
int i=0;
do
cout<<‟value of i=”<<i;
i++;
}while(i<10);
31
Object Oriented Programming with C++
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
32
Object Oriented Programming with C++
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.
33
Object Oriented Programming with C++
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.
34
Object Oriented Programming with C++
UNIT-II
FUNCTION:
35
Object Oriented Programming with C++
Function Prototype:
36
Object Oriented Programming with C++
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.
37
Object Oriented Programming with C++
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).
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.
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
40
Object Oriented Programming with C++
CONST ARGUMENT
FUNCTION OVERLOADING
41
Object Oriented Programming with C++
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);
}
42
Object Oriented Programming with C++
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,
class class_name
{
private:
variable declarations;
function declarations;
public:
variable declarations;
function declarations;
};
43
Object Oriented Programming with C++
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.
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;
44
Object Oriented Programming with C++
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;
}
};
45
Object Oriented Programming with C++
46
Object Oriented Programming with C++
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;
}
47
Object Oriented Programming with C++
48
Object Oriented Programming with C++
49
Object Oriented Programming with C++
50
Object Oriented Programming with C++
ARRAY OF OBJECTS
Array of variable that are of the type class are called as array of objects.
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;
}
51
Object Oriented Programming with C++
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.
52
Object Oriented Programming with C++
53
Object Oriented Programming with C++
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;
}
54
Object Oriented Programming with C++
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
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)
55
Object Oriented Programming with C++
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 ::
56
Object Oriented Programming with C++
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)
{
57
Object Oriented Programming with C++
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);
};
58
Object Oriented Programming with C++
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.
59
Object Oriented Programming with C++
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);
60
Object Oriented Programming with C++
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
61
Object Oriented Programming with C++
62
Object Oriented Programming with C++
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.
63
Object Oriented Programming with C++
Types of constructor:
1. Default constructors
2. Parameterized constructors
3. Copy constructors
64
Object Oriented Programming with C++
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.
65
Object Oriented Programming with C++
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.
66
Object Oriented Programming with C++
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()
{
67
Object Oriented Programming with C++
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.
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?
69
Object Oriented Programming with C++
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.
70
Object Oriented Programming with C++
71
Object Oriented Programming with C++
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 +.
Examples:
Create a class that defines the data type that is to be used in the overloading operation
72
Object Oriented Programming with C++
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;
}
73
Object Oriented Programming with 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
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;
74
Object Oriented Programming with C++
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;
}
76
Object Oriented Programming with C++
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
77
Object Oriented Programming with C++
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.
78
Object Oriented Programming with C++
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;
}
80
Object Oriented Programming with C++
};
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
81
Object Oriented Programming with C++
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
82
Object Oriented Programming with C++
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;
}
83
Object Oriented Programming with C++
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;
}
};
84
Object Oriented Programming with C++
Example:
#include <iostream.h>
class A
{
85
Object Oriented Programming with C++
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
86
Object Oriented Programming with C++
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;
} };
87
Object Oriented Programming with C++
Example:
class A
{
public:
int i;
};
class B : virtual public A
{
public:
int j; };
88
Object Oriented Programming with C++
class AB
public:
};
Function AB::f is a pure virtual function. A function declaration cannot have both a pure
specifier and a definition.
89
Object Oriented Programming with C++
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
90
Object Oriented Programming with C++
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;
}
91
Object Oriented Programming with C++
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.
92
Object Oriented Programming with C++
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( );
93
Object Oriented Programming with C++
Example:
virtual void display ( ) = 0;
94
Object Oriented Programming with C++
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.
95
Object Oriented Programming with C++
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();
96
Object Oriented Programming with C++
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.
97
Object Oriented Programming with C++
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
98
Object Oriented Programming with C++
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”;
99
Object Oriented Programming with C++
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
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;
101
Object Oriented Programming with C++
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.
F)resetiosflag(arg 2)
This function is used to reset set flags for output.
102
Object Oriented Programming with C++
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;
}
103
Object Oriented Programming with C++
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.
104
Object Oriented Programming with C++
105
Object Oriented Programming with C++
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”);
------
106
Object Oriented Programming with C++
------
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;
}
107
Object Oriented Programming with C++
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();
108
Object Oriented Programming with C++
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
109
Object Oriented Programming with C++
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:
110
Object Oriented Programming with C++
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;
111
Object Oriented Programming with C++
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
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()
{
112
Object Oriented Programming with C++
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;
113
Object Oriented Programming with C++
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);
114
Object Oriented Programming with C++
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())
115
Object Oriented Programming with C++
{
--- (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[])
argvknown as argument vector is an array of char type pointers that points to command
line argument.
Eg:
116
Object Oriented Programming with C++
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);
117
Object Oriented Programming with C++
cout<<ch;
}
while(fin);
fin.close();
}
return 0;
}
118
Object Oriented Programming with C++
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;
}
119
Object Oriented Programming with C++
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
120
Object Oriented Programming with C++
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.
121
Object Oriented Programming with C++
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)
122
Object Oriented Programming with C++
{
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.
123
Object Oriented Programming with C++
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.
124
Object Oriented Programming with C++
125
Object Oriented Programming with C++
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
126
Object Oriented Programming with C++
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.
128
Object Oriented Programming with C++
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;
}
129
Object Oriented Programming with C++
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);
130
Object Oriented Programming with C++
}
}
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.
131
Object Oriented Programming with C++
#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)
132
Object Oriented Programming with C++
{
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
133
Object Oriented Programming with C++
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
134
Object Oriented Programming with C++
{
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.
135
Object Oriented Programming with C++
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; }
136
Object Oriented Programming with C++
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
137
Object Oriented Programming with C++
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.
138
Object Oriented Programming with C++
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.
139
Object Oriented Programming with C++
140
Object Oriented Programming with C++
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.
141
Object Oriented Programming with C++
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;
142
Object Oriented Programming with 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)
143
Object Oriented Programming with C++
{
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; }
144
Object Oriented Programming with C++
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";
146
Object Oriented Programming with C++
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;
}
147
Object Oriented Programming with C++
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
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;
}
149
Object Oriented Programming with C++
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;
150
Object Oriented Programming with C++
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();
cp1.sum( );
getch( );
return 0;
OUTPUT:
=========
5 5
5 5
2.1
2.1
2.1
2.1
3.2
3.2
3.2
3.2
5.3 5.3
5.3 5.3
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+
154
Object Oriented Programming with C++
155
Object Oriented Programming with C++
{
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
156
Object Oriented Programming with C++
#include<iostream.h>
#include<conio.h>
#include<fstream.h>
#include<stdio.h>
#include<stdlib.h>
void main()
157
Object Oriented Programming with C++
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);
158
Object Oriented Programming with C++
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..!!
159