Programming in C++ For BCA BIT BE PDF
Programming in C++ For BCA BIT BE PDF
“The workers and professionals of the world will soon be divided into two distinct groups:
those who will control computers and those who will be controlled by the computers. It
would be best for you to be in the former group.” – Lewis D. Eigen
object oriented
procedural
assembly
m/c
language
language
language
language
The binary system is based on two digits viz. 0 and 1. M/C language consists of a stream
of 0 and 1 having different combination and different meaning. eg.
11110010 01110011 11010010 00010000 01110000 00101011.
Assembly language was abbreviation and mnemonic code (codes more easily memorized) to
replace the 0s and 1s of machine language. This could be expressed in assembly language
(LDA, ADD) statement as
PACK 210(8, 13), 02B(4, 7)
Procedure-Oriented Programming:
Conventional Programming, using high level languages such as COBOL (Common
Business Oriented Language), FORTAN (Formula Translation) and C, is commonly called
as procedural oriented programming (POP). POP basically consists of writing a list of
instructions (or actions) for the computer to follow, and organizing these instructions into
groups known as function. A typical program structure for procedural programming is shown
in the figure below. The technique of hierarchical decomposition has been used to specify the
task to be completed for solving a problem.
Page: 2 of 128
Main Program
Function-4 Function-5
In a multi-function program, many important data items are placed as globally. So that
they may be accessed by all the functions. Each function may have its own local data. The
figure shown below shows the relationship of data and function in a procedure-oriented
program.
Global Data Global Data
object A object B
Data Data
communication
Functions Functions
object C
Functions
Data
The data of an object can be accessed only by the function associated with that object.
However, functions of one object can access the function of other objects.
Some features of object oriented programming are:
Emphasis is on data rather than procedure.
Programs are divided into what are called objects.
Data structures are designed such that they characterize the objects.
Functions that operate on the data of an object are tied together in the data structure.
Data is hidden and cannot be accessed be external functions.
Objects may communicate with each other through functions.
New data and functions can be easily added whenever necessary.
Follows bottom-up approach in program design.
Objects:
Objects are the basic run-timePage: 4 ofin
entities 128
an object-oriented language. They may
represent a person, a place, a bank account, a table of data or any item that the program has to
Downloaded From: www.bhawesh.com.np
. 4
Object Oriented . Downloaded From: www.bhawesh.com.np
Programming in C++
handle. They may also represent user-defined data such as vectors, time and lists. Program
objects should be chosen such that they match closely with the real-world objects. Objects
take up space in the memory. E.g.
Object : STUDENT
STUDENT
DATA
Name
Total
Date of Birth
Marks Average
------
FUNCTIONS Display
Total Average, Display
------
Classes:
A class is a collection of objects of similar types. Classes are user-defined data types
and behaves like the built-in types of a programming language. A class also consists method
(i.e. function). So, both data and functions are wrapped into a single class.
Inheritance:
It is the process by which objects of one class acquire the properties of another class. It
supports the concept of hierarchical classification. In OOL, the concept of inheritance
provides idea of reusability. Eg.
Bird
Attributes
Feathers
lay eggs
Reusability:
Object-oriented programs are built from reusable software components. Once a class is
completed and tested, it can be distributed to other programmers for use in their own
programs. This is called reusability. If those programmers want to add new features or change
the existing ones, new classes can be derived from existing one. Reusability reduces the time
of software development.
One of the benefits of objects is that they give the programmer a convenient way to
construct new data types. Suppose, you work with two-dimensional position (such as X & Y
co-ordinates, or latitude and longitude) in your program. You would like to express operation
on these positional values with normal arithmetic operations, such as
position1=position2+origin ;
where, the variables position1, position2 and origin each represent a pair of independent
numerical quantities. By creating a class that incorporates these two values and declaring
position1, position2 and origin to be objects of this class, we can, in effect, create a new data
types in this manner.
Polymorphism and Overloading:
Polymorphism is another important characteristics of OOL. Polymorphism, a Greek
term, means the ability to take more than one form. The process of making an operator to
exhibit different behaviours in different instances is known as operator overloading. Using a
single function name to perform different types of tasks is known as function overloading.
For example,
consider the operation of addition. For two numbers, the operation will generate a sum.
If the operands are strings, then the operation would produce a third string by concatenation.
A single function name can be used to handle different number and different types of
arguments as in figure.
Shape
Draw( )
Page: 7 of 128
Keywords:
The keywords implement specifies C++ language features. They are explicitly reserved
identifiers and cannot be used as names for the program variables or other user-defined
program elements. Many of the keywords are common to both C and C++.
Constants refer to fixed values that do not change during. They include integers,
characters, floating point numbers and strings. Constants do not have memory location.
Examples are:
123 // decimal
12.37 // floating point
“C++” // string constant
Page: 8 of 128
Built-in-type is also known as basic or fundamental data type. The basic data type may
have several modifiers preceding them to serve the needs of various situations except void.
The modifier signed, unsigned, long and short may be applied to character and integer basic
data types. Long modifier may also be applied to double data type representation in memory
in terms of size (Bytes)
Type Bytes
char 1 long int 4
unsigned char 1 signed int 4
signed char 1 unsigned int 4
int 2 float 4
unsigned int 2 double 8
signed int 2 long-double 10
short int 2
unsigned int 2
signed int 2
Pointers:
Pointers are declared and initialized as in C. Examples:
int * ip ; // integer pointer
ip = &x ; // address of x assigned to ip
ip = 10 ; // 10 assigned to x through indirection.
C++ adds the concept of constant pointer and pointer to a constant.
char *const ptr1 = “Good” // constant pointer
We cannot modify the address that pointer1 is initialized to
int const *ptr2 = &m // pointer to a constant
ptr 2 is declared as pointer to a constant. It can point to any variable of correct type, but
the contents of what it pointers to not be changed.
We can also declare both the pointer and the variable as constants in the following way:
pointers are extensively used in C++ for memory management & achieve polymorphism.
};
detain in chapter (4)
Suppose in a C program there are two variables with the same name a. Assume that one
has become declared outside all functions (global) and another is declared locally inside a
function. Now, if we attempt to access the variable a in the function we always access the
local variable. This is because the rule says that whenever there is a conflict between a local
and a global variable, local variable gets the priority. C++ allows you the flexibility of
accessing both the variables. It achieves through a scope resolution operator (: :).
Demotion:
Demotion occurs whenever a variable or expression of a larger type gets converted to
smaller type. Bye default, a floating point number is considered as a double number in C++.
int a=7.5 // double gets down – converted to int ;
int b=7.0f ; // float gets down – converted to int
char c=b ; // int gets down – converted to char
Standard Automatic demotion can result in the loss of information. In the first example
the variable ‘a’ will contain the value 7, since int variable cannot handle floating point values.
We can also initialize the memory using new operator. This is done as
pointer_variable=new data-type(value)
For e.g.
int *p=new int(25) ;
float *q=new float(7.5) ;
New can be used to create a memory space for any data type including user-defined
types such as arrays, structures and classes. The general form for a one-dimension array is
pointer_variable=new data_type[size] ;
Here, size specifies the number of elements in the array. For example,
int *p=new int[10] ; creates a memory space for an array of 10 integers.
Delete:
When a data object is no longer needed, it is destroyed to release the memory space for
reuse. For this purpose, we use delete unary operator. The general syntax is
delete pointer_variable
The pointer_variable is the pointer that points to a data object created with new. For e.g.
delete p ;
delete q ;
If we want to free a dynamically allocated array, we must use the following form of
delete.
delete [size] pointer_variable ;
The size specifies the number of elements in the array to be freed. The problem with
this form is that the programmer should remember the size of the array. Recent version of
C++ do not require the size to be specified.
Control Flow:
1) Conditional Statement : if, if else, nested if else
2) Repetitive Statement : Page:
for, loop while,
13 of 128 do while
3) Breaking Control Statement : break statement, continue, go to
Downloaded From: www.bhawesh.com.np
. 13
Object Oriented . Downloaded From: www.bhawesh.com.np
Programming in C++
Manipulators:
Manipulators are operators that are used to format the data display. The most commonly
used manipulators are endl and setw.
The endl manipulator, when used in an output statement, causes a linefeed to be
inserted. It has the same effect as using the new line character “\n”.
cout<< “m=” <<m <<endl ;
2.5 Const:
The keyword const(for constant), if present, precedes the data type of a variable. It
specifies that the value of the variable will not change throughout the program. Any attempt
to alter the value of the variable defined with this qualifier will result into an error message
from the compiler. Const is usually used to replace defined constant. Variables with this
qualifier are often named in all uppercase, as a reminder that they are constants. The
following program shows the usage of const.
#include <iostream.h>
#include <conio.h>
void main( )
{
clrscr( );
float r, a ;
const float PI=3.14 ;
cout<<“Enter r:”<< endl ;
cin>>r ;
a = PI*r*r ;
cout<<endl<< “Area of circle=”<<a ;
getch( );
}
Each enumerated data type retains its own separate. This means that C++ doesn’t permit
an int value to be automatically converted to an enum value. e.g.
color background = blue ; // allowed
color background = 7 ; // Error in C++
color background = color(7) ; // ok
By default, the enumerators are assigned integers values starting with 0 for the first
enumerator, 1 for the second and so on. e.g.
enum color(red, blue = 4, green=8) ;
enum color(red=5, blue, green) ; are valid definitions. In first case, red is 0 by default.
On second case, blue is 6 and green is 7. Note that the subsequent initialized enumerators are
larger by one than their predecessors.
2.7 Comments:
C++ introduces a new comment symbol // [double slash]. Comments start with a double
slash symbol and terminate at the end of the line. A comment may start anywhere in the line
and whatever follows till the end of the line ignored. Note that there is no closing symbol.
The double slash comment is basically a single line comment. Multiple comments can
be written as
// This is an example of
// C++ program to illustrate
// some of its features
The C comments symbols / * , * / are still valid and are more suitable for multiple line
comments. The above comment is written as:
/* This is an example of C++ program to illustrate some of its features */
cout:
The identifier cout (pronounced as ‘C out’) is a predefined object that represents the
standard output stream in C++.
The operator << is called insertion (or put to) operator. It inserts the contents of the
variable on its right to the object on its left. For e.g.
cout << “Number”Page:; 15 of 128
cin:
The identifier cin (pronounced as ‘C in’) is a predefined object in C++ that corresponds
to the standard input stream. Here, this stream represents the keyword.
The “>>” operator is known as extraction (or get from) operator. It extracts (or takes)
the value form the keyboard and assigns it to the variable on its right. This corresponds to the
familiar scanf( ) operation. “>>” is bit-wise right shift operator.
Page: 16 of 128
Page: 17 of 128
Syntax of function:
void show( ) ; / * Function declaration * /
main ( )
{
------
------
show( ) ; / * Function call * /
}
void show( ) / * Function definition * /
{
------
- - - - - - / * Function body * /
------
}
When the function is called, control is transferred to the first statement in the function
body. The other statements in the function body are then executed and controls return to the
main program when the closing brace is encountered. C++ has added many new features to
functions to make them more reliable and flexible.
Function Prototyping:
Function prototyping is one of the major improvements added to C++ functions. The
prototype describes the function interface to the compiler by giving details such as the
number and type of arguments and the type of return values. Any violation in matching the
arguments or the return types will be caught by the compiler at the time of compilation itself.
These checks and controls did not exist in the conventional C functions.
Function prototype is a declaration statement in the calling program and is of of the
following form:
The argument_list contains the types and names of arguments that must be passed to the
function. E.g.
float volume(int x, int y, float z) ; // prototype
Page: 18 of 128 // legal
float volume (int x, int y, z) ; // illegal
Downloaded From: www.bhawesh.com.np
. 18
Object Oriented . Downloaded From: www.bhawesh.com.np
Programming in C++
Passing Arguments to Function:
An argument is a data passed from a program to the function. In function, we can pass a
variable by three ways:
1. Passing by value
2. Passing by reference
3. Passing by address or pointer
Passing by value:
In this the value of actual parameter is passed to formal parameter when we call the
function. But actual parameter are not changed.
#include <iostream.h>
#include<conio.h>
// declaration prototype
void swap(int, int) ;
void main ( ) {
int x,y ; clrscr( ) ;
x=10 ;
y=20 ;
swap(x,y) ;
cout << “x =” <<x<<endl ;
cout<< “y =” <<y<<endl ;
getch( ) ;
void swap(int a, int b) // function definition
{
int t ;
t=a ;
a=b ;
b=t ;
}
Output:
x=10
y=20
Passing by reference:
Passing argument by reference uses a different approach. In this, the reference of
original variable is passed to function. But in call by value, the value of variable is passed.
The main advantage of passing by reference is that the function can access the actual
variable one value in the calling program. The second advantage is this provides a
mechanism for returning more than one 19
Page: value from the function back to the calling program.
of 128
Page: 22 of 128
int main( )
{
clrscr( );
if (even(10)) cout<< “10 is even \n” ;
if (even(11)) cout<< “11 is even \n” ;
return 0 ;
getch( );
}
Output: 10 is even.
Page: 23 of 128
The specifier starts with keyword class, followed by the name smallobj in this example.
The body of the class is delimited by braces and terminated by a semicolon. The class
smallobj specified in this program contains one data member item and two member functions.
The dot operator is also called “class member access operator.”
void main( )
{ clrscr( );
rectangle r1, r2, r3 ; //define three objects of class rectangle
r1.setdata(10, 20) ; //setdata in elements of the object.
r1.displaydata( ) ; //display the data set by setdata( )
r1.area_Peri( ) ; //calculate and print area and perimeter
r2.setdata(5, 8) ;
r2.displaydata( ) ;
r2.area_Peri( ) ;
r3.getdata( ) ; //receive data from keyboard
r3.displaydata( ) ;
r3.area_Peri( ) ;
getch ( );
}
Output:
length 10
breadth 20
area 200
perimeter 60 Page: 26 of 128
length 5
Downloaded From: www.bhawesh.com.np
. 26
Object Oriented . Downloaded From: www.bhawesh.com.np
Programming in C++
breadth 8
area 40
perimeter 26
enter length and breadth 2 4
length 2
breadth 4
area 8
perimeter 12
#include <iostream.h>
#include<conio.h>
class rectangle
{
Private: int len, br ;
Public:
void getdata( ) ;
void setdata(int l, int b) ; Page: 28 of 128
};
Downloaded From: www.bhawesh.com.np
. 28
Object Oriented . Downloaded From: www.bhawesh.com.np
Programming in C++
void showdata( )
{
cout<< “i is” <<i<<endl ; //one way to display data
cout<< “my object address is” <<this<<endl ;
cout<< “num is” this i ; //another way to display
}
};
void main( )
{ clrscr( );
thisemp e1 ;
e1.setdata(10) ;
e1.showdata( ) ;
getch( );
}
Output:
i is 10
my object address is ×121bfff4
num is 10
e.g. 2
// A Function Friendly to two classes
#include <iostream.h>
class ABC ; // Forward declaration
class XYZ Page: 39 of 128
{
Downloaded From: www.bhawesh.com.np
. 39
Object Oriented . Downloaded From: www.bhawesh.com.np
Programming in C++
int x ;
public:
void setdata (int i)
{
x=i ; }
friend void max (XYZ, ABC) ;
};
class ABC
{
int a ;
public:
void setdata (int i)
{ a=i ; }
friend void max(XYZ, ABC) ; } ;
e.g. 3
#include <iostream.h> //Program swapping private data of classes
class class2 ; // Forward declaration
class class1
{
int value1 ; Page: 40 of 128
public:
Downloaded From: www.bhawesh.com.np
. 40
Object Oriented . Downloaded From: www.bhawesh.com.np
Programming in C++
void indata (int a)
{ value1=a ; }
void display(void)
{ cout<<value1<, “\n” ; }
friend void exchange (class1 &, class2 &) ;
};
class class2
{
int value2 ;
Public:
void indata (int a)
{ value2=a ; }
void display(void)
{ cout<<value2<< “\n” ; }
friend void exchange(class1 &, class2 &) ;
};
void exchange(class1 &x, class2 &y)
{
int temp=x.value1 ;
x.value1=y.value2 ;
y.value2=temp ;
}
int main( )
{
class1 c1 ;
class2 c2 ;
c1.indata(100) ;
c2.indata(200) ;
cout<< “Value before exchange”<< “\n” ;
c1.display( ) ;
c2.display( ) ;
exchange(c1, c2) ; //swapping
cout<< “Values after exchange”<< “\n” ;
c1.display( ) ;
c2.display ( ) ;
return 0 ; }
Output:
values before exchange Page: 41 of 128
100
Downloaded From: www.bhawesh.com.np
. 41
Object Oriented . Downloaded From: www.bhawesh.com.np
Programming in C++
200
values after exchange
200
100
Friend class can be done through same process like friend function and we will discuss
in next chapter constructor and destructor.
Page: 42 of 128
Characteristics of constructor
1. Constructor has same name as that of its class name.
2. It should be declared in public section of the class.
3. It is invoked automatically when objects are created.
4. It cannot return any value because it does not have a return type even void.
5. It cannot have default arguments.
6. It cannot be a virtual function and we cannot refer to its address.
7. It cannot be inherited.
8. It makes implicit call to operators new and delete when memory allocation is
required.
e.g.
#include <iostream.h>
Page: 43 of 128
#include <conio.h>
Downloaded From: www.bhawesh.com.np
. 43
Object Oriented . Downloaded From: www.bhawesh.com.np
Programming in C++
class sample
{
int a, b ;
public:
sample( )
{
cout<< “This is constructor” << endl ;
a=100; b=200 ; }
int add( )
{ return(a+b) ; }
};
void main( )
{
clrscr( ) ;
sample s ; //constructor called
cout<< “Output is:”<<s.add( )<<endl ;
getch( ) ;
}
Output:
This is constructor
Output is 300.
#include <iostream.h>
#include <conio.h>
class myclass {
int a ;
public:
myclass( ) ; // constructor
void show( ) ;
};
myclass : : myclass( ) {
cout<< “In constructor \n” ;
a=10 ;
}
void myclass: : show( ) {
cout<<a ; }
int main( ) {
clrscr( ) ;
myclass ob ;
ob.show( ) ;Page: 44 of 128
return 0 ;
Downloaded From: www.bhawesh.com.np
. 44
Object Oriented . Downloaded From: www.bhawesh.com.np
Programming in C++
getch( ) ;
}
Output:
In construtor : 10
#include <iostream.h>
#include <conio.h>
class xyz
{ int a,b ;
public: xyz (int a1, int b1)Page:
// Parameterized
45 of 128 constructor
{ a=a1 ; b= b1 }
Downloaded From: www.bhawesh.com.np
. 45
Object Oriented . Downloaded From: www.bhawesh.com.np
Programming in C++
int mul( )
{ return (a*b) ; }
};
void main( )
{
int i,j ;
clrscr( ) ;
cout<< “Enter first no. :” ;
cin>>i ;
cout<< “Enter second no.” ;
cin>>j ;
xyz c1(i, j) ;
cout<< “Multiplication is:” ;
cout<<c1.mul( )<<endl ;
getch( ) ; }
Output:
Enter first no. : 5
Enter second no. : 6
Multiplication is : 30
The statement abc c2 ; calls the no argument constructor while the statement abc c3(c2)
; called first constructor that is copy constructor. The statement abc c3=c2 also called copy
constructor.
The general syntax of copy constructor header is clas_name (class_name & object_ref).
In above example, we have written copy constructor as
abc (abc &c1)
{x=c1.x ; y=c1.y ; }
where abc is name of class ; c1 is reference of object.
E.g. 1
#include <iostream.h>
#include <conio.h>
class complex
{ int r, i ;
public: complex (int a, int b)
{r=a ; i=b ; }
complex (complex &c)
Page: 48 of 128
{r=c.r ; i=c.i ; }
Downloaded From: www.bhawesh.com.np
. 48
Object Oriented . Downloaded From: www.bhawesh.com.np
Programming in C++
void show( )
{cout<<r<< “+i”<<i<<endl ; }
};
void main( )
{ int x, y ;
clrscr( ) ;
cout<< “Enter real part:” ; cin>>x ;
cout<< “Enter imag part:” ; cin>>y ;
complex c1(x, y ) ; // 1stconstructor called
complex c2(c1) ; // copy constructor called
cout<<”First no. is: “ ;
c1.show( ) ;
cout<< “Second no. is:” ;
c2.show( ) ;
getch( ) ; }
Output:
Enter real part : 5
Enter imag part : 6
First no. is : 5+i6
Second no. is : 5+i6
e.g. 2
#include <iostream.h>
#include <conio.h>
class cons
{ int data ;
public: cons (int c) // Parameterized constructor
{ data=c ; }
cons (cons &a) //copy constructor
{ data=a.data ; }
void display( )
{cout<<data ; }
};
void main( ) {clrscr( ) ;
cons A(5) ;
cons B(A) ; // or cons B=A ;
cout<< “\n data in A:” ;
A.display( ) ;
cout<< “\n data in B:” ; Page: 49 of 128
B.display( ) ;
Downloaded From: www.bhawesh.com.np
. 49
Object Oriented . Downloaded From: www.bhawesh.com.np
Programming in C++
getch( ) ;
}
Output:
data in A : 5
data in B : 5
Destructors:
The complement of a constructor is the destructor. This function is called when an
object is destroyed. For example, an object that allocates memory when it is created will want
to free that memory when it is destroyed.
The name of a destroyer is the name of its class preceded by a ~. For a destructor, it
never takes any arguments not returns any value. Destructor will automatically be called by a
compiler upon exit from the program to clean up storage taken by objects. The objects are
destroyed in the reverse order from their creation in the constructor.
e.g. 1
#include <iostream.h>
class myclass { int a ;
public:
myclass( ) ; // constructor
~ myclass( ) ; // destructor
void show( ) ; } ;
myclass: : myclass( ) { Page: 50 of 128
cout<< “\n constructor \n” ;
Downloaded From: www.bhawesh.com.np
. 50
Object Oriented . Downloaded From: www.bhawesh.com.np
Programming in C++
a=10 ; }
myclass: :~ myclass( ) {
cout<< “Destructing .... \n” ;
}
e.g. 2
#include <iostream.h>
int count=0 ;
class alpha
{ public: alpha( ) {
cout ++ ;
cout << “\n No. of objects created”<<count ; }
~ alpha( )
{ cout<< “\n No. of object destroyed”<< count ;
count ...... ; }
};
void main( )
{ cout << “\n \n Enter main \n” ;
alpha A1, A2, A3, A4 ;
{ cout<< “\n \n Enter Block1\n” ;
alpha A5 ; }
{ cout<< “\n \n Enter Block2\n” ;
alpha A6 ; }
cout<< “\n \n Re-enter main\n” ; }
Output:
Enter main Re- Enter main
No. of objects created1 No. of objects destroyed4
No. of objects created2 No. of objects destroyed3
No. of objects created3 No. of objects destroyed2
No. of objects created4 No. of objects destroyed1
Enter Block1
No. of object created5
No. of object destroyed5
Enter Block2
No. of object created5
No of object destroyed5
Page: 53 of 128
6.1 Introduction:
Operator overloading is one of the feature of C++ language. The concept by which we
can give special meaning to an operator of C++ language is known as operator overloading.
For example, + operator in C++ work only with basic type like int and float means c=a+b is
calculated by compiler if a, b and c are basic types, suppose a, b and c are objects of user
defined class, compiler give error. However, using operator overloading we can make this
statement legal even if a, b and c are objects of class.
Actually, when we write statement c=a+b (and suppose a, b and c are objects of class),
the compiler call a member function of class. If a, b and c are basic type then compiler
calculates a+b and assigns that to c.
When an operator is overloaded, that operator loses none of its original meaning.
Instead, it gains additional meaning relative to the class for which it is defined.
We can overload all the C++ operators except the following:
1. Scope resolution operator (: :)
2. Membership operator (.)
3. Size of operator (size of)
4. Conditional operator(? :)
5. Pointer to member operator(.*)
#Q# WAP to concatenate two strings “Sita” and “Ram” and display “SitaRam” as output.
#include <iostream.h>
#include <string.h>
class string
{
char s[20] ;
public:
void get (char *c)
{ strcpy (s, c) ; }
void show( )
{ cout<<s; }
string operator+(string x)
{
string temp ;
strcpy (temp.s, s) ;
strcat (temp.s, x.s) ;
return temp ;
} Page: 59 of 128
};
Downloaded From: www.bhawesh.com.np
. 59
Object Oriented . Downloaded From: www.bhawesh.com.np
Programming in C++
void main( )
{ string s1, s2, s3 ;
s1.get (“Sita”) ;
s2.get (“Ram”) ;
s3.show( ) ;
}
Output:
SitaRam
By constructor:
When the conversion routine is in destination class, it is commonly implemented as a
constructor.
By Conversion Function:
When the conversion routine is in source class, it is implemented as a conversion
function.
Page: 65 of 128
7.1 Introduction:
Inheritance is the most powerful feature of object-oriented programming after classes
and objects. Inheritance is the process of creating a new class, called derived class from
existing class, called base class. The derived class inherits some or all the traits from base
class. The base class is unchanged by this. Most important advantage of inheritance is
reusability. Once a base class is written and debugged, it need not be touched again and we
can use this class for deriving another class if we need. Reusing existing code saves time and
money. By reusability a programmer can use a class created by another person or company
and without modifying it derive other class from it.
B Base Class
D Derived Class
examples:
#include <iostream.h>
class B
{ private: int x ;
protected: int y ;
public: int z ;
void getdata( )
{ cout<< “Enter 3 numbers=” ;
cin>>x>>y>>z ; }
void showdata( )
{ cout<< “x=”<<x<<endl ;
cout<< “y=”<<y<<endl ;
cout<< “z=”<<z<<endl ;
};
class D : public B
{ private : int k ;
public : void getk( )
{ cout<< “Enter k=” ; cin>>k ; }
void output( )
{ int s=y+z+k ;
cout<< “y+z+k=”<<s<<endl ; } } ;
void main( )
{
D d1 ;
d1.getdata( ) ;
d1.getk( ) ;
d1.showdata( ) ;
d1.output( ) ;
}
Output: Page: 68 of 128
Enter 3 numbers = 5 6 7
Downloaded From: www.bhawesh.com.np
. 68
Object Oriented . Downloaded From: www.bhawesh.com.np
Programming in C++
Enter k=8
x=5
y=6
z=7
y+z+k=21
//protected inherited
#include <iostream.h>
class B{
private : int x ;
protected : int y ;
public : void getdata( ) {
cout<< “enter x=” ; cin>>x ;
cout<< “enter y=” ; cin>>y ; }
void showdata( ) {
cout<< “x=”<<x<<endl ;
cout<< “y=”<<y<<endl ;
class D : protected B
{ private : int z ;
public : void getz( ) {
cout<< “enter z=” <<endl ; }
void showz( )
{ cout<< “z=”<<z<<endl ; }
};
void main( )
{ D d1 ;
d1.getz( )
d1.showz( ) ;
}
The output of the above program is
Enter z=4
z=4
//private inherited
#include <iostream.h>
#include<conio.h>
class B{
private : int x ;
protected : int y ;
public : void getdata( ) {
cout<< “enter x and y:” ; Page: 69 of 128
cin>>x>>y ; }
Downloaded From: www.bhawesh.com.np
. 69
Object Oriented . Downloaded From: www.bhawesh.com.np
Programming in C++
void showdata( )
{ cout<<x<<y<<endl ; }
} ; //end of class B
class D : private B
{ private : int z ;
public : void assign( ) {
{ z=30 ; y=40 ;
void output( )
{ int f=y+z
cout<< “s”<<f<<endl ; }
} ; //end of class D
void main( )
{ D d1 ;
clrscr( ) ;
d1.assign( ) ;
d1.output( ) ;
getch( ) ; }
Output:
s=70
Multiple Inheritance:
If a class is derived from more than one base class then inheritance is called as multiple
inheritance. Multiple inheritance allows us to combine the features of several existing classes
as starting point for defining new class. The syntax of multiple inheritance is:
class D: derivation B1, derivation B2 ........
{
member of class D
};
The derivation is private, public or protected. Note this is also possible that one
derivation is public and another one is protected or private, etc.
For example:
(1) class D : public B1, public B2
{private : int a ;} ;
(2) class D : public B1, protected B2
{private : int a;} ;
(3) class D : private B1, protected B2, public B3
{private : int a ;} ;
If B1, B2 and Bn are three classes from which class D is derived then we can draw the
multiple inheritance as Page: 70 of 128
// Multiple inheritance
#include <iostream.h>
#include <conio.h>
class biodata { char name[20] ;
char semester[20] ;
int age ;
int rn ;
public: void getbiodata( ) ;
void showbiodata( ) ;
};
class marks { char sub[10] ;
float total ;
public:
void getrm( ) ;
void showm( ) ; } ;
class final: public biodata, public marks
{ char fteacher[20] ;
public: void getf( ) ;
void showf( ) ; } ;
void biodata: : getbiodata( )
{
cout<< “Enter name:” ; cin>>name ;
cout<< “Enter semester:” ; cin>>semester ;
cout<< “Enter age:” ; cin>>age ;
cout<< “Enter rn:” ; cin>>rn ; }
void biodata: : showbiodata( )
{
cout<< “Name:”<<name<<endl ;
cout<< “Semester:”<<semester<<endl ;
cout<< “Age:”<<age<<endl ;
cout<< “Rn:”<<rn<<endl ;
Page: 71 of 128
void marks: : getm( )
Downloaded From: www.bhawesh.com.np
. 71
Object Oriented . Downloaded From: www.bhawesh.com.np
Programming in C++
{
cout<< “Enter subject name:” ; cin>>sub ;
cout<< “Enter marks:” ; cin>>total ; }
void marks: : showm( )
{
cout<< “Subject name:”<<sub<<endl ;
cout<< “Marks are:”<<total<<endl ; }
void final: : getf( )
{ cout<< “Enter your favourite teacher” ; cin>>teacher ; }
void final: : showf( )
{ cout<< “Favourite teacher:”<<fteacehr<<endl ; }
void main( )
{ final f ; clrscr( ) ;
f.getbiodata( ) ;
f.getm( ) ;
f.getf( ) ;
f.showbiodata( ) ;
f.shown( ) ;
f.showf( ) ;
getch( ) ;
}
Output:
Enter name : archana
Enter semester : six
Enter age : 20
Enter rn : 10
Enter subject name : C++
Enter marks : 85
Enter favourite teacher : Ram
Name : archana
Semester : six
Age : 20
Rn : 10
Subject name : C++
Marks are : 85
Favourite teacher : Ram
Page: 72 of 128
Intermediate
Base Class B1 father
#include <iostream.h>
class std
{ protected : char name[20] ;
int rn ;
public : void.getdata( )
{ cout<< “Student=” ; cin>>name ;
cout<< “Roll no.=” ; cin>>rn ; }
void showdata( )
{ cout<< “Student=”<<name<<endl ;
cout<< “Roll no=”<<rn<<endl ;
} ; // end of class std
class marks : public std {
protected : int m1, m2 ;
public:
void getm( )
{ cout<< “enter marks in Maths:”
cin>>m1 ;
cout<< “enter marks in English=” ; cin>>m2 ; }
void showm( ) {
cout<< “Maths”<<m1<<endl ; cout<< “English=”<<m2<<endl ; }
} ; //end of class marks
class result : public marks
{ int total ;
public: void calculate( ) Page: 73 of 128
{ total=m1+m2 ; }
Downloaded From: www.bhawesh.com.np
. 73
Object Oriented . Downloaded From: www.bhawesh.com.np
Programming in C++
void show( )
{ cout<< “Total marks=”<<total ; }
} ; //end of class result
void main( )
{ result s1 ;
s1.getdata( ) ;
s1.getm( ) ;
s1.calculate( ) ;
s1.showdata( ) ;
s1.shown( ) ;
s1.show( ) ;
}
Output:
Student=ram
Roll no=4
Enter marks in maths=56
Enter marks in english=45
Student=ram
Roll no=4
Maths=56
English=45
Total marks=101
Hierarchical Inheritance:
When from one base class more than one classes are derived that is called hierarchical
inheritance. The diagram for hierarchical inheritance is
D1 D2 D3
Hybrid Inheritance:
If we apply more than one type of inheritance to design a problem then that is known as
hybrid inheritance. The diagram of a hybrid inheritance is
B1
D1 B2
D2
However, there is a problem in using cptr to access the public members of the derived
class D. Using cptr, we can access only those members which are inherited from B and not
the members that originally belong to D. In case a member of D has the same name as one of
the members of B, then any reference to that member by cptr will always access the base
class member.
Although C++ permits a base pointer to point any object derived from that base, the
pointer cannot be directly used to access all the members of the derived class. We may have
to use another pointer declared as Page:
pointer
77toofthe
128derived type.
#include <iosteram.h>
Downloaded From: www.bhawesh.com.np
. 77
Object Oriented . Downloaded From: www.bhawesh.com.np
Programming in C++
class BC
{ public : int b;
void show( )
{ cout<< “b=”<<b<< “\n” ; }
};
class DC: public BC
{ public : int d ;
void show( )
{ cout<< “b=”<<b<< “\n”<< “d=”<<d<< “\n” ;
}
};
void main( )
{
BC*bptr ; //base pointer
BC base ;
bptr=&base ; //base address
bptr b=100 ; //access BC via base pointer
cout<< “bptr points to base object \n” ;
bptr show( ) ;
// derived class
DC derived ;
bptr=&derived //address of derived class’s object
bptr b=200 ; // access DC via base pointer
/* bptr d=300 ; / //won’t work
cout<< “bptr now points to derived object \n” ;
bptr show( ) ; //bptr now point to derived object
/*accessing d using a pointer to type derived class DC */
DC*dptr ; //derived type pointer
dptr=&derived ;
dptr d=300 ;
cout<< “dptr is derived type pointer \n” ;
dptr show( ) ;
cout<< “using(DC*) bptr)\n” ;
((DC*)bptr ) d=400 ; // cast bptr to DC type
((DC*)bptr) show( ) ;
}
Output:
bptr points base object
b=100 Page: 78 of 128
bptr now points to derived object
Downloaded From: www.bhawesh.com.np
. 78
Object Oriented . Downloaded From: www.bhawesh.com.np
Programming in C++
b=200
dptr is derived type pointer
b=200
d=300
using ((DC*)bptr)
b=200
d=400
The syntax for passing an argument from the derived class to the base class is as
derived_constructor(arg_list) : base(arg_list)
{
body of the derived class constructor
}
Here, base is the name of the base class. It is permissible for both the derived class and
the base class to use the same argument. It is possible for the derived class to ignore all
arguments and just pass them along to the base.
// Illustrate when base and derived class constructor and destructor functions are executed
#include <iostream.h>
class base {public:
base( ) { cout<< “Constructing base \n” ; }
base( ) {cout<< “Destructing
Page: 79 ofbase
128 \n” ; }
};
Downloaded From: www.bhawesh.com.np
. 79
Object Oriented . Downloaded From: www.bhawesh.com.np
Programming in C++
class derived : public base {
public:
derived( ) { cout<< “Constructing derived \n” ; }
~ derived( ) { cout<< “Destructing derived \n” ; }
};
int main( )
derived obj ;
return 0 ;
}
Output:
Constructing base
Constructing derived
Destructing derived
Destructing base
// Program shows how to pass argument to both base class and derived class
#include <iostream.h>
class base {int i ;
public :
base (int n) {
cout<< “Constructing base \n” ;
i=n ; }
~ base( ) { cout<< “Destructing base \n” ; }
void showi( ) { cout<<i<< “\n” ; }
};
class derived: public base {int j ;
public:
derived (int n): base(n) // pass argument to the base class
{ cout<< “Constructing derived \n” ;
j=n ; }
~ derived( ) {cout<< “Destructing derived \n”;}
void show( ) { cout<<j<< “\n” ; }
};
void main( ) {derived o(10) ;
o.showi( ) o.showj( ) ; }
Output:
Constructing base
Constructing derived
10 Page: 80 of 128
10
Downloaded From: www.bhawesh.com.np
. 80
Object Oriented . Downloaded From: www.bhawesh.com.np
Programming in C++
Destructing derived
Destructing base
Page: 81 of 128
Polymorphism:
Polymorphism is one of the crucial features of OOP. Polymorphism means one name,
multiple form. We have already studied function overloading, constructor overloading,
operator overloading, all these are examples of polymorphism .
For e.g.
#include <iostream.h>
#include <conio.h>
void area(float r) ;
void area(float l, float b) ;
void main( )
{ float r1, l1, b1 ;
clrscr( ) ;
cout<< “enter value of r1:” ; cin>>r1 ;
cout<< “enter value of l1:” ; cin>>l1 ;
cout<< “enter value of b1:” ; cin>>b1 ;
cout<< “Area of circle is”<<endl; area(r1) ;
cout<< “Area of rectangle is”<<endl ; area(l1, b1) ;
getch( ) ; }
void area (float r)
{ float a=3.14*r*r ;
cout<< “Area=”<<a<<endl ; }
void area(float l , float b)
{
float a1=l*b ;
cout<< “Area=”<<a1<<endl ; }
Output:
enter value of r1 : 2
enter value of l1 : 4
enter value of b1 : 6
Area of circle is
Area = 12.56
Area of rectangle is
Area = 24
In above program two functions have same name but question is how compile
differentiates these two. Actually,Page:
C++ compile
82 of 128differentiates these two by argument. In one
Classification of Polymorphism:
1.Compile time polymorphism
2.Run time polymorphism
The overloaded member functions are selected for invoking by matching arguments,
both type and number. This information is known to the compiler at the compile time,
therefore, compiler can select appropriate function. So, this is known as compile time
polymorphism. It is also called early binding or static binding. The example of compile time
polymorphism are
a) function overloading
b) operator overloading
If a member function is selected while program is running then this is called run time
polymorphism. In run time polymorphism, the function link with a class very late(i.e. after
compilation), therefore, this is called late binding or dynamic binding. This is called dynamic
binding because function is selected dynamically at runtime. For example
a) virtual function
#include <iostream.h>
class B
{ public :
virtual void show( )
{ cout<< “This is in class B”<<endl ; }
}; // end of class B Page: 83 of 128
class D1 : public B
Downloaded From: www.bhawesh.com.np
. 83
Object Oriented . Downloaded From: www.bhawesh.com.np
Programming in C++
{ public : void show( )
{ cout<< “This is in class D1”<<endl ; }
}; // end of class D1
class D2 : public B
{ public: void show( )
{ cout<< “This is in class D2”<<endl ; }
}; //end of class D2
void main( )
{ B *P ;
D1 obj1 ;
D2 obj2 ;
B objbase ;
p=&objbase ;
p show( ) ;
p=&obj1 ;
p show( ) ;
p=&obj2 ;
p show( ) ;
}
Output:
This is in class B
This is in class D1
This is in class D2
#include <iostream.h>
class polygon
{ protected : int width, height ;
public :
void setdata(int a, int b)
{ width=a; height=b; }
virtual int area( )
{return 0 ; }
}; //end of class polygon
class rectangle: public polygon
{ public:
int area( )
{ return (width*height) ; }
}; //end of class rectangle
class triangle: public polygon Page: 84 of 128
{ public:
Downloaded From: www.bhawesh.com.np
. 84
Object Oriented . Downloaded From: www.bhawesh.com.np
Programming in C++
int area( )
{ return (width*height /z) ; }
} ; //end of class triangle
void main( )
{ rectangle r ;
triangle t ;
polygon p ;
polygon *p1=&c ; polygon *p2=&t ;
polygon *p3=&p ;
p1 setdata(4,5) ;
p2 setdata(4,5) ;
p3 setdata(4,5) ;
cout<<p1 area( )<<endl ;
cout<<p2 area( )<<endl ;
cout<<p3 area( )<<endl ;
}
Output:
20
10
0
Virtual inside the base class and redefine it in the derived class. But the function
defined inside the base class B is seldom (rarely) used for performing any task. These
functions only serve as placeholder. Such functions are called do-nothing function or pure
virtual function.
In above edxample, ‘=’ sign has nothing to do with assignment operation and value 0 is
not assigned anything. This simply informs the compiler that function will be pure i.e. it will
have no definition relative to base class.
It should be noted that class containing pure virtual function cannot be used to create
objects of its own. Such classes are known as Abstract classes.
//virtpure.cpp
//pure virtual function
#include <iostream.h>
#include <conio.h>
class B //Base class
{ public:
virtual void show( )=0 ; // pure virtual function
};
class D : public B //derived class Page: 85 of 128
{
Downloaded From: www.bhawesh.com.np
. 85
Object Oriented . Downloaded From: www.bhawesh.com.np
Programming in C++
public:
void show( )
{ cout<< “Inside derived class”; } } ;
int main( )
{ Od;
B *P ;
P=&d ;
P show( ) ;
return 0 ;
getch( ) ;
}
Output:
Inside derived class
Page: 90 of 128
2. The information regarding which function 2. The compiler doesn’t know which function
to invoke that matches a particular call is to bind with particular function call until
known in advance during compilation. That program is executed i.e. the function is linked
is why it is also called as early binding. with particular class much later after
compilation.
3. The function call is linked with particular 3. The selection of appropriate function is
function at compiler time statically. So, it is done dynamically at run time, so it is also
also called static binding. called dynamic binding..
4. This type of binding can be achieved using 4. This type of binding is achieved using
function overloading and operator virtual function and base class pointer.
overloading.
Page: 91 of 128
Introduction:
The main objective of the computer program is to take some data as input, do some
process on that data and generate desired output. Thus input/output operations are the most
essential part of any program. In C++, there are several I/O function which help to control the
input and output operations.
We have already studied, cin and cout in combination with >> and << operators for
console input/output operations. Here, we discuss about various I/O functions, including
stream and stream classes that implement the I/O operation.
Program
Output Stream
Output
Device
Different input devices like keyboard can send data to the input stream. Also,
data in output stream can go the output device like screen (monitor) or any other storage
device. In C++, there are predefined I/O stream like cin and cout which are automatically
opened where a program begins its execution.
Page: 92 of 128
ios ostream
istream streambuf
fstream
The above figure shows a hierarchy of stream classes in C++ used to define various
stream in order to deal with both the console and disk files. From the figure, it is clear that ios
is a base class. This ios class is declared as virtual base class so that only one copy of its
members is inherited by its derived classes ; thereby avoiding ambiguity. The ios class
comprises of basic functions and constants required for input and output operations. It also
comprises of functions related with flag strings.
istream and ostream classes are derived from ios and are dedicated to input and output
streams respectively. Their member functions perform both formatted and unformatted
operations. istream contains functions like get( ), getline, read( ) and overloaded
extraction(>>) operators. ostream comprises of functions like put( ), write( ) and overloaded
insertion(<<) operators.
The iostream class is derived from istream and ostream using multiple inheritance.
Thus, it provides the facilities for handling both input and output streams. The class
istream_withassign and ostream_withassign add assignment operator to these classes. Again
the classes ifstream and ofstream are concerned with file I/O function. ifstream is used for
input files and ofstream for output files. Also there is another class of stream which will be
used both for input and output. All the classes ifstream, ofstream and fstream are derived
from classes istream, ostream and iostream respectively.
streambuf is also derived from ios base class. filebuf is derived from streambuf. It is
used to set the file buffers to read and write. It also contains open( ) and close( ) used to open
and close the file respectively.
Put( ):
It is used to output a line of text character by character basis.
for e.g.
cout.put (‘T’) ; // prints T
cout.put(ch) ; // prints the value of variable ch
cout.put(65) ; // displays a character whose ASCII value is 65 that is A
Program
#include <iostream.h>
void main( )
{
int count=0 ;
char c ;
cout<< “INPUT TEXT \n” ;
cin.get(c) ;
while (c!= ‘\n’)
{ cout.put(c) ;
count++ ; Page: 94 of 128
cin.get(c) ;
Downloaded From: www.bhawesh.com.np
. 94
Object Oriented . Downloaded From: www.bhawesh.com.np
Programming in C++
}
cout<< “\n Number of characters=”<<count<<\n” ;
}
Output:
INPUT TEXT
Object Oriented Programming
Object Oriented Programming
Number of characters = 27
Second Run:
Enter city name : New Baneshwor
City name : New Baneshwor
Enter city name again : Old Baneshwor
New city name : Old Baneshwor
write( ):
This function displays an entire line of text in output string.
General syntax is cout.write(line, size)
where, line represents the name of string to be displayed and second argument size
indicates number of characters to be displayed.
For e.g.
#include <iosteram.h>
#include <string.h>
void main( )
{
char *s1= “C++” ;
char *s2= “Programming” ;
int m=strleng(s1) ;
int n=strlen(s2) ;
for (int i=1 ; i<n ; i++)
{ cout.write(string2, i) ;
cout<< “\n” ;
}
for (i=n ; i>0 ; i.....)
{ cout.write(s2, i ) ;
cout<< “\n” ;
}
// concating strings
cout.write (s1, m).write (s2, n),
cout<< “\n” ;
// crossing the boundary
cout.write(s1, 10) ;
}
Manipulators:
Manipulators are special functions that can be included in the I/O statements to alter the
format parameters of a stream. Following are the important manipulators functions:
Manipulator Equivalent ios function
setw( ) width( )
setprecision( ) precision( )
setfill( ) fill( )
setioflags( ) setf( )
resetioflags( ) unsetf( )
Table : Manipulator Functions
To access all these manipulator, the file iomanip.h should be included in the program.
Following section describes different ios class functions:
width( ):
We can use the width( ) function to define the width of a field necessary for the output
of an item. The general syntax is
cout.width(w) ;
where, ‘w’ is the field width (total number of columns)
for e.g. cout.width(5) ;
cout<<123<<45<< “\n” ;
will produce the following output:
Page: 97 of 128
12345
123 45
If the field width specified is smaller than
the size of value to be printed, C++ expands the field to fit the value.
precision( ):
This function helps to specify the number of digits to be displayed after the decimal
point for printing floating point numbers. By default the floating numbers will be six digit
after decimal point. The general syntax is
cout.precision (d) ;
where, d is the number of digits to be displayed after decimal point.
This function has effect until it is reset. Consider the following statement.
cout.precision(3) ;
cout<<sqrt(2)<< “\n” ;
cout<<3.14159<< “\n” ;
cout<<2.50032<< “\n” ;
The above program produces the following output:
1.141 (truncated)
3.142 (round to the nearest number)
2.5 (no trailing zero or trailing zero truncated)
This is seen above, we can set the precision only once and this is used by all three
outputs.
fill( ):
We use this function for filling and padding the unused positions (filled with white
spaces by default) with desired symbol or characters.
syntax : cout.fill(ch) ;
where ch is character used to fill the unused space
For e.g. cout.fill(‘#’)
cout.width(10) ;
cout<< “filling” ;
Page: 98 of 128
###filling
3 . 1 400000
setf( ) with ios: : showpos flag as an argument can be used to print a plus (+) sign before
number.
#include <iostream.h>
void main( )
{
cout.width(5) ;
cout.setf(ios: : showpos) ;
cout<<3.14 ;
}
Output:
+3. 14
For example
#include <iostream.h>
#include <conio.h>
#include <iomanip.h>
#include <math.h>
void main( )
{
cout<<setw(5)<<setprecision(2)<<1.2345 ;
cout<<setw(10)<<setprecision(4)<<sqrt(2) ;
cout<<set(15)<<setiosflag(ios: :scientific)<<sqrt(3) ;
getch( ) ;
}
Output:
In above example, we print all the three values in one line with the field size of 5, 10
and 15 respectively. Setprecision (4) is used to output the value of sqrt(2) and setflags (ios: :
scientific) used for sqrt(3).
The basic difference between manipulators and ios class function is that ios member
functions return the previous format state which can be used later. But manipulators do not
return the previous format state. Thus ios functions are useful when we need to save the old
format states.
For e.g.
cout previous(2) ; // previous state
int p=cout.precision(4) ; // current format state
cout.precision(p) ; // p=2
#include <iostream.h>
void main( )
{ cout.precision(4) ;
cout<<2.33309<<endl ;
int p=cout.precision(4) ;
cout.precision(2) ;
cout<<endl<<2.33309 ;
cout.precision(p) ; Page: 101 of 128
cout<<endl<<2.33309 ;
Downloaded From: www.bhawesh.com.np
. 101
Object Oriented . Downloaded From: www.bhawesh.com.np
Programming in C++
}
Output:
2.3331
2.33
2.3331
write data
(to files)
Read data
Internal Memory (from files)
Program + Data
cin>> cout<<
(get data Console Unit (put data console program
from keyboard) to screen) interaction
Screen
File stream:
The I/O system of C++ handles file operations which are very much similar to the
ios
fstreambase
File Operations:
There are different types of operations that can be performed on a file, like opening,
reading, writing, closing, etc. A file can be defined by class ifstream header file fstream.h. If
a file is declared by ifstream class then it can be used for reading from file purpose. If a file is
declared by ofstream then that can be used for writing purpose. If file is declard by fstream
Page: 104 of 128
Examples:
1) fstream file ;
file.open(“Person.Dat”, ios: : app) ios: : out(ios: : in) ;
This creates Person file for input and output in append mode.
2) ifstream infile ;
infile.open(“Test.txt”, ios: : in) ;
This opens Test.txt file for reading only.
3) ofstream outfile ;
outfile.open(“Test.txt”, ios: : out) ;
This opens Test.txt for writing only.
4) ofstream fout Page: 105 of 128
fout.open(“data”, ios: : app/ios: : nocreate) ;
Downloaded From: www.bhawesh.com.np
. 105
Object Oriented . Downloaded From: www.bhawesh.com.np
Programming in C++
This opens the file in append mode but fails to open if it doesn’t exist.
2) Closing a File:
After opening any file, it is necessary that it must be closed. The general syntax for
closing a file is
stream_class_object.close( ) ;
Examples :
fout.close( ) ;
fin.close( ) ;
2. seekp( ):
This move puts pointer (output pointer) to a specified location. For example:
outfile.seekp(5) ;
3. tellg( ):
This gives the current position of get pointer (i.e. input pointer)
4. tellp( ):
This gives the current position of put pointer (i.e. output pointer). For example:
ofstream fileout ;
fileout.open (“test”, ios: 106
Page: : app) ;
of 128
int length=fileout.tellp( ) ;
Downloaded From: www.bhawesh.com.np
. 106
Object Oriented . Downloaded From: www.bhawesh.com.np
Programming in C++
By the above statement in length, the total number byte of files are assigned. Because file
opened in append mode that means the file pointer is at last of file.
#include <iostream.h>
#include <conio.h>
#include <fstream.h>
void main( )
{ ofstream fout(“Test.txt”) ;
fout<< “I am Ram” ;
fout.seekp(3) ;
fout<< “is” ;
int p=fout.tellp( ) ;
cout<<p ;
fout.close( ) ;
getch( )
}
Output: 5
1.eof( ): This function returns true if end of file encountered while reading otherwise
return false.
2.fail( ): This function returns true when an input and output operation has failed
otherwise return false.
3.bad( ): This function returns true if an invalid operation is attempted or any
unrecoverable error has occurred otherwise return false.
4.good( ): This function returns true if no error occurred otherwise false.
String Input/Output:
C++ provides us with the facility to read and write the character strings.
#include <iostream.h>
#include <conio.h>
#include <fstream.h>
void main( )
{ char str[80] ;
ofstream outfile (“Test.Dat”) ; // creates file for output
outfile<< “This is Testing\n” l // send text to file
outfile<< “This demonstrate string I/O” ;
outfile.close( ) ;
ifstream infile(“Test.Dat”) ; // create file for input
shile (infile) // until end of file reached
{ infile.getline(str, 80) ; // read content of file
cout<<str<<endl ; // and display it
}
getch( ) ;
}
Output:
Page: 108 of 128
Characer I/O:
Downloaded From: www.bhawesh.com.np
. 108
Object Oriented . Downloaded From: www.bhawesh.com.np
Programming in C++
We can use put( ) [member of ostream] and get( ) [member of istream] to output and
input a single character at a file.
#include <iostream.h>
#include <fstream.h>
#include <string.h>
int main( )
{ char s[80] ;
cout<< “Enter a string\n” ; cin>>s ;
int len=strlen=strlen(s) ;
fstream file ; // input and output stream
file.open (“Text”, ios: : in/ios: : out) ;
for (int i=0; i<len; i++)
file.put(s[i]) ; // put a character to file
file.seekg(0) ; // go to the start
while (file)
{ file.get(ch) ; // get a character from file
cout<<ch ; // display it on screen
}
return 0 ;
}
Output:
Enter a string
cplusplus_programming input
cplusplus_programming output
These function treats the data stored in the object as the sequence of bytes and make no
assumptions about how these bytes should be handled.
The general syntax for inputPage:
and output function is:
109 of 128
infile.read (cchar*)&v, sizeof(v)) ;
Downloaded From: www.bhawesh.com.np
. 109
Object Oriented . Downloaded From: www.bhawesh.com.np
Programming in C++
outfile.write(cchar*)&v, sizeof(v)) ;
The read( ) and write( ) function both takes two arguments. One to hold address of object and
another sizeof( ) operator to hold length of objects in bytes. The address of the object must be
cast to type pointer to char i.e. char*.
#include <iostream.h>
#include <fstream.h>
#include <conio.h>
void main( )
{ clrscr( ) ; // simple character example
ofstream fout(“abc.txt”) ;
cout<< “Enter any integer Number” ;
cin>>a ;
fout<<a ;
ifstream fin(“abc.txt”) ;
fin>>b ;
cout<< “content abc.txt is” ;
cout<<b ;
getch( ) ;
}
Output:
Enter any Integer Number 23
Content of abc.txt is 23
}
Output:
Enter Detail for Three items
Enter name : Mango
Enter code : 1001
Enter cost : 100.00
Enter name : Orange
Enter code : 1002
Enter cost : 150.00
Enter name : Apple
Enter code : 1003
Enter cost : 200.00
Output:
Mango 1001 100.00
Orange 1002 150.00
Apple 1003 200.00
Page: 112 of 128
10.1 Templates:
10.1.1 Introduction to Templates:
Template is one of the important features of C++ which enables us to define generic
(generalized) classes and function. Thus, it helps us to perform generic programming.
Generic programming is an approach where generic types are used a parameters in algorithms
so that they work for a variety of suitable data types and data structures.
A template can be considered as a macro which helps to create a family of classes or
functions. When an object of a specific type is defined for actual use, the template definition
for that class is substituted with the required data type. Since a template is defined with a
parameter that would be replaced by a specified data type at the time of actual use of the class
or function, the templates are sometimes called parameterized classes or functions.
There are two types of templates:
1. Function Templates
2. Class Templates
Example No. 2
#include <iostream.h>
const size=3
template <class T>
class vector
{ T*V ; // type T vector
public:
vector( ) Page: 114 of 128
{ v=new T[size] ;
Downloaded From: www.bhawesh.com.np
. 114
Object Oriented . Downloaded From: www.bhawesh.com.np
Programming in C++
for (int i=0 ; i<size ; i++)
v[i]=a[i] ;
T operator*(vector &y)
{ T sum=0 ;
for (int i=0 ; i<size ; i++)
sum+=this v[i]*y.v[i] ;
return sum ;
}};
int main( )
{ int x[3]={1, 2, 3} ;
int y[3]={4, 5, 6) ;
vector <int>v1 ;
vector<int>v2 ;
int R=v1*v2 ;
cout<< “R=”<<R<< “\n” ;
return 0 ;
}
Output: R=32
Example No. 3
#include <iostream.h>
template <class T>
class test
{ T a,b ;
public:
void getdata( )
{cin>>a>>b ;}
void putdata( )
{cout<< “You Entered:”<<a<< “ ”<<b ;}
};
int main( )
{ test<int>t1 ;
t1.getdata( ) ; t1.putdata( ) ;
test<float>t2 ;
t2.getdata( ) ; t2.putdata( ) ;
test(char>t3 ;
t3.getdata( ) ; t3.putdata( )
return 0 ; }
Output: Page: 115 of 128
12
Downloaded From: www.bhawesh.com.np
. 115
Object Oriented . Downloaded From: www.bhawesh.com.np
Programming in C++
You Entered : 1 2
1.5 2.5
You Entered : 1.5 2.5
xy
You Entered : x y
b) Algorithms:
It is a procedure that is used to process data contained in the containers. STL consists of
different algorithms for different tasks like initializing, searching, storing, copying, merging,
etc. These algorithms are implemented by template functions.
c) Iterators:
It is an object (like a pointer) that points to elements in a container. It can be used to move the
contents of container. As it works just as a pointer, it can be incremented or decremented.
They help to connect algorithms with containers and manipulate data stored in containers.
There can be different types of iterators like bidirectional, random access iterators, etc.
10.3 Namespaces
10.3.1 Introduction:
Namespace is a new concept introduced by teh ANSI C++ standards committee. This
defines a scope for the identifiers that are used in a program. For using the identifiers defined
in the namespace scope we must include the using directive, like
using namespace std ;
Here, std is the namespace where ANSI C++ standard class libraries are defined. All ANSI
C++ programs must include this directive. This will bring all the identifiers defined in std to
the current global scope. Using and namespace are the new keywords of C++.
An unnamed namespace is one that does not have a name. Unnamed namespace member
occupy global scope and are accessible in all scopes. For example:
// using unnamed Namescope with Nesting
#include <iostream.h>
using namespace std ;
namespace Name1
{ double x=5.67 ;
int m=10 ;
namespace Name2 // Nesting namespace
{
doubly y=4.56 ;
}
namespace // unnamed namespace
{ int m=20 ;
}
void main( )
{ cout<< “x=”<<Name1: : x<< “\n” ; // x is qualified
cout<< “m=”<<Name1: :m<< “\n” ;
cout<< “y=”<<Name1: : Name2: : y<< “\n” ; // ys is fully qualified
cout<< “m=”<<m<< “\n” ; // m is global
}
Output:
x=5.67
m=10
y=4.56
m=20
10.4 Exceptions:
10.4.1 Introduction:
The most common types of error(also known as bugs) occured while programming in
C++ are Logic error and SyntacticPage:
error.121
Theof logic
128 errors occur due to poor understanding of
Throw Point
Function that
causes an
exception
try block
Invokes a function
that contains an
exception
catch block
catches and
handles the
The keyword ‘try’ is used to preface a block of statements surrounded by braces which
may generate exceptions. This block of statement is known as try block. When an exception
is detected, it is thrown using a throw statement in the try block.
A catch block defined by the keyword catch ‘catches’ the exception ‘thrown’ by the
throw statement in the try block, and handlies it appropriately. Fig(a) shows try-catch
relationship. The catch block must immediately follow the try block that throws the
exception. The general syntax is
----
try
{----
---- // block of statement which detects and throws exception.
throw exception ;
----
}
catch(type arg)
{
---- // block of statements that handles the exception
----
}
Throwing Mechanism:
The exception is thrown by the use of throw statement in one of the following ways:
throw(exception) ;
throw exception ;
throw ; Page: 123 of 128
Catching Mechanism:
Code for handling exceptions is included in catch blocks. A catch block looks like a
function definition and is of the form:
catch(type arg)
{
// statements for
// managing exceptions
}
The “type” indicates the type of exception that catch block handles. The parameter arg
is an optional parameter name. The exception_handling code is placed between two braces.
The catch statement catches an exception whose type matches with the type of catch
argument. When it is caught, the code in the catch block is executed.
#include <iostream.h>
void main( )
{ int m, n ;
cout<< “Enter first no.:” ; cin>>m ;
cout<< “Enter second no.” ; cin>>n ;
try
{
if (n!=0)
{ cout<< “division=”<<m/n<<endl ; }
else
{ throw(n) ; } // throw object of int
} //end of try block
catch (int a)
{ cout<< “there is an exception division by zero \n” ;
<< “second no.”<<n<<endl ;
} // end of catch block
}
The output: (1strun)
Enter first no. : 6
Enter second no. : 3
division=2
nd
(2 run):
Enter first no. : 6
Enter second no. : 0
There is an exception divison by zero
second no. = 0
Q. [1] [a] What is object oriented paradigm? Discuss the merits and demerits of object
oriented methodologies. [2+3]
[b] What is class? Write a program illustrating class declaration, definition and
accessing class members. [2+3]
Q. [2] [a] What is polymorphism? How does function overloading implement
polymorphism? [2+2]
[b] What are inline functions? Write an inline function for finding minimum of
tow numbers using object oriented concept. [2+4]
Q. [3] [a] what are constructor and destructor? Explain copy constructor and explain
their need. [2+3]
[b] Write a program to accept a date of birth and calculate the age of a person
using passing object as argument. [5]
Q. [4] [a] What is the pointer? Write a program demonstrating the use of the pointer.
[1+4]
[b] Create a class complex for complex number and write a program to add two
complex numbers using friend function. [5]
Q. [5] [a] What is type conversion? Explain different types of data conversions.
[2+3]
[b] Create a class string and add two strings using + operator. [5]
Q. [6] [a] What is inheritance ? What are the types of inheritance?
[2+4]
[b] Why overriding is needed? Explain with example. [4]
Q. [7] [a] What are virtual functions? Explain how runtime polymorphism can be
achieved using them. [2+3]
[b] What is visibility mode? What are the different inheritance visibility modes
supported by C++ with suitable example. [1+4]
Q. [8] [a] What are file modes? Describe different methods of opening a file. [2+3]
[b] Write an interacting program to maintain an employee database. It has to
maintain information such as employee id, name, salary, designation etc. The
user must be able to access all details about a person by entering id or name.
[5]
Q. [9] [a] What is generic programming? What are its advantages and state some of its
application. [2+3]
[b] Write a function template for finding the largest number in a given array.
[5]
Q. [10] Write short notes on any TWO: [5+5]
[a] Object modeling Vs Page: 126 ofmodeling
Dynamic 128
[b] Namespaces [c] Data encapsulation Vs Data abstraction.
Downloaded From: www.bhawesh.com.np
. 126
Object Oriented . Downloaded From: www.bhawesh.com.np
Programming in C++
PURWANCHAL UNIVERSITY
II SEMESTER FINAL EXAMINATION-2007
LEVEL : B. E. (Civil/Computer/Electronics & Comm.)
++
SUBJECT: BEG176CO, Object-Oriented Programming C
Full Marks: 80
TIME: 03:00 hrs Pass marks: 32
Candidates are required to give their answers in their own words as far as practicable.
All question carry equal marks mark. The marks allotted for each sub-question is specified
along its side.
Answer EIGHT questions.