C++ Programming part-2

 Inheritance:

Reusability is yet another important feature of oop. It is always nice if we could reuse some thing that already exist rather than trying to create same all over again . it saves both time and money and increase reliability .
C++ support the reusability using  mechanism of inheritance . this is basically done by creating a new classes , reusing the properties of existing ones .
“ The mechanism of deriving a new class from an old one is called inheritance . the old class is referred as base class and new one is known as derived class or subclass ” . The derived class inherits the some or all of the traits from the base class .
Base Class: 
It is the class whose properties are inherited by another class. It is also called Super Class.

Derived Class:
It is the class that inherit properties from base class(es).It is also called Sub Class.
General form of defining a derived class
Class derived-class-name : visibility-mode Basic-class-name
{
……….
……….//members of derived class
};
The colon indicates that the derived-class-name is derived from base-class –name
The visibility-mode is optional and , if present may be either public , protected or private . The default visibility mode is private . visibility modes are used to specifies the features of the base class are publicly , privately  derived .
Protected:

 it is one of visibility modifier in C++ . A member  declared as protected is accessible by the member functions with in its class and a class immediately derived from it.
 When a base class is publicly inherited by  a derived class, ‘public members’ of the base class became ‘public members’ of the derived class . therefore  , they are inaccessible to the objects of the derived class
When a base class is privately inherited by  a derived class, ‘public members’ of the base class became ‘private members’ of the derived class . therefore the public members of the base class can only be accessed by the member functions of the derived class , they are inaccessible to the objects of the derived class .
When a protected member is inherited in public mode .it become a protected member in derived class . if its inherited in private mode becomes a private in derived class . 
 It is also possible to inherit the base class in protected mode . In protected derivation both public and protected members of the base class become a protected members of the derived class
In C++ have five types of inheritance
1 single inheritance
2 multiple inheritance
3 hierarchical inheritance
4 multilevel inheritance
5 Hybrid inheritance

Single Inheritance:

In this type of inheritance one derived class inherit from only one base class . it is the most simplest form of inheritance

Single inheritance through publicly .
#include<iostream.h>
#include<conio.h>
class X
{
int a;
public:
int b;
void get_ab();
int get_a();
void show_a();
};
class Y:public X
{
int c;
public:
void mul();
void display();
};
void X::get_ab()
{
a=10;b=20;
}
int X::get_a()
{
return a;
}
void X::show_a()
{
cout<<"val of a is:"<<a<<endl;
}
void Y::mul()
{
c=get_a()*b;
}
void Y::display()
{
cout<<"val of a is:"<<get_a()<<endl;
cout<<"val of b is:"<<b<<endl;
cout<<"mul a,b is:"<<c<<endl;
}
main()
{
clrscr();
Y y;
y.get_ab();
y.get_a();
y.show_a();
y.mul();
y.display();
y.b=30;
y.mul();
y.display();
getch();
return 0;

}
Single Inheritance privately

#include<iostream.h>
#include<conio.h>
class X
{
int a;
public:
int b;
void get_ab();
int get_a();
void show_a();
};
class Y:private X
{
int c;
public:
void mul();
void display();
};
void X::get_ab()
{
a=10;b=20;
}
int X::get_a()
{
return a;
}
void X::show_a()
{
cout<<"val of a is:"<<a<<endl;
}
void Y::mul()
{
get_ab();
cout<<"val of a:"<<get_a()<<endl;
cout<<"val of b:"<<b<<endl;
c=get_a()*b;
}
void Y::display()
{
cout<<"mul a,b is:"<<c<<endl;
}
main()
{
clrscr();
Y y;
y.mul();
y.display();
getch();
return 0;

}
OUTPUT:

value of a  10
value of b  20
mul of a,b is 200
Multilevel Inheritance :

In this type of inheritance derived class inherit from a class . which in turn inherit from some other class .

#include<iostream.h>
//#include<stdio.h>
#include<conio.h>
#include<iomanip.h>
class student
{
protected:
int roll_num;
public:
void get_rno(int);
void put_rno();
};
void student::get_rno(int x)
{
roll_num=x;
}
void student::put_rno()
{
cout<<"studnt num is:"<<roll_num<<endl;
}
class test:public student
{
protected:
int sub1,sub2;
public:
void get_marks(int x,int y);
void put_marks();
};
void test::get_marks(int x,int y)
{
sub1=x;
sub2=y;
}
void test::put_marks()
{
cout<<"sub1,sub2 marks are:  "<<sub1<<setw(5)<<sub2<<endl;
}
class result:public test
{
int total;
public:
void get_result();
void display();
};
void result::get_result()
{
total=sub1+sub2;
}
void result::display()
{
put_rno();
put_marks();
cout<<"total marks are: "<<total<<endl;
}
main()
{
clrscr();
result r;
r.get_rno(1);
r.get_marks(90,80);
r.get_result();
r.display();
getch();
return 0;
}

