http://KVSeContents.in http://eTeacher.KVSeContents.in
{
Ayan() { } //Default/Implicit Constructor
};
Copy Constructor
A copy constructor is a special constructor that
creates a new object from an existing object. If we do
not define a copy constructor, the compiler will
generate one for us that performs a shallow copy
(copies only a pointer so that the two pointers refer
to the same object) of the existing object's member
variables. So, if our object allocates any resources,
we most likely need a copy constructor so that we can
perform a deep copy (copies what a pointer points to so
that the two pointers now refer to distinct objects).
// Shallow Copy Example
char *ch = new char('Z');
char *cp = ch; // copy the pointer ch
*ch = 'X'; // change the value of the char pointed to
by *ch
// Deep Copy Example
int *p = new int(99);
int *q = new int(*p);
// Allocate a new int before copying the value pointed
to by p
*p = 100; // change the value of the int pointed to by
p
Example of Default Copy Constructor that compiler
provides and its problem:
#include <iostream.h>
#include<string.h>
class Kangra
{
int *temp;
public:
Page 101 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
Kangra(int i)
{
cout << " Constructor";
temp=new int();
*temp = i;
}
~Kangra()
{
cout << "Destructor";
delete temp;
}
};
int main()
{
Kangra kg(150); // First Object Created Invoke our
Constructor
Kangra kg1(kg); // Here is the Problem;
/* When Second Object will be Created It will
not Invoke our Constructor. It will invoke Default Copy
Constructor */
cout << "Main";
return 0;
}
Let's look at the output:
Constructor
Main
Destructor
Destructor
Null Pointer Assignment
Destructor does delete. The problem is it is trying to
delete a pointer we haven't allocated. When default
copy constructor is called (Kangra kg1(kg)), it does
not allocate anything.
How to fix it?
Page 102 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
Use explicit Copy Constructor Instead of Default Copy
Constructor
#include<iostream.h>
#include<string.h>
class Kangra
{
int *temp;
public:
Kangra(int i)
{
cout<<"Constructor\n";
temp=new int();
*temp=i;
}
Kangra(const Kangra &obj) // Explicit Copy Constructor
{
cout << "Copy Constructor\n";
temp = new int();
*temp=*obj.temp ;
}
~Kangra()
{
cout << "Destructor\n";
delete temp;
}
};
int main()
{
Kangra kg(150); // Call to Simple Constructor when
Object 1 will be created
Kangra kg1(kg); // Call to Explicit Copy Constructor
when Object 2 will be created
cout << "Main\n";
return 0;
}
Now we will get the desired output: Two Objects Created
and Two Deleted
Page 103 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
Constructor
Copy Constructor
Main
Destructor
Destructor
This should be our choice.
Summary
The copy constructor gets called in the following
cases:
An object is passed to a method by value or returned by
value.
An object is initialized using the syntax, MyClass a =
b.
An object is thrown or caught in an exception.
Constructor with Default Argument:
#include <iostream.h>
#include<string.h>
class Kangra
{
int temp;
public:
Kangra(int i=10) //Constructor with Default Argument 10
{
cout << " Inside Constructor with Default Argument";
temp=i;
cout<<"Temp = "<<temp;
}
};
int main()
{
Kangra kg; // Object Created without argument. This
Page 104 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
will take default argument of the Constructor
cout << "Main";
return 0;
}
Output:
Inside Constructor with Default Argument
temp=10;
Main
Page 105 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
Inheritance in C++
A key feature of C++ is inheritance. Inheritance allows
to create classes which are derived from other classes,
so that they automatically include some of its
"parent's" members, plus its own. For example, If we
declare a class FRUIT which describes all the common
attribute of fruits such as their taste , colour etc.
From this FRUIT class we cab drive two other classes
Apple and Orange.
The class Fruits would contain members that are common
for both types of Fruits. In our case: Taste and
Colour. And Orange and Apple would be its derived
classes, with specific features that are different from
one type of fruit to the other.
If a base class includes a member A and we derive it to
another class with another member called B, the derived
class will contain both members A and B.
In order to derive a class from another, we use a colon
(:) in the declaration of the derived class using the
following format:
Class derived_class: access_specifier base_class
{ /*...*/ };
Page 106 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
Where derived_class_name is the name of the derived
class and base_class_name is the name of the class on
which it is based. The access specifier may be replaced
by any one of the access specifiers such as
public,protected and private. This access specifier
limits the most accessible level for the members
inherited from the base class: The members with a more
accessible level are inherited with this level instead,
while the members with an equal or more restrictive
access level keep their restrictive level in the
derived class.
// Inheritance Example
#include <iostream.h>
#include<string.h>
class Fruits
{
public:
char taste[20],color[20];
};
class Orange: public Fruits
{
public:
void TasteColor()
{
strcpy(taste,"sweet-sour");
strcpy(color,"orange");
}
void Display()
{
cout<<"Orange Taste = "<<taste<<endl;
cout<<"Orange Colour ="<<color<<endl;
Page 107 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
}
};
class Apple: public Fruits
{
public:
void TasteColor()
{
strcpy(taste,"sweet");
strcpy(color,"red");
}
void Display()
{
cout<<"Apple's Taste = "<<taste<<endl;
cout<<"Apple's Colour ="<<color<<endl;
}
};
int main ()
{
Orange org; Apple
app;
org.TasteColor();
app.TasteColor();
org.Display();
app.Display();
return 0;
}
Output:
Page 108 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
Orange Taste = sweet-sour
Orange Colour =orange
Apple Taste = sweet
Apple Colour =red
The objects of the classes Orange and Apple each
contain members inherited from Fruits. These are: taste
and color().
Since we wanted taste and color to be accessible from
members of the derived classes Orange and Apple, we
have used public access specifier.
We can summarize the different access types according
to who can access them in the following way:
Access Public Protected Private
Members of the same class yes yes Yes
Yes Yes No
Members of derived Yes No No
classes
Non members
Where "not members" represent any access from outside
the class, such as from main(), from another class or
from a function.
Access Specifier in Inheritance:
When deriving a class from a base class, the base class
may be inherited through public,
protected or private inheritance. The type of
inheritance is specified by the access-specifier .
public inheritance is commonly used. While using
different type of inheritance, following rules are
applied:
1. Public Inheritance: When deriving a class from
a public base class, public members of the base
Page 109 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
class become public members of the derived class
and protected members of the base class
become protected members of the derived class. A
base class's private members are never accessible
directly from a derived class, but can be accessed
through calls to the public and protected members
of the base class.
2. Protected Inheritance: When deriving from
a protected base class,public and protected
members of the base class become
protected members of the derived class.
3. Private Inheritance: When deriving from
a private base class, public and protected members
of the base class become private members of the
derived class.
In our example, the members inherited by Orange and
Apple classes have the same access permissions as they
had in their base class Fruits:This is because we have
used the public keyword to define the inheritance
relationship on each of the derived classes:
class Orange: public Fruits{ ... }
This public keyword after the colon (:) denotes the
most accessible level the members inherited from the
class that follows it (in this case Orange) will have.
Since public is the most accessible level, by
specifying this keyword the derived class will inherit
all the members with the same levels they had in the
base class.
If we specify a more restrictive access level like
protected, all public members of the base class are
inherited as protected in the derived class. Whereas if
we specify the most restricting of all access levels:
private, all the base class members are inherited as
private.
For example, if we derive Orange class as:
class Orange: protected Fruits;
Page 110 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
This would set protected as the maximum access level
for the members of Orange that it inherited from Apple.
That is, all members that were public in Fruits would
become protected in Orange. Of course, this would not
restrict Orange to declare its own public members. That
maximum access level is only set for the members
inherited from Fruits.
If we do not explicitly specify any access level for
the inheritance, the compiler assumes private for
classes declared with class keyword and public for
those declared with struct.
Forms of Inheritance
Single Inheritance: It is the inheritance hierarchy
wherein one derived class inherits from one base class.
Multiple Inheritance:It is the inheritance hierarchy
wherein one derived class inherits from multiple base
class(es)
Hierarchical Inheritance: It is the inheritance
hierarchy wherein multiple subclasses inherits from one
base class.
Multilevel Inheritance: It is the inheritance hierarchy
wherein subclass acts as a base class for other
classes.
Hybrid Inheritance:The inheritance hierarchy that
reflects any legal combination of other four types of
inheritance.
Page 111 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
Examples
Single Inheritance
When a class is inherited from one base class,this type
of Inheritance is called Single Inheritance Example
// Inheritance Example
#include <iostream.h>
#include<string.h>
class Fruits
{
public:
char taste[20],color[20];
};
class Orange: public Fruits // Single Inheritance
{
public:
void TasteColor()
Page 112 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
{
strcpy(taste,"sweet-sour");
strcpy(color,"orange");
}
void Display()
{
cout<<"Orange Taste = "<<taste<<endl;
cout<<"Orange Colour ="<<color<<endl;
}
};
int main ()
{
Orange org;
org.TasteColor();
org.Display();
return 0;
}
Output:
Orange's Taste = sweet-sour
Oange's Colour =orange
Multiple Inheritances:
A C++ class can inherit members from more than one
class and here is the syntax:
class derived-class: access base_A, access base_B....
Where access is one of public, protected, or private
and would be given for every base class and they will
be separated by comma as shown above. Let us try the
following example:
#include<iostream.h>
#include<conio.h>
Page 113 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
class A //Use of Multiple
{
protected:
int m;
};
class B
{
protected:
int o;
};
class C: public A, public B
Inheritance
{
public:
void set_m_o()
{
m=5; // m is Inherited from class A
o=6; // o is Inherited from class B
}
void display() // Not Inherited from any class
{
cout<<"m="<<m<<endl;
cout<<"o="<<o<<endl;
cout<<"m*o="<<m*o<<endl;
}
};
int main()
{
A aobj;
B bonj;
C cobj;
cobj.set_m_o();
cobj.display();
return 0;
}
Output:
m=5
o=6
m*o=30
Page 114 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
Multi Level Inheritances:
#include<iostream.h>
class A
{
public :
int a1;
};
class B: public A //class B is publicly derived by
class A
{
public :
int b1; // //class C is publicly derived by
};
class C: public B
class B
{
public :
void Cgetdata()
{
cout<<endl<<"Enter the values of a1 and b1";
cin>>a1>>b1; // a1 and b1 are derived from class A and
class B
}
void Cputdata()
{
cout<<endl<<"You have entered a1 = "<<a1<<"and b1 is
="<<b1;
}
};
int main()
{
C obj;
obj.Cgetdata(); //member function of class C
obj.Cputdata(); //member function of class C
return 0
;
}
Output:
Page 115 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
Enter the values of a1 and b1
10 20
You have entered a1= 10 b1 = 20
What is inherited from the base class?
In principle, a derived class inherits every member of
a base class except:
its constructor and its destructor its operator=()
members its friends
Although the constructors and destructors of the base
class are not inherited themselves, its default
constructor (i.e., its constructor with no parameters)
and its destructor are always called when a new object
of a derived class is created or destroyed.
If the base class has no default constructor or you
want that an overloaded constructor is called when a
new derived object is created, you can specify it in
each constructor definition of the derived class:
derived_constructor_name (parameters) :
base_constructor_name (parameters) {...}
Example:
// constructors and derived classes
#include <iostream.h>
class A
{
public:
A()
{
cout << "A's no parameter constructor\n";
}
A(int a)
{
Page 116 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
cout << "A's one parameter constructor\n";
}
};
class B : public A
{
public:
B(int a) // A's no parameter constructor will called by
the compiler
{
cout << "B's one parameter constructor\n";
}
};
class C : public A
{
public:
C(int a) : A(a) // Explicit Call to A;s one parameter
constructor
{
cout << "C's one parameter constructor\n";
}
};
int main ()
{
B bobj(0);
C cobj(0);
return 0;
}
A's no parameter constructor
B's one parameter constructor
Page 117 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
A's one parameter constructor
C's one parameter constructor
Notice the difference between which A's constructor is
called when a new B's object is created and which a new
C's object is created. This difference is because of
the constructor declaration of B and C class:
B(int a) // nothing specified: call default by the
compiler to A's no parameter constructor
C(int a) : A(a) // constructor specified: Explicit
call to the A's one parameter constructor
Page 118 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
Data File Handling
File
A file is a collection of bytes stored on a secondary
storage device, which is generally a disk of some kind.
The collection of bytes may be interpreted, for
example, as characters, words, lines, paragraphs
,fields and records belonging to a database.
Essentially there are two kinds of files that
programmers deal with text files and binary files.
Text files
A text file can be a stream of characters that a
computer can process sequentially. It is not only
processed sequentially but only in forward direction.
For this reason a text file is usually opened for only
one kind of operation (reading, writing, or appending)
at any given time.
Similarly, since text files only process characters,
they can only read or write data one character at a
time.
Binary files
A binary file is no different to a text file. It is a
collection of bytes. In C++ Programming Language a byte
and a character are equivalent. Hence a binary file is
also referred to as a character stream, but there are
two essential differences.
1.No special processing of the data occurs and each
byte of data is transferred to or from the disk
unprocessed.
2.C++ Programming Language places no constructs on
the file, and it may be read from, or written to,
in any manner chosen by the programmer.
Binary files can be either processed sequentially or,
depending on the needs of the application, they can be
processed using random access techniques. In C++
Programming Language, processing a file using random
access techniques involves moving the current file
position to an appropriate place in the file before
Page 119 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
reading or writing data. This indicates a second
characteristic of binary files. They a generally
processed using read operations
simultaneously. and write
For example, a database file will be created and
processed as a binary file. A record update operation
will involve locating the appropriate record, reading
the record into memory, modifying it in some way, and
finally writing the record back to disk at its
appropriate location in the file.
C++ has two basic classes to handle files, ifstream and
ofstream. To use them, include the header file fstream.
Ifstream handles file input (reading from files), and
ofstream handles file output (writing to files). The
way to declare an instance of the ifstream or ofstream
class is:
ifstream fin;
fin.open("filename");
or
ifstream fin( "filename" );
The default mode for opening a file with ofstream's
constructor is to create it if it does not exist, or
delete everything in it if something does exist in it.
ios::in -- Open file for input mode/read mode
ios::out -- Open file for output mode/write mode
ios::app -- Open file for append mode
ios::binary --Open file in Binary mode
we can combine more than one mode at a time with |
(Logical Or operator)
ofstream fout( "test.txt", ios::in|ios::out );
This will open test.txt file in input as well as in
output mode simultaneously.
Open File in append mode:
ofstream fout( "test.txt", ios::app );
Page 120 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
This will open the file without destroying the current
contents and allow you to append new data.
Detecting End of File
C++ provides a special function, eof( ), that returns
nonzero (meaning TRUE) when there are no more data to
be read from an input file stream, and zero (meaning
FALSE) otherwise.
Rules for using end-of-file (eof( )):
1.Always test for the end-of-file condition before
processing data read from an input file stream.
2.Use a while loop for getting data from an input file
stream.
Example of read from file and display it using eof()
#include<fstream.h>
#include<iostream.h>
#include<conio.h>
int main()
{
ifstream fin;
fin.open("input.txt");
char ch;
while(!fin.eof()) //use of eof() function
{
fin.get(ch);
cout<<ch;
}
fin.close();
getch();
return 0;
}
Program to count number of words
#include<fstream.h>
#include<iostream.h>
#include<conio.h>
int main()
{
ifstream fin;
fin.open("input.txt");
char words[50]; int count=0;
Page 121 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
while(!fin.eof())
{
fin>>words;
count++;
}
cout<<"Number of words in file is "<<count;
fin.close();
getch();
return 0;
}
Program to count number of lines
#include<fstream.h>
#include<iostream.h>
#include<conio.h>
int main()
{
ifstream fin;
fin.open("input.txt");
char line[80]; int count=0;
while(!fin.eof())
{
fin.getline(line,80);
count++;
}
cout<<"Number of lines in file is "<<count;
fin.close();
getch();
return 0;
}
Program to count number of vowels
#include<fstream.h>
#include<iostream.h>
#include<conio.h>
int main()
{
ifstream fin;
fin.open("input.txt");
char ch; int count=0;
while(!fin.eof())
{
fin.get(ch);
Page 122 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
if(ch=='a'||ch=='e'||ch=='i'||ch=='o'||ch=='u')
count++;
}
cout<<"Number of vowels in file are "<<count;
fin.close();
getch();
return 0;
}
Program to count number of digits
#include<fstream.h>
#include<iostream.h>
#include<conio.h>
int main()
{
ifstream fin;
fin.open("input.txt");
char ch; int count=0;
while(!fin.eof())
{
fin.get(ch);
if(isdigit(ch))
count++;
}
cout<<"Number of digits in file are "<<count;
fin.close();
getch();
return 0;
}
Program to count number of line starting with alphabet
‘A’.
#include<fstream.h>
#include<iostream.h>
#include<conio.h>
int main()
{
ifstream fin;
fin.open("input.txt");
char line[80]; int count=0;
while(!fin.eof())
{
fin.getline(line,80);
Page 123 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
if(line[0]=='A')
count++;
}
cout<<"Number of lines starting with A are
"<<count;
fin.close();
getch();
return 0;
}
Program to copy contents of one file to another file.
#include<fstream.h>
int main()
{
ifstream fin;
fin.open("source.txt");
ofstream fout;
fout.open("destination.txt");
char ch;
while(!fin.eof())
{
fin.get(ch);
fout<<ch;
}
fin.close();
fout.close();
return 0;
}
Binary File Handling Functions
ifstream::read
ifstream& read ( char* t, int n );
Reads a block of data of n characters and stores it in
the array pointed by t.
If the End-of-File is reached before n characters have
been read, the array will contain all the elements read
until it.
Notice that this is an unformatted input function and
what is extracted is not stored as a c++ string format,
Page 124 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
therefore no ending null-character is appended at the
end of the character sequence.
Parameters
t
Pointer to an allocated block of memory where the
content read will be stored.
n
Integer value of type streamsize representing the size
in characters of the block of data to be read.
ofstream::write
ofstream& write ( const char* t , int n );
Writes the block of data pointed by t, with a size of n
characters, into the output buffer. The characters are
written sequentially until n have been written.
This is an unformatted output function and what is
written is not necessarily a c++ string, therefore any
null-character found in the array t is copied to the
destination and does not end the writing process.
Parameters
t
Pointer to a block data with the content to be written.
n
Integer value of type streamsize representing the size
in characters of the block of data to write.
Return Value
The function returns *this.
ofstream::seekp()
ofstream& seekp ( int pos );
ofstream& seekp ( int off, ios::seekdir dir );
Sets the position of the put pointer.
The put pointer determines the location in the output
sequence where the next output operation is going to
take place.
Page 125 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
Parameters
pos
The new position in the stream buffer. This parameter
is an integral value.
off
Integral value representing the offset to be applied
relative to an absolute position specified in the dir
parameter.
dir
Seeking direction. It is an object of type ios::seekdir
that specifies an absolute position from where the
offset parameter off is applied. It can take any of the
following member constant values:
ios::beg beginning of the stream buffer
ios::cur current position in the stream buffer
ios::end end of the stream buffer
Return Value
The function returns *this.
Example
// Position of put pointer
#include <fstream.h>
int main () {
long pos;
ofstream outfile;
outfile.open ("example.txt");
outfile.write ("My Name is Ayan",15);
pos=outfile.tellp();
outfile.seekp (pos-4);
outfile.write ("Sanju",5);
outfile.close();
return 0;
Page 126 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
}
In this example, seekp is used to move the put pointer
back to a position 4 characters before the end of the
first output operation. The final content of the file
shall be:
My Name is Sanju
ifstream::seekg()
ifstream& seekg ( int pos );
ifstream& seekg ( int off, ios::seekdir dir );
Sets the position of the get pointer.
The get pointer determines the next location to be read
in the source associated to the stream.
Parameters
pos
The new position in the stream buffer. This parameter
is an integral value of type streampos.
off
Integral value representing the offset to be applied
relative to an absolute position specified in the dir
parameter.
dir
Seeking direction. It is an object of type ios::seekdir
that specifies an absolute position from where the
offset parameter off is applied. It can take any of the
following member constant values:
ios::beg beginning of the stream buffer
ios::cur current position in the stream buffer
ios::end end of the stream buffer
Return Value
The function returns *this.
Example
// load a file into memory
#include <iostream.h>
Page 127 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
#include <fstream.h>
int main () {
int length;
char buffer[100];
ifstream is;
is.open ("test.txt", ios::binary );
// get length of file:
is.seekg (0, ios::end);
length = is.tellg();
is.seekg (0, ios::beg);
// read data as a block:
is.read (buffer,length);
is.close();
cout.write (buffer,length);
return 0;
}
In this example seekg is used to move the get pointer
to the end of the file, and then back to the beginning.
ofstream ::tellp ( );
int tellp ( );
Get position of put pointer
Returns the absolute position of the put pointer.
The put pointer determines the location in the output
sequence where the next output operation is going to
take place.
Return Value
An integral value of type int with the number of
characters between the beginning of the output sequence
and the current position.
Page 128 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
Failure is indicated by returning a value of -1.
Example
// position of put pointer
#include <fstream.h>
int main ()
{
long pos;
ofstream outfile; outfile.open
("test.txt"); outfile.write ("My Name
is Ayan",15); pos=outfile.tellp();
outfile.seekp (pos-4);
outfile.write ("Sanju",5);
outfile.close();
return 0;
}
In this example, tellp is used to get the position of
the put pointer after the writing operation. The
pointer is then moved back 4 characters to modify the
file at that position, so the final content of the file
shall be:
My name is Sanju
ifstream::tellg()
int tellg ( );
Get position of the get pointer.
Returns the absolute position of the get pointer.
The get pointer determines the next location in the
input sequence to be read by the next input operation.
Return Value
Page 129 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
An integral value with the number of characters between
the beginning of the input sequence and the current
position.
Failure is indicated by returning a value of -1.
Example of tellg()
#include <iostream.h>
#include <fstream.h>
int main () {
int length;
char buffer[50];
ifstream is;
is.open ("test.txt", ios::binary );
is.seekg (0, ios::end);
// get length of file:
length = is.tellg();
is.seekg (0, ios::beg);
// read data:
is.read (buffer,length);
is.close();
cout.write (buffer,length);
return 0;
}
In this example, tellg is used to get the position in
the stream after it has been moved with seekg to the
end of the stream, therefore determining the size of
the file.
Some Basic Operations on Binary Files in C++
#include<iostream.h>
#include<string.h>
class student
{
int rollno;
Page 130 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
char name[20];
public:
void getdata()
{
cout<<"\nEnter The Roll no. ";
cin>>rollno;
cout<<"\n\nEnter The Name of The Student ";
gets(name);
}
void showdata()
{
cout<<"\nRoll no. : "<<rollno;
cout<<"\nStudent Name : ";
puts(name);
}
int returnrollno()
{
return rollno;
}
};
This function will write on Binary File
void write_data()
{
student obj; ofstream fout;
fout.open("student.dat",ios::binary|ios::app);
obj.getdata();
fout.write((char*)&obj,sizeof(obj));
fout.close();
}
This function will display records
void display()
{
student obj; ifstream fin;
fin.open("student.dat",ios::binary);
while(fin.read((char*)&obj,sizeof(obj)))
{
obj.showdata();
}
fin.close();
}
Page 131 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
This function will search and display from binary file
void search (int n)
{
student obj; ifstream fin;
fin.open("student.dat",ios::binary);
while(fin.read((char*)&obj,sizeof(obj)))
{
if(obj.returnrollno()==n)
obj.showdata();
}
fin.close();
}
This function will delete a record
void deleterecord(int n)
{
student obj; ifstream fin;
fp1.open("student.dat",ios::binary);
ofstream fout;
fout.open("Temp.dat",ios::out|ios::binary);
while(fin.read((char*)&obj,sizeof(obj)))
{
if(obj.returnrollno()!=n)
fout.write((char*)&obj,sizeof(obj));
}
fin.close(); fout.close();
remove("student.dat");
rename("Temp.dat","student.dat");
}
This function will modify a record
void modifyrecord(int n)
{
fstream finout;
student obj; int found=0;
finout.open("student.dat",ios::in|ios::out);
while(finout.read((char*)&obj,sizeof(obj)) &&
found==0)
{
Page 132 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
if(obj.returnrollno()==n)
{
obj.showdata();
cout<<"\nEnter The New data of student";
obj.getdata();
int pos=-1*sizeof(obj);
finout.seekp(pos,ios::cur);
finout.write((char*)&obj,sizeof(obj));
found=1;
}
}
finout.close();
}
Page 133 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
Pointer
A pointer is a variable which contains the address in
memory of another variable. We can have a pointer to
any variable type.
The & operator gives the address of the variable
pointed by the pointer. The indirection or dereference
operator * gives the contents of the variable pointed
to by a pointer.
To declare a pointer to a variable do:
Data-type *pointer_variable_name;
NOTE: We must associate a pointer to a particular type:
You can't assign the address of a short int to a long
int, for instance.
Consider the effect of the following code:
int x = 1, y = 2;
int *ip;
ip = &x;
y = *ip;
x = ip;
*ip = 3;
Assume that the variable x resides at memory location
100, y at 200 and ip at 1000.
Page 134 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
The assignments x = 1 and y = 2 load these values into
the variables. ip is declared to be a pointer to an
integer and is assigned to the address of x (&x). So ip
gets loaded with the value 100.
Next y gets assigned to the contents of ip. In this
example ip currently points to memory location 100 ,the
location of x. So y gets assigned to the values of x,
which is 1.
It is legal to assign the current value of ip to x. The
value of ip at this instant is 100.Finally we can
assign a value to the contents of a pointer (*ip).
IMPORTANT: When a pointer is declared it does not point
anywhere. You must set it to point somewhere before you
use it.
So ...
int *ip;
*ip = 100;
will generate an error
The correct use is:
int *ip;
int x;
Page 135 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
ip = &x;
*ip = 100; // Now the value of x is 100
We can do integer arithmetic on a pointer:
int *ip;
int i=10;
ip= &i;
*ip = *ip + 5;
++*ip;
(*ip)++;
// The value of i and *ip would be 17
The reason we associate a pointer to a data type is so
that it knows how many bytes the data is stored in.
When we increment a pointer we increase the pointer by
one block memory.
So for a character pointer ++ch_ptr adds 1 byte to the
address.For an integer pointer ++ip_ptr adds 2 bytes to
the address. For a float pointer ++flp_ptr adds 4 bytes
to the address.
Consider a float variable (fl) and a pointer to a float
(flp)
Pointer Arithmetic Assume that flp points to fl then if
we increment the pointer ( ++flp) it moves to the
position shown 4 bytes on. If on the other hand we
added 2 to the pointer then it moves 2 float positions
i.e 8 bytes as shown in the Figure.
Page 136 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
Dynamic memory allocation/deallocation operators
// Use of new and delete operators
#include <iostream.h>
int main ()
{
int *intp = NULL; // Pointer initialized with null
intp = new int; // Request memory for the variable
*intp = 123; // Store value at allocated address
cout << "Pointer intp = " << *intp << endl;
delete intp ; // free up the memory.
return 0;
}
Reference variable
A reference variable is an alias, that is, another name
for an already existing variable. Once a reference is
initialized with a variable, either the variable name
or the reference name may be used to refer to the
variable.
Reference vs Pointer variable:
References are often confused with pointers but three
major differences between references and pointers are:
You cannot have NULL reference for a reference
variable
Once a reference variable is initialized to an
object, it cannot be changed to refer to another
object. Pointers can be pointed to another object
at any time.
A reference must be initialized when it is created.
Pointers can be initialized at any time.
// Reference variable Example
#include <iostream.h>
int main ()
{
// declare simple variables
int i;
Page 137 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
// declare reference variables
int &r = i; // Now we can refer i as r or r is a
alias for i
i = 5;
cout << "Value of i = " << i << endl;
cout << "Value of reference variable r = " << r <<
endl;
return 0;
}
Output
Value of i = 5
Value of reference variable r = 5
Call by value and Call by Reference
When C++ passes arguments to functions it passes them
by value. There are many cases when we may want to
alter a passed argument in the function and receive the
new value back to the calling function. C++ uses
pointers explicitly to do this. The best way to study
this is to look at an example where we must be able to
receive changed parameters. Let us try and write a
function to swap variables:
// Call by Value Example
#include<iostream.h>
int main()
{
void swap(int m,int m);
int a=10 ,b=20;
swap(a,b); // Call by value
cout<<"After interchanging the values ";
cout<<" a = "<<a<<endl<<"b = "<<b;
return 0;
}
void swap(int m ,int n)
{
int a;
a=m;
m=n;
n=a;
cout<<"Inside swap function the values are ";
cout<<endl<<" m = "<<m<<endl<<" n= "<<n;
Page 138 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
}
output:
Inside swap function the values are
m=20
n=10;
After interchanging the values
a=10
b=20
Note: No change to the values of a and b inside the
calling function .Because when we pass values to the
function only the copies of those values get passed not
the original data value .Any change made inside the
called function to these data value is not reflected to
the calling function. That is why we call it call by
value.
swap(a, b) WON'T WORK.
Pointers provide the solution: Pass the address of the
variables to the functions and access address of
function.
Thus our function call in our program would look like
this:
swap(&a, &b)
// Call by Reference Example
#include<iostream.h>
int main()
{
void swap(int *m,int *m);
int a=10 ,b=20;
swap(&a,&b); // Call by reference
cout<<"After interchanging the values ";
cout<<" a = "<<a<<endl<<"b = "<<b;
return 0;
}
void swap(int *m ,int *n)
Page 139 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
{
int a;
a=*m;
*m=*n;
*n=a;
cout<<"Inside swap function the values are ";
cout<<endl<<" *m = "<<m<<endl<<" *n= "<<n;
}
output:
Inside swap function the values are
*m=20
*n=10;
After interchanging the values
a=20
b=10
Note: The values of a and b changed .Because when we
pass reference of the values to the function original
data value are passed .Any change made inside the
called function to these data value is reflected to the
calling function. That is why we call it call by
Reference.
Let us see another way of call by reference using C++
reference variable .
// Using Reference variables method
#include<iostream.h>
int main()
{
void swap(int &m,int &m);
int a=10 ,b=20;
cout<<"After interchanging the values ";
swap(a,b); // Call by value
cout<<" a = "<<a<<endl<<"b = "<<b;
return 0;
Page 140 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
}
void swap(int &m ,int &n)// use of reference variable
{
int a;
a=m;
m=n;
n=a;
cout<<"Inside swap function the values are ";
cout<<endl<<" m = "<<m<<endl<<" n= "<<n;
}
output:
Inside swap function the values are
m=20
n=10;
After interchanging the values
a=20
b=10
Pointers and Arrays
Pointers and arrays are very closely linked.
Consider the following:
int a[10], x;
int *pa;
pa = &a[0]; /* pa pointer to address of a[0] */
x = *pa;
/* x = contents of pa (a[0] in this case) */
Arrays and Pointers
To get somewhere in the array using a pointer we could
do:
(pa + i)= a[i]
C++ however is much more subtle in its link between
arrays and pointers.
For example we can just type
pa = a;
instead of
Page 141 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
pa = &a[0]
and
a[i] can be written as *(a + i).
We also express pointer addressing like this:
pa[i] = *(pa + i).
However pointers and arrays are different:
A pointer is a variable. We can do
pa = a;
pa++ ;
An Array is not a variable.
a = pa and a++ ARE ILLEGAL.
We can now understand how arrays are passed to
functions. When an array is passed to a function what
is actually passed is its initial elements location in
memory.
So:
int a[]={1,2};
void arpass(int a[]);
arpass(a) ;
/* Passing array in a function. Here only name of the
array is required, it is same as arpass(&a[0]); */
Example of passing array in a function
#include <iostream.h>
int main ()
{
int a[]={1,2}; // Declare simple int arry
void arpass(int a[]); // Function declaration for
accepting array as an argument
arpass(a); //At the time of call only the name of the
array needs to specified
Page 142 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
return 0;
}
void arpass(int a[]) // Function Definition
{
for(int i=0;i<2;i++)
cout<<a[i];
}
Pointer to an One Dimensional Array
#include <iostream.h>
int main ()
{
int i,a[5];
int *p;
p=a; // same as p = &a[0]
cout<<endl<<"Enter 5 Numbers ";
for(i=0;i<5;i++)
cin>>p[i]; // same as a[i]
//Other form of the above statement is cin>>*(p+i);
cout<<endl<<"You have Entered";
for(i=0;i<5;i++)
cout<<p[i]<<endl; // same as a[i]
// Other form of the above statement is cout<<*(p+i);
return 0;
}
Function Returning a Pointer
If a function return type is a Pointer of any data type
then we say that this function will return Pointer.
// A c++ Example of Function returning Pointer
#include<iostream.h>
int main()
{
int *func(int a); // this function will return a
Pointer
int *p;
int a;
cout<<"Enter a Number";
Page 143 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
cin>>a;
p=func(a); // P will point to the pointer
returned by *func()
cout<<" *p = "<<*p;
return 0;
}
int *func(int a)
{
int *t;
t =&a;
return t; // This statement will return a
Pointer
}
Arrays of Pointers
There may be a situation when we want to maintain an
array which can store pointers to an int or char or any
other data type available. Following is the declaration
of an array of pointers to character:
int *ptr[SIZE];
This declares ptr as an array of SIZE integer pointers.
Thus, each element in ptr, now holds a pointer to an
integer value. Following example makes use of two
integer pointers which will be stored in an array of
pointers as follows:
Array of Pointer Example:
#include <iostream.h>
const int SIZE = 2;
int main ()
{
int i=10,j=20 ,*ip ,*jp;
int *arrp[SIZE];
ip=&i;
jp=&j;
arrp[0]=ip;
arrp[1]=jp;
for (int t = 0; t < SIZE; t++)
Page 144 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
{
cout << "Value of arrp[" << t << "] = ";
cout << *arrp[i] << endl;
}
return 0;
}
When the above code is compiled and executed, it
produces following result:
Value of arrp[0] = 10
Value of arrp[1] = 20
Pointers and Structures
These are fairly straight forward and are easily
defined. Consider the following:
struct Ayan
{
int a,b;
}ap;
struct Ayan *aptr;
aptr = ≈ // assigns pointer to &ap
the -> operator lets us access a member of the
structure pointed to by a pointer i.e.:
aptr->a = 10;
aptr->b = 20;
Example of Pointers and Structure
#include <iostream.h>
struct Ayan
{
int a,b;
}ap; // Structure variable
struct Ayan *aptr; // Pointer Structure variable
int main()
{
aptr = ≈ // Assigns address of ap to pointer aptr
Page 145 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
// Accessing structure members through Pointer
aptr->a=10;
aptr->b=20;
cout<<endl<<"a =" <<aptr->a<<" b = "<<aptr->b;
return 0;
}
Output
a=10
b=20;
Self Referential Structure
Suppose we have a structure declaration linke this
struct list
{
int data;
struct list *next;
//Above statement makes struct list as self
referential
}*node;
Any structure which have a member of type structure
itself is called a Self referential structure. In the
above example structure list contain a member *next
whose data type is structure itself, this will makes
struct list as Self Referential Structure. These types
of structures are generally used for Queue,Stack and
Linked List implementation.
Page 146 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
XII – COMPUTER SCIENCE UNIT –II C++
Page 147 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
Array
An array is a series of elements of the same type
placed in contiguous memory locations that can be
individually referenced by adding an index to a unique
identifier.
That means that, for example, we can store 5 values of
type int in an array without having to declare 5
different variables, each one with a different
identifier. Instead of that, using an array we can
store 5 different values of the same type, int for
example, with a unique identifier.
Arrays come in two flavors: one dimensional and
dimensional arrays.
Declaring an Array
Just like any variable ,an array has to be declared
before being used. Yet the difference this time is that
you need to tell the compiler what kind of array you
are defining. This is because, once more, the compiler
wants to know how much space your array is going to
occupy in the computer memory. This is because when you
declare an array of items, the compiler puts each one
of the items in an appropriate location.
Like any other variable, the syntax of declaring an
array is:
DataType ArrayName[size]
Page 148 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
The array is first identified by its kind, which could
be a char, an int, a float, etc; followed by its name.
The name is then followed by square brackets that
specify the size of the array.
Here are examples of declaring arrays:
int a[4];
float f[100];
double d[100];
int a[4]; declares a group or array of 4 values, each
one being an integer.
float f[100]; declares an array of 100 floating-point
values.
double d[100]; declares an array of double-precision
numbers. There are 100 of these items in the group.
Initializing an Array
Just like any variable can be initialized, an array
also can be initialized. To accomplish this, for a one-
dimensional array, the syntax used is:
DataType ArrayName[size] = { element1, element2, …,
elementn};
Here are examples of declaring an initializing arrays:
int num[5] = {1,2,3,4,5};
If you have decided to initialize the array while you
are declaring it, you can omit the size. Therefore,
array can be declared as follows:
int num[] = {1,2,3,4,5};
Processing the Elements of an Array
Page 149 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
After initializing an array, its elements are counted
from left to right. Each element of the array, also
called a member of the array, has a specific and
constant position. The position of an item is also
called its index. The first member of the array, the
most left, has an index of 0. The second member of the
array has an index of 1. Since each array has a number
of items which can be specified as n, the last member
of the array has an index of n-1
Based on this system of indexing, to locate a member of
an array, use its index in the group. Imagine you
declare and initialize an array as follows:
double weight[] = {20.2,24.5,34.7};
To locate the value of the 3rd member of the array, you
would type weight[2]. In the same way, the 1st member
of the array can be located with weight[0].
Once you can locate a member of the array, you can
display its value. Here is an example:
#include <iostream.h>
int main()
{
double weight[] = {20.2,24.5,34.7};
cout << "2nd member = " << weight[1] << endl;
cout << "3rd member = " << weight[2] << endl;
return 0;
}
This would produce:
2nd member = 24.5
3rd member = 34.7
The Size of an Array
When declaring an array, we saw that you must specify
the number of items that the array is made of. Here is
an example:
float price[5];
Page 150 of 232