OUTPUT

student num is 1
sub1 ,sub2 marks are 90 80
total marks are 170


Hybrid Inheritance: 

In this type of inheritance we combine one or more types of inheritances



Ex: combination of multiple and multilevel inheritance
Hybrid inheritance:
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
class student
{
protected:
int roll_num;
public:
void get_rno(int);
void put_rno();
};
void student::get_rno(int x)
{
roll_num=x;
}
void student::put_rno()
{
cout<<"studnt num is:"<<roll_num<<endl;
}
class test:public student
{
protected:
int part1,part2;
public:
void get_marks(int x,int y);
void put_marks();
};
void test::get_marks(int x,int y)
{
part1=x;
part2=y;
}
void test::put_marks()
{
cout<<"part11,part2 marks are:  "<<part1<<setw(5)<<part2<<endl;
}
class sports
{
protected:
int score;
public:
void get_score(int x);
void put_score();
};
void sports::get_score(int x)
{
score=x;
}
void sports::put_score()
{
cout<<"the score is: "<<score<<endl;
}
class result:public test ,public sports
{
int total;
public:
void get_result();
void display();
};
void result::get_result()
{
total=part1+part2+score;
}
void result::display()
{
put_rno();
put_marks();
put_score();
cout<<"total marks are: "<<total<<endl;
}
main()
{
clrscr();
result r;
r.get_rno(1);
r.get_marks(90,80);
r.get_score(50);
r.get_result();
r.display();
getch();
return 0;
}
OUTPUT

student num is: 1
part1 ,part2 marks are: 90 80
the score is: 50
total marks are :220


Multiple Inheritance:

In this type of inheritance single derived class may inherit from more than two base classes.
#include<iostream.h>
#include<conio.h>
class M
{
protected:
int m;
public:
void get_m(int x);
};
void M::get_m(int x)
{
m=x;
}
class N
{
protected:
int n;
public:
void get_n(int x);
};
void N::get_n(int x)
{
n=x;
}
class P:public M,public N
{
public:
void display();
};
void P::display()
{
cout<<"val of m: "<<m<<endl;
cout<<"val of n: "<<n<<endl;
cout<<"val of m*n: "<<m*n<<endl;
}
main()
{
clrscr();
P p;
p.get_m(2);
p.get_n(3);
p.display();
getch();
return 0;
}


OUTPUT :
value of m:2
value of n:3
value m*n:6

Virtual base class:

                  In the above fig Consider the situation where all the three kinds of inheritances is there namely multilevel , multiple , hierarchical inheritances are involved . in which the child has two direct base classes ‘parent1’ and ‘parent2’ which themselves have a common base class ‘grandparent’ that’s why child inherit traits of a grand parent via two separate paths that is the reason all public and protected members of grand parent are inherited to child twice first via parent1 and again via parent2 . This means child have a duplicate sets of members inherited from grandparent . this introduces ambiguity and should be avoided by making a common base class as virtual base class .
Syn:
Class A
{
…….
……..
};
Class B1: virtual public A
{
……………..
……………
} ;
Class B2: public virtual A
{
……
};
class C: public B1 , public B2
{
…….
};
when a class is made a virtual base class , C++ takes necessary care only one copy of that class is inherited regardless of how many inheritance paths exist between the virtual base class and a derived class .
Note: the keywords virtual , public may be used in either order .

Pointers:

Pointer is a derived data type in C++ language . Pointer is simply like a variable that holds the address(reference) of a another variable  rather than data .
data-type *pointer-variable;
Here pointer-variable is the name of the variable , Data-type refer to the one of the c++ data-type.
Int *ptr;
Here ptr is pointer variable , and it is a integer type .

void pointer: 

void pointers known as generic pointers .which refer to a variables of any data type . Before using the void pointers we must typecast the the variables to the specific data type that they point to 

null pointers: 

the pointers which are not initialized in program , are called null pointers .

Write a program which is illustrating normal pointers
#include<iostream.h>
#include<conio.h>
main()
{
int *ptr,**ptr1,v=1,x=7;
void *ptr2;
clrscr();
ptr=&v;
ptr1=&ptr;
cout<<"address of ptr:"<<ptr<<endl;
cout<<"address of ptr1:"<<ptr1<<endl;
cout<<"val of ptr:"<<*ptr<<endl;
cout<<"val of ptr1:"<<**ptr1<<endl;
ptr2=&x;
int *y=(int*)(ptr2);
cout<<"val of generic pointer after casting"<<*y<<endl;
return 0;
}

write a program for implementing function pointers 
#include<iostream.h>
#include<conio.h>
#include<ctype.h>
int number[10],i,count,*ptr1;
void read()
{
cout<<"enter how many ele u want 2 read"<<endl;
cin>>count;
for(i=0;i<count;i++)
{
cin>>number[i];
}
}
void even()
{
int sum=0;
ptr1=number;
for(i=0;i<count;i++)
{
if(*ptr1%2==0)
{
sum=sum+*ptr1;
}
ptr1++;
}
cout<<"sum of even no is "<<sum;
}
main()
{
typedef void (*funpointer)();
clrscr();
funpointer fp;
fp=&read;
fp();
cout<<endl;
fp=&even;
fp();

}


Write a program for implementing Array of pointers
#include<iostream.h>
#include<conio.h>
#include<string.h>
main()
{
int i=0;
char *ptr[10]={"shiva","sathish","bhaskar"};
char str[25];
clrscr();
cout<<"enter u r favorite leisure persuite"<<endl;
cin>>str;
for(i=0;i<3;i++)
{
if(!strcmp(str,ptr[i]))
{
cout<<"u r favorite oersuit available in store"<<endl;
break;
}
}
if(i==3)
{
cout<<"u r favorite persuit not a available"<<endl;
}
}
Memory management operators :

C++ uses malloc() and calloc() functions for dynamic memory allocation at runtime .and free( ) for  dynamically free the allocated memory .and it also support two unary operators new and delete that perform the task of allocating and freeing the memory .
These operators operator s manipulate the memory on the free store . they are also known as free store operators .
The new operator can be used to create objects of any type .
Pointer-variable = new data-type;
And new operator can be used to create memory space for any data-types including derived data types  user defined data types .
Int *p=new int ;
Where p is a pointer of type int .
 Pointer-variable = new data-type [size] ;
Int *p=new int[10];
Item *p=new item[size] ;
We can de allocate existing memory using delete operator
Delete pointer-variable ;
The pointer-variable is the pointer points to a data object created with new .
Delete p;     
Delete  [size] pointer-variable;   
Delete   [ ]p; some new compilers support this also .

Pointer to objects :

We can use pointer to point to an object created by a class .
Item x;
Ex:  x.show();
Where item is a class and x is an object defined to be of type item. And we can define pointer variable ptr to x as follows .
Item x;
Item *ptr = &x ;
(*ptr).show();
Here parentheses are necessary because . (dot) operator has higher precedence than indirection (*) operator 
And we can also create a objects using pointers and new operator
Item *ptr = new item ;
 This statement allocate enough memory for the data members in the object structure and assigns the address of the memory space to the pointer .

Write a Program for Dynamic Memory allocation 

#include<iostream.h>
#include<conio.h>
#include<string.h>
class city
{
protected:
char *name;
int len;
public:
city()
{
len=0;
name=new char[len+1];
}
void getname()
{
char *str=new char[30];
cout<<"enter city name"<<endl;
cin>>str;
len=strlen(str);
name=new char[len+1];
strcpy(name,str);
}
void printname()
{
 cout<<name<<endl;
}
};
main()
{
city *ptr[10];
int n=1,i;
int option;
clrscr();
do
{
ptr[n]=new city;
ptr[n]->getname();
//ptr[1]->printname();
n++;
cout<<"if u wanna enter another city enter 1 else enter 0"<<endl;
cin>>option;
}while(option==1);
for(i=1;i<n;i++)
{
ptr[i]->printname();
}
return 0;
delete *ptr;
}
In the above program using arrow operator and object pointer to access the member functions .
ptr[n]->getname();

Polymorphism:

 polymorphism is one of the feature of oop . Its simply means  ‘one name multiple forms ‘
In C++ we have two types of polymorphism
1)compile time polymorphism
2) run time polymorphism

1.Compile time polymorphism:
       
 Compile time polymorphism implemented using function overloading and method overloading .in which over loaded member functions are selected for invoking by matching arguments both type and number . this information is known to the compiler at compile time therefore compiler able to select appropriate member function for particular call at compile time .
Bound a object to a method call at compile time is known as compile time polymorphism .this is early binding  or static binding or static linking .
2.Runtime polymorphism :
   Runtime polymorphism implemented using virtual functions. the appropriate function could be selected while program is running  (or) the  function is linked with a particular class much later after compilation . this process  is known as  late binding  or dynamic binding or dynamic linking .

Write a program which is implementing virtual function .
If there are member function with same name in derived classes, virtual functions gives programmer capability to call member function of different class by a same function call depending upon different context. This feature in C++ programming is known as polymorphism which is one of the important feature of OOP.
If a base class and derived class has same function and if you write code to access that function using pointer of base class then, the function in the base class is executed even if, the object of derived class is referenced with that pointer variable
If you want to execute the member function of derived class then, you can declare  base class function as a virtual function with virtual key word .

#include<iostream.h>
#include<conio.h>
class base
{
public:
void display()
{
cout<<"i am frm base cls display"<<endl;
}
virtual void show()
{
cout<<"i am frm base cls show"<<endl;
}
};
class derived: public base
{
public:
void display()
{
cout<<"i am frm derived cls display"<<endl;
}
void show()
{
cout<<"i am frm derived cls show"<<endl;
}
};
main()
{
base b;
derived d;
clrscr();
base *bptr;
bptr=&b;
bptr->display();
bptr->show();
bptr=&d;
bptr->display();
bptr->show();
}
i am frm base cls display
i am frm base cls show
i am frm base cls display
i am frm derived cls show
pure virtual functions :

A pure virtual function is a  function declared in a base class that has no definition related to the base class in such class the compiler requires each derived to either define the function or re declare it as pure virtual function  . a class contain pure virtual function can’t be used to declare any objects it’s own . such classes are abstract base classes .
 #include<iostream.h>                                                              
#include<conio.h>
class shape
{
protected:
float l;
public:
void get_len()
{
cout<<"enter length"<<endl;
cin>>l;
}
virtual float area()=0;
};
class square:public shape
{
public:
float area()
{
return (l*l);
}
};
class circle:public shape
{
public:
float area()
{
return (3.14*l*l);
}
};
main()
{
square s;
circle c;
clrscr();
s.get_len();
cout<<"area of square"<<endl;
cout<<s.area()<<endl;
c.get_len();
cout<<"area of circle"<<endl;
cout<<c.area()<<endl;
}
OUTPUT:

enter length
2
area of square
4
enter length
3
area of circle
28.26
C++  uses streams and stream classes to implement I/o operations  with console and  disk files .

Streams:  

I/O systems in C++  is design to work with a wide variety of devices although each device is very different being accessed . This interface is known as stream .  it act as an interface between program and input/output devices .  
(or)
Stream is sequence of bytes it acts either as a source from which the input data can be obtained or as a destination to which out put data can be sent.


Stream are two types 1)input stream 2) output stream           

1.input stream : 

the source stream that provides data to the program is called the input stream . the data in input stream can come from the keyboard or any other storage device . the default input device is keyboard .

2.output stream:  

the destination stream that receives  output from the program is called output stream . the data in output stream  can go to the screen or any other storage device . the default output device is screen .
C++ contain several pre-defined streams . That are automatically opened when a program begin its execution  for example cin , cout
C++  stream classes :

C++ I/O system contains a hierarchy of classes that are used  to define  various streams to deal with both the console and disk files . These classes are called stream classes . 
In the above figure ios  the base class for istream  and ostream which are in turn base classes for iostream
The class ios provides the basic support formatted and unformatted I/O operations  . The class istream  provides the facilities for formatted and unformatted input and The class ostream  provides the facilities for formatted and unformatted output .  the class iostream provides facilities both input and out put streams . and remaining three classes add assignment operators to this classes .

Ios: (input /output stream class)

The class ios provides the basic support formatted and unformatted I/O operations
Its contain pointer to a buffer  object .

Istream:

Inherit the properties of ios
Contain input functions such as get() , Getline() and read()
Contain overloaded extraction operator >>
Ostream:

Inherit the properties of ios
Contain output functions such as put() , write()
Contain overloaded extraction operator <<

Iostream:

Inherit the properties of istream and ostream  through multiple inheritance and thus contain all input and output functios

Streambuf :

Provides an interface to physical devices through buffers

Unformatted I/O Operations

1.Overloaded operators >> and <<

          The >> operator overloaded in the Istream class and <<  is overloaded in ostream class . these operators are used with combination of cin , cout object
Cin>>var1>>var2>> var3;
  this statement will cause to the computer to stop  execution and look for output
cout<<var1;
above statement just display the value of variable  var1 ;

put() and get() functions :

the classes istream  and ostream define two member functions get() , put() . these functions used for handling  single character input/output operations . 

get():

the function get() is member of istream class
there are two types of get() functions are there first one is get(char *) and get(void)  .
the get(char *) version assigns the input character to its argument .
get(void) returns the input character .

 put():

the function put() is member of ostream class
it can be used to output a line of text character by character by character .

#include<iostream.h>
#include<conio.h>
main()
{
char c;
int count=0;
clrscr();
cout<<"input text"<<endl;
c=cin.get();
while(c!='\n')
{
cout.put(c);
count++;
cin.get(c);
}
cout<<"\ntotal no of characters"<<endl;
cout<<count;

}
}
Getline () and write() :
we can read and display a line of text more efficiently using the line-oriented input/output functions getline() and write() .
getline() function reads whole line of text that ends with a newline character . this function can be invoked by using object cin as follows .
cin.getline(line , size);
the first argument represent the name of the string to be read and reading is terminated as soon as either the newline character (\n) is encountered or size-1 characters are read , the newline (\n) character os read but not saved  
the write() function displays an entire line
cin.write(line , size);
the first argument represent the name of the string  to be displayed . the argument size indicates the number of character to display
#include<iostream.h>                                                              
#include<conio.h>
main()
{
int size=20;
char name[20];
int ch=1;
clrscr();
while(ch)
{
cout<<"enter first city name"<<endl;
cin>>name;
cout<<"first city name:"<<name<<endl;
cout<<"enter second city name "<<endl;
cin.getline(name,size);
cout<<"second city name"<<name<<endl;
cout<<"enter third city name "<<endl;
cin.getline(name,size);
cout<<"third city name is "<<name<<endl;
cout<<"enter 1 for next iteration 0 for exit"<<endl;
cin>>ch;
}
getch();

}
#include<iostream.h>
#include<conio.h>
#include<string.h>
main()
{
int i,m,n;
char *cptr="c++";
char *cptr1="programming";
clrscr();
m=strlen(cptr);
n=strlen(cptr1);
for(i=0;i<n;i++)
{
cout.write(cptr,i)<<"\n";
}
for(i=n;i>0;i--)
{
cout.write(cptr,i)<<"\n";
}
cout.write(cptr,m).write(cptr1,n)<<endl;
cout<<"secondop"<<endl;
cout.write(cptr,10);
getch();
}



Formatted console  i/o operations:

C++ supports three types of features for formatting the output these are

1. ios class functions and flags.
2. Manipulators .
3. User defined output functions.

1.ios class functions and flags :

The ios class contains large number of member functions that would help us to formats the out in number of ways. The important ones among them  are
1.width()
2.precision()
3.fill()
4.setf()
5.unsetf()
1.width(): 

We can use width to define the width of a field necessary for output of an item.

Syntax: cout.width(w);

Where ‘W’ is the field width the output will be printed in a field of   ‘w’ characters wide at right end of the field. The width can specify for only one item. After one item it revert back to the default.
Remember that field width should be specified for each item separately .C++ never truncates the values if the specified width is smaller than the size of the value to be printed. C++ expands field to fit the value

2.Precision():

.By default the floating point numbers are printed with 6 digits after the decimal point .If u want to specify the number of digits to be displayed after the decimal point while printing the floating point numbers .This can be done  by using precision number function.

Syntax: cout.precision(d);

Where d is the number of digits to the right of decimal point .

Note :- i)The output is rounded to the nearest cent(1.6666 will be 1.67 , 1.3333 will be  1.3333 only  )trailing zeros are truncated .
ii)Precision settings stays in effect until it  is reset.
iii)Default precision  is 6 digits.

3.fill():

Sometime we print the values using much larger field width then required by the value .By default  the  unused positions of the field are filled with white spaces. However  we can use the fill () to fill unused positions by any designed character

Syntax: cout.fill(ch);

Where ch represents the character which is used for filling the unused positions .

4.Setf() ,Formatting flags and bit fields  :

 When we use width() function the value is printed right justified position in the field width created .Then  if you want to print value in left justified position and print floating point number in scientific notation we ca use setf() member function.

Syntax: cout.setf(arg1,arg2);

In the above syntax the arg1 is one of the formatting flags defining the class ios. The formatting flags specifies the format action required for the output another ios constant arg2 known as bit field specifies group to which the formatting belongs.  
Format  required
Flag(arg1)
Bit field (arg2)
Left-justified output
Ios::left
Ios::adjust field
right-justified output
Ios::right
Ios::adjust field
Scientific notation
Ios::scientific
Ios::float field
Decimal base
Ios::dec
Ios::basefield
Using setf() function we can trailing zeroes of the number and adding the signs  either ‘+’ or ‘-’ before the number .
Flag
Meaning
Ios::showbase
Use base indicator on output.
Ios::showpos
Print + before positive numbers.
Ios::uppercase
Use Uppercase letters for hex output.
The flags such as a showpoint and showpos do not have any bit fields therefore are used as a single arguments  in the setf().
Note:-  i)The  flags set by setf() remain effective until they are reset or unset.
ii)The format flags can be reset any number of times in program 
iii)we can apply more than one format controls jointly on output value.

/*Write a Program to illustrating formatted console i/o operations using  ios class functions?*/

#include<iostream.h>
#include<conio.h>
#include<math.h>
void main()
{
clrscr();
cout.fill('*');
cout.setf(ios::left ,ios::adjustfield);
cout.width(10);
cout<<"value";
cout.setf(ios::right,ios::adjustfield);
cout.width(20);
cout<<"sqrt of value"<<endl;
cout.fill('.');
cout.precision(4);
cout.setf(ios::showpoint);
cout.setf(ios::showpos);
cout.setf(ios::fixed,ios::floatfield);
for(int n=0;n<=10;n++)
{
cout.setf(ios::internal,ios::adjustfield);
cout.width(4);
cout<<n;
cout.setf(ios::right,ios::adjustfield);
cout.width(20);
cout<<sqrt(n)<<"\n";
}
cout.setf(ios::scientific,ios::floatfield);
cout<<"\nsqrt(100)="<<sqrt(100)<<"\n"<<endl;
}
OUTPUT:

value************sqrt of value
...0..............0.0000
+..1.............+1.0000
+..2.............+1.4142
+..3.............+1.7321
+..4.............+2.0000
+..5.............+2.2361
+..6.............+2.4495
+..7.............+2.6458
+..8.............+2.8284
+..9.............+3.0000
+.10.............+3.1623   sqrt(100)=+1.0000e+01

Write a program for implementing manipulators cpp .

#include<stdio.h>
#include<iomanip.h>
#include<conio.h>
#include<math.h>
#include<string.h>
main()
{
clrscr();
cout.fill('*');
cout<<setiosflags(ios::left)<<setw(10)<<"value"<<
setiosflags(ios::right)<<setw(20)<<"sqrt of a value"<<endl;
for(int i=1;i<=10;i++)
{
cout<<setfill('.')<<setiosflags(ios::showpoint)
<<setiosflags(ios::showpos)<<setw(2)<<i<<resetiosflags(ios::showpos)<<
setprecision(3)<<setw(20)<<sqrt(i)<<endl;
}
cout<<setfill(' ')<<setiosflags(ios::scientific)<<"sqrt(10) is "<<setw(10)<<sqrt(10)<<endl;
}


OUTPUT:

 value************sqrt of value
...0..............0.0000
+..1.............+1.0000
+..2.............+1.4142
+..3.............+1.7321
+..4.............+2.0000
+..5.............+2.2361
+..6.............+2.4495
+..7.............+2.6458
+..8.............+2.8284
+..9.............+3.0000
+.10.............+3.1623   sqrt(100)=+1.0000e+01



User Defined Manipulaters:
These are very useful when ever user want to implement their own manipulators

#include<iostream.h>
#include<conio.h>
ostream& Rupee(ostream &output)
{
output<<"Rs";
return output;
}
ostream& complex(ostream &output)
{
output<<"+i";
return output;
}
main()
{
 clrscr();
 cout<<"Book cost is:"<<Rupee<<200<<endl;
 cout<<"complex no is:"<<2<<complex<<3<<endl;
}
 Book cost is:Rs200
complex no is:2+i3

Files in C++ :

    .A file is collection of related data stored in a particular area on the disk  . iosystems  of c++  using  file streams as an interface between programs and files. A stream that supplies data to the program is known as input stream and the stream that receives data from the program is known as output stream.  In other words the input stream extracts data from the file and the output stream inserts data to the files.

Classes for file stream operations

The io system of c++ contain set of classes that define file handling methods.These classes  include ifstream,ofstream and fstream. These classes are derived from fstream base  and from the corresponding to iostream classes.
Class
context
Filebuf
Its purpose is to set the file buffers to read and write. Also contains close() and open()  as methods.
Fstreambase
Base class for fstream , ifstream and ofstream class also contains open() and close() methods.
Ifstream
Provide input operations . contains open() open with default input mode. inherits functions get() ,getline(),read(),seekg() ,tellg()
Ofstream
Provide output operations . contains open() open with default output mode , inherits functions put() ,seekp() ,tellp()
Fstream
Provide support for simultaneos i/p operation contains open() open with default input mode .
Inherits all the functions from istream and ostream classes through iostream
Open and closing a files:

If you want to perform any operations on file we use file name . filename is a name which consist string of characters and its contain two parts 1)primary name 2) extension   
Opening of a file can be done in two ways
1.Using constructor
2.Using open( ) method .

1.Using constructor :

Here file name is used to initialize an object . Here we create stream object to manage stream using the appropriate class for example the class ofstream is used to create the output stream. the class ifstream is used to create the input stream , initialize object with the desired filename .
Ex:
Ofstream outfile(“results”); //create a output file connects results to it
ifstream infile(“results”); //create a input file connects results to it 
outfile.close( ) ;
disconnects the file results from the output stream outfile . if we want we connect it later .

2.Using open( ) method

The function open can be used to open multiple files that use same stream object .
Syntax:
File-stream-class stream-object ;
stream-object.open(“ filename”);
if you want to close the existing file just use close( ) function .
ex: infile.close();
Working with single file

#include<iostream.h>
#include<fstream.h>
#include<string.h>
#include<conio.h>
void main()
{
clrscr();
ofstream otf("items");
cout<<"enter name";
char name[10];
cin>>name;
otf<<name<<"\n";
//cin.getline(name,30);
cout<<"enter code";
int code;
cin>>code;
otf<<code<<"\n";
cout<<"enter cost";
int cost;
cin>>cost;
otf<<cost<<"\n";
otf.close();
ifstream inf("items");
inf>>name;
inf>>code;
inf>>cost;
cout<<"\n";
cout<<"name is"<<name   <<endl;
cout<<"code is"<<code<<endl;
cout<<"cost is"<<cost<<endl;
inf.close();
}
enter namep
enter code23
enter cost235
name isp
code is23
cost is235

end of file:

detecting end of the file is necessary for preventing any further attempt to read data from the file.
 Eof( ) is member function of ios class . It returns a non-zero value if the end-of-file condition is encountered and otherwise it returns zero .

reading two files data simultaneously

#include<iostream.h>
#include<conio.h>
#include<fstream.h>
#include<stdlib.h>
 main()
{
ofstream outf;
clrscr();
outf.open("country");
outf<<"india"<<endl;
outf<<"pakistan"<<endl;
outf<<"america"<<endl;
outf.close();
outf.open("capital");
outf<<"delhi"<<endl;
outf<<"eslama bad"<<endl;
outf<<"washington"<<endl;
outf.close();
ifstream  inf1,inf2;
char line[50];
int size=30;
inf1.open("country");
inf2.open("capital");
for(int i=0;i<=2;i++)
{
if(inf1.eof()!=0)
{
exit(1);
cout<<"exit from the country";
}
inf1.getline(line,size);
cout<<"capital of the "<<line<<"is"<<endl;
if(inf2.eof()!=0)
{
exit(1);
cout<<"exit from the capital";
}
inf2.getline(line,size);
cout<<line<<endl;
}
}
capital of the indiais
delhi
capital of the pakistanis
eslama bad
capital of the americais
Washington
File modes: 
     Parameter
Meaning
Ios::app
Append to end of file
Ios::ate
Go to end-of-file on opening
Ios::binary
Binary file
Ios::in
Open for reading only
Ios::nocreate
Open fails if file does not exist
Ios::noreplace
Open fails if file already exist
Ios::out
Open for writing only
Ios::trunk
Delete the contents of the file if it exists
·         Opening a file in ios::out mode also opens it in the ios::trunc mode by default
·         Both ios::app and ios::ate take us to the end of the file when it is opened , the difference between the two parameters is that the ios::app allows us to add data to the end of the file only while ios::ate add data any where in a file . in both the cases , a file is created by specified name if it does not exist.
·         The fstream class does not provide a mode default and therefore we must provide the mode explicitly .
·         The mode can combine two are more parameters using using betwise Or operator ( | )
       
File pointers:
Each file has two pointers one of them is called input pointer( or get pointer) and other one is called output pointer (or put pointer) . we can use this pointers to move through the files while reading and writing . the input pointer is used for reading the contents of given file location . output pointer is used for writing to a given file location .
Functions for manipulation of file pointers :
If we want to move the file pointer any other position inside the file , we use following functions .  Seekg( ) : moves get pointer to a specified location .
   Seekp( ): moves put pointer to a specified location .
   Tellg( ):  gives the current position of the get pointer .
   Tellp( ): gives the current position of the put pointer .
‘Seek ‘ functions seekg( ) and seekp( ) can also be used with two arguments as follows
  Seekg (offset ,refposition)
  Seekp (offset ,refposition)
The parameter offset represents the number of bytes the file pointer is to be moved from the location specified by the refposition . the refposition takes one of  following three constants defined in ios class
Ios::beg     : start of the file
Ios::cur      : current position of the pointe
Ios:: end    :  End of the file .
Using ‘seek’ functions we move file pointer in both directions like forward and backward .
Ex:
Fout.seekg ( 0 , ios ::  beg ) ->go to start
Fout.seekg ( m , ios :: cur ) ->go forward by m byte from current position .
Fout.seekg ( -m , ios :: cur ) ->go backward by m byte from current position .
Input and out operations on a files :
The file stream class support a number of member functions for performing the input and output operations on files .  one pair of functions put( ) , Get( ) are designed for handling a single character at a time (put( ) writes a single character to the associate stream , get( ) reads a single character from associate stream)  . another pair of functions write( ) and read( ) are designed to handle write and read blocks of binary data . this means that the values stored in the disk file in the same format in which they are stored in the internal memory .the binary format is more accurate for storing the numbers as they are stored in exact internal representation . There are no internal conversions while savingthe data . that’s why it’s much faster .
Syntax
Infile. read ((char *) &v,sizeof(v));
Outfile.write((char *)&v, sizeof(v));
The first argument is address of the variable V , and the second is length of the variable in bytes .
W.A.P to implement Sequential input and output operations .
#include<conio.h>
#include<string.h>
#include<fstream.h>
void main()
{
char str[20];
clrscr();
cout<<"enter fisrt string\n"<<endl;
cin>>str;
int n=strlen(str);
fstream file;
file.open("text2",ios::in|ios::out);
for(int i=0;i<n;i++)
{
file.put(str[i]);
}
file.seekg(0);
char ch;
while(file)
{
file.get(ch);
cout<<ch;
}
}
enter fisrt string
innerlookofprogramming
innerlookofprogramming 
#include<iostream.h>
#include<conio.h>
#include<string.h>
#include<fstream.h>
class inventory
{
char name[10];
int price;
public:
void read_data();
void write_data();
};
void inventory::read_data()
{
cout<<"\nenter name,cost of an item\n"<<endl;
cin>>name>>price;
}
void inventory::write_data()
{
cout<<"\n name,cost of an item\n"<<endl;
cout<<name<<price<<endl;
}
main()
{
inventory i1[2];
fstream file;
file.open("input",ios::in|ios::out);
cout<<"\n input\n";
for(int i=0;i<2;i++)
{
i1[i].read_data();
file.write((char *)& i1[i],sizeof(i1[i]));
}
cout<<"\n output\n";
for(i=0;i<2;i++)
{
file.read((char *)& i1[i],sizeof(i1[i]));
i1[i].write_data();
}
 input
enter name,cost of an item
hdd
2500
enter name,cost of an item
pendrive
300
output
hdd      2500
pendrive       300
random accessing of a file .
#include<iostream.h>
#include<conio.h>
#include<string.h>
#include<fstream.h>
class inventory
{
char name[10];
int price;
public:
void read_data();
void write_data();
};
void inventory::read_data()
{
cout<<"\nenter name,cost of an item\n"<<endl;
cin>>name>>price;
}
void inventory::write_data()
{
cout<<"\n name,cost of an item\n"<<endl;
cout<<name<<price<<endl;
}
main()
{
inventory i1;
clrscr();
fstream file;
file.open("shiva",ios::ate|ios::in|ios::out|ios::binary);
cout<<"\n input\n";
for(int i=0;i<=2;i++)
{
i1.read_data();
file.write((char *)& i1,sizeof(i1));
}
file.seekg(0,ios::beg);
while(file.read((char *)& i1,sizeof(i1)))
{
i1.write_data();
}
file.clear();
cout<<"\n>>>>>>>>>> Add one more Item >>>>>>>>>>\n"<<endl;
cout<<"\n Add an one more item\n"<<endl;
i1.read_data();
char ch;
//cin.get(ch);
file.write((char *)& i1,sizeof(i1));
file.seekg(0);
while(file.read((char *)& i1,sizeof(i1)))
{
i1.write_data();
}
int last=file.tellg();
int n=last/sizeof(i1);
cout<<"the no of objects"<<n<<endl;
cout<<"the no of bytes"<<last<<endl;
cout<<"\nenter object no to be updated\n";
int object;
cin>>object;
cin.get(ch);
int loc=(object-1)*sizeof(i1);
if(file.eof())
file.clear();
file.seekp(loc);
cout<<"\n eneter new value for object\n"<<endl;
i1.read_data();
cin.get(ch);
file.write((char *)& i1,sizeof(i1));
file.seekg(0);
cout<<"\n conten in the updated file is \n"<<endl;
while(file.read((char *)& i1,sizeof(i1)))
{
i1.write_data();
}
file.close();
}
Error Handling functions
Eof()
Fail(): returns true when an i/o failed
Bad():returns true an invalid operation attempt . un recoverable error occurred . return false to recover from any other error
Good(): returns true if no error has occurred .
Unit-5
templates enables us to define a generic classes and functions and thus provides support for generic programming . Generic programming is an approach where generic types are used as parametres parametres in algorithams so that they work variety of suitable datatypes and datastructures .
A template can be used to create a family of classes or functions for eaxmple a class template for an array class would enable us to create arrays of various datatypes such as int array and float array . similarly we can define a template for a function , say mul() , that would help us create various versions of mul () for multiplying int , float and double type values .
#include<iostream.h>
#include<conio.h>
const size=3;
template<class T>
class vector
{
T *v;
public:
vector()
{
v=new T[size];
for(int i=0;i<size;i++)
{
v[i]=0;
}
}
vector(int *a)
{
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.1,2.7,3.8};
int y[3]={4.6,5.7,6.9};
clrscr();
vector<float> v1;
vector<float> v2;
v1=x;
v2=y;
float r=v1*v2;
cout<<"the result is"<<r<<endl;
return 0;
}
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
template<class T1, class T2>
class test
{
T1 a;
T2 b;
public:
test(T1 x,T2 y)
{
a=x;
b=y;
}
void show()
{
cout<<setw(10)<<a<<" and "<<b;
}
};
main()
{
clrscr();
test<int,float>t1(2,3.5);
t1.show();
cout<<"\n";
test<int ,char> t2(23,'B');
t2.show();
}
        2 and 3.5
        23 and B

                                                        For Part1 Click here


Thanks for visiting this blog. How is the content?. Your comment is great gift to my work. Cheers.

No comments:

Post a Comment