Escolar Documentos
Profissional Documentos
Cultura Documentos
C++
(Object Oriented Programming)
Introduction:
A language is basically for providing better communication between two or more
objects. There are certain language categories that provide communication between a
computer and its user. Such languages are said to be computer languages. They are
meant for better problem solving. In order to provide better instructions for problem
solving in any language, the language must posses various features. In fact, many
things can judge a languages efficiency. Some of the following:
A well defined syntax and semantic structure
Reliability
Fast translation
Efficient object code
Orthogonal
Machine independence
Provability
Genericity
Consistency
Uniformity
Extensibility
The process of problem solving may be referred as Programming. In computers,
programming techniques are classified in to 4 types. The list follows:
Monolithic Programming.
Procedural Programming.
Structured Programming.
Monolithic Programming:
The programs written in these languages provide only global data & sequential code
that manage the data. It doesnt support any loops & functions concept. Only
branching statements like goto can be used.
PRKP/KMK
C++ Material
1
2
3
go to 100
------- --------------- --------go to 2
------- ---------
Global data
Assembly languages and Basic are the examples for monolithic programming.
Procedural Programming:
The program written in these languages provide both global data, sequential code
along with control structures.
Sub programs
Fortran & COBOL are the examples for procedural language.
Structured Programming:
A new programming technique called structured programming has came into picture
after the procedural languages. It supports both control structures and functions in
addition to top down approach. In this approach, there is more concentration on
functions rather than data.
PRKP/KMK
C++ Material
Sub-modules
Each program in this approach consists of several modules and each module has its
own local data along with the global data. Pascal & C are the examples for structured
programming languages. It becomes tedious to implement complex applications using
structured programming languages and even they are costly to implement.
Object Oriented Programming:
In order to develop large software systems, we require a better programming
approach compare to structured programming. Moreover, such systems require more
concentration rather than data. To achieve this, a new programming approach has
been developed called Object oriented programming where data may be organized in
terms of classes and objects to improve better accessibility and security to the data.
Object 1
Data
Object2
PRKP/KMK
Functions
Object 3
Data
Data
Functions
Functions
C++ Material
C++, Smalltalk, Java are the some of the examples for oop languages.
In Object oriented approach everything is identified in terms of objects or entities.
OOP is a method of implementation in which programs are organized as a
cooperative collection of objects, each of which represents an instance of
some class.
In OOP concept you find different jargon like class, object, data abstraction,
encapsulation. Here,
A class is a blue print for several objects. Or a class is a logical construct that doesnt
have any physical occupation. Or a class is a ADT (abstract data type) the defines a
set of properties and behavior as a unit. Or a class is a template that unites data and
functions.
Here we can assume that properties are nothing but data members and behavior
means operations or functions.
An object is an instance of a class. Or an object is a physical construct that occupies
certain amount of memory.
For example:
Class : Person
Properties: Name, age, sex.
Functions: listen(), speak()
Class: Student
Properties: stno, name, group
Functions: get(), put() etc.,
PRKP/KMK
C++ Material
classes
objects
Data abstraction
Data encapsulation.
Polymorphism
Inheritance
Templates
Persistence
Message passing.
Extensibility.
Classes & Objects: In OOP concept, a class & an objects are the basic units. Here a
class is a collection of data and its corresponding member functions and it is an
abstract data type. An object is a physical construct that holds certain amount of
memory and it is assumed as a runtime entity.
Data Abstraction: The process of creation of a new data type from already existing
data types is referred as data abstraction. In other words, the process of exhibiting the
essential information without revealing the background details is referred as data
abstraction.
Data Encapsulation: The process of wrapping up of data and its corresponding
member functions as a single unit is said to be data encapsulation. It leads to data
hiding. which disables unauthorized access to the data.
Polymorphism: Polymorphism is one of the striking features of any object oriented
programming language. Poly means many and morphism means forms. The ability
of providing multiple definitions to the same function name or operator is referred as
polymorphism.
PRKP/KMK
C++ Material
Inheritance: Inheritance is one of the most striking features of OOPs concept. The
process of extracting the features of one class into another is said to be inheritance.
The main objective of inheritance is to provide code reusability.
Templates: A template is a generic function that works on different types of data.
OOPs supports generic programming. It is one of the advanced concepts of c++.
Persistence: The process of providing life to objects even after completion of
program is called persistence. I.e., one can made objects permanent through I/O
streams.
Message Passing: The process of invoking any operation on an object is referred as
message passing.
Extensibility:
PRKP/KMK
C++ Material
Introduction to C++
Bjarne Stroustrup invented C++ at AT&T Bell labs as an extension to C in the year
1980. The initial name of C++ was C with Classes. As C++ is an extension to C, it
supports all the concepts of C. Hence the learner may not feel C++ as a completely
new language.
In fact, C++ is not meant for simple applications. Its usage may be extended to
complex applications as it uses classes and objects.
Either Borland C++ or Turbo C++ or ANSI C++ compiler may be used for developing
applications.
For any language, the smallest individual units are in a program are called as tokens.
The C++ tokens are:
Keywords.
Data Types.
Operators.
Identifiers.
Constants.
Strings.
Note :
C++ supports 48 keywords including all the 32 keywords of C.
In addition to C data types, some other data types are also available.
In addition to C operators, more number of operators list is also provided.
Some of the operators that are additional in C++ are:
PRKP/KMK
::
.*
->*
new
delete
endl
<<
insertion operator
>>
extraction operator
setw
Etc.,
C++ Material
functions)
public section
(declaration of either data members or member
functions)
};
class member function definitions
void main()
{
-----------------}
Note:
1. Either single line or multi-line commenting may be used in C++.
2. Every class definition must be terminated by semi coolen.
3. For every class there must be an object in order to make a call to the
function.
4. There may be any no. of objects for a class.
5. One program may have any no. of classes.
Standard I/O operations:
In C++ the basic Input and output operations can be performed using predefined
stream I/O objects called cout & cin.
PRKP/KMK
cout
console output
cin
console input.
C++ Material
cout
<<
Keyboard
cin
>>
A,B
C++ Material
advantages. It is used to define the scope of a variable and is used to define member
functions of a class outside the class.
For ex1:
#include<iostream.h>
int a = 10;
//global variable
void main()
{
int a = 20;
for (int k = 0; k<4 ; k++)
{
cout<<k<<endl; // prints local variable
cout<<::k<<endl;// prints global variable
}
}
Note: Runtime declaration of variables may be performed in C++. In the above
example k was declared when it is required. Variables may be declared anywhere in
the program.
PRKP/KMK
C++ Material
Ex2:
#include<iostream.h>
class test
{
int a,b;
public:
void get();
void put();
};
void test ::get()
{
a = 10;
b = 20;
}
void test :: put()
{
cout<<a<<b<<endl;
}
void main()
{
test t;
t . get ();
t . put ();
}
Reference Variables
A reference variable creates an alias name to a variable. I.e., more than one reference
name (variable name) may be there to the same data. It provides the behavior of a
pointer variable. However, it may not be as flexible as a pointer. Moreover a reference
variable must be initialized at the time of declaration itself. Another point to be noted
is, an alias name may be created to a constant value. I.e.,
For ex:
int A = 10;
Int &B = A; // valid;
PRKP/KMK
C++ Material
A,B
Note:
10
1005
Inline Functions:
An Inline function is similar to a macro in its behavior. It never gets through overheads
like loading, compilation and debugging as the normal functions have. It improves
program execution speed. In fact, a macro never gets compiled; instead, it replaces
the statement with the required statement.
In order to develop an inline function, one has to precede a keyword inline to the
function definition.
Syntax is:
Inline return type function name (arguments list)
{
body of function;
}
PRKP/KMK
C++ Material
Example:
# include <iostream.h>
void main()
{
int k;
cout<<Enter k;
cin>>k;
k = cube(k);
cout<<The value of k is<<k;
}
inline int cube(int z)
{
return (z*z*z);
}
Before implementing Inline Functions, remember the following:
An inline function should not contain complex control structures like switch and
goto.
PRKP/KMK
C++ Material
A data member of a class can be declared as static data member. The behavior of
static data member resembles C static variables.
Only one copy of static data member is created for entire class. Hence all the
objects of the class share the same data member..
Definition might be inside or outside of the class. While defining outside, it must
precede class name and scope resolution operator.
Syntax:
A static function does not require any objects in order to call itself.
i.e., we use class name & scope resolution operator to call a static function.
PRKP/KMK
C++ Material
Friend Functions
A friend function is a special kind of function used to access private data of a class. It
is a function implemented only in C++. A non-member function that has access to the
private data of a class is nothing but friend function.
In order to implement friend functions, use friend keyword while defining the
function. The declaration of the friend function must be in the class but the
corresponding definition must be outside the class. Though the declaration is there in
the class, the function is not supposed to be part of the class. More than one object of
the same class or more than one class can be accessed by a friend function.
Some times we may raise a situation where more than one class wants to share the
same function. In such situations friend functions are the best choice.
In order to implement friend functions, one has to remember the following:
Only the declaration of friend function must be within the class but the definition
should be outside class.
While calling the friend function, you need not to create object or use object.
If Friend function trying to access objects of more than one class, then the
declaration must be in all the classes.
Example:
Class student
{
int stno;
char stname[10];
PRKP/KMK
C++ Material
public:
void get_info()
{
cout<<Enter student no;
cin>>stno;
cout<<enter student name;
cin>>stname;
cout<<Enter m1,m2,m3;
cin>>m1>>m2>>m3;
}
void find_total()
{
total = m1+m2+m3; //calculating total marks
}
void disp_info()
{
cout<<Stno = <<stno<<endl;
cout<<Name =<<stname<<endl;
cout<<Total = <<total<<endl;
}
friend student highest_marks (student, student, student);
//friend function declaration.
}; //end of class.
Student highest_marks(student s1, student s2, student s3)
{
if((s1.total>s2.total)&&(s1.total>s3.total))
return s1;
else
if ((s2.total>s1.total)&&(s2.total>s3.total))
return s2;
else
return s3;
} //end of friend function definition.
PRKP/KMK
C++ Material
void main()
{
student s1,s2,s3, s;
s1.get_info(); s1.find_total();
s2.get_info(); s2.find_total();
s3.get_info(); s3.find_total();
s = highest_marks (s1, s2, s3); //calling friend function
s.disp_info();
}
PRKP/KMK
C++ Material
C++ Material
Default constructor.
Parameterized Constructor.
Copy constructor.
Like a constructor, destructor also has the same name as its class name.
Example:
Class demo
{
public:
demo()
{
cout<<this is a demo program<<endl;
cout<<Object was initialized<<endl;
cout<<through the constructor<<endl;
PRKP/KMK
C++ Material
Output:
PRKP/KMK
C++ Material
Polymorphism
Polymorphism is one of the striking features of any Object Oriented language. Poly
means many & morphism means forms. The process of providing multiple forms is
referred as polymorphism.
Polymorphism is classified in to two types:
1. Compile time polymorphism.
2. Runtime Polymorphism.
The Other classification is:
1. Function Overloading.
2. Operator Overloading.
Function Overloading: The process of providing multiple definitions to the same
function signature is referred as function overloading. In other words, the process of
extending the capability of the same function signature by providing more definitions
may be called as function overloading.
In fact, as per any other nonoops based language, one function should have one
function definition i.e., unique function name & definition may be there for every
function.
This process may increase the clarity of the program and reduces complexity of the
language to some extent.
In function overloading, functions may be differentiated by the number of arguments,
type of arguments and the order of the arguments passed to the function. The function
signature doesnt include the return type.
For example:
Return type function name(arguments list);
Function signature
#include<iostream.h>
PRKP/KMK
C++ Material
class sample
{
public:
void show(int a)
{
cout<<Integer is::::<<a<<endl;
}
void show(char a)
{
cout<<Character is::::<<a<<endl;
}
void show(float a)
{
cout<<Float value is::::<<a<<endl;
}
};
void main()
{
sample s;
s.show(89);
s.show( M );
s.show(123.4f);
}
o/p:-
Integer is::::89
Character is::::M
Float value is::::123.4
PRKP/KMK
C++ Material
Operator Overloading:
Usually operators are meant for performing operations on standard data types in
normal programming languages. But C++ allows the operators play another vital role
in overloading. The process of extending the capability of an operator by providing
additional definition is referred as operator overloading.
Consider an example, the operator + is able to perform arithmetic addition over the
numeric data. But its capability may be extended to strings & objects. Hence we say,
operators allow polymorphism i.e., performing many actions with a single operator.
However, we do not disturb the actual meaning of the operator.
Most of the C++ operators may be overloaded. In order to overload any operator, use
operator keyword. Initially we write an operator function to assign a new definition to
the operator. Such definition must precede operator keyword.
Syntax:
Return type operator Operator Symbol (arguments list);
{
// body of the function
}
Both unary & binary operators may be overloaded but not the ternary operator.
An operator function may be a friend function.
Ex1: void operator +(complex);
Complex operator +(complex, complex);
Void operator ==(string, string);
The following is the list of operators that cant be overloaded:
PRKP/KMK
Operator Category
Operator
1. Member access
(dot operator)
2. Scope resolution
::
3. Conditional
?:
size of
5. Pointer to member
C++ Material
#include<iostream.h>
class string
{
char str[20];
public:
string()
{
cout<<Enter any string;
cin>>str;
}
void show()
{
cout<<String is..<<str<<endl;
}
void operator +(string &s)
{
strcat(str,s.str);
}
};
void main()
{
string s1,s2;
s1.show();
s2.show();
s1+s2;
s1.show();
}
In the above example strings of s2 is concatenated to string of s1. To implement this,
we have used operator overloading. An operator + is overloaded i.e., an operator
function is written.
Here the statement s1+s2; is converted as s1. +(s2);
Moreover, an operator function can be a friend function. In the above example, if the
operator function was written as friend then the statement s1+s2; is converted as:
S1+S2; --
PRKP/KMK
+(S1,S2);
C++ Material
Inheritance
Inheritance is the most striking feature of OOP language that allows hierarchical
classifications. Or Inheritance is a technique of organizing information in a hierarchical
form. Inheritance is a process of extracting the features of one class into another. The
main object of inheritance is reusability.
In some other way, inheritance allows new classes to be built from the older or
existing classes instead of rewriting again. In this approach, multiple classes are
involved. Moreover, apart from private & public access specifiers, it allows protected
specifier.
Types of Inheritances:
B
Single Inheritance
Multiple Inheritance
B
B
C
C
Hierarchical Inheritance
Multi-level Inheritance
D
Hybrid Inheritance
PRKP/KMK
Multi-path Inheritance
C++ Material
Once the inheritance concept is implemented, the member functions and data
members of base class may be used in derived as if they are defined in the derived
class itself.
Single Inheritance: The process of extracting the features of one class into another
class is referred as single inheritance. In this approach, two classes are involved in
which one class is base class and the other class is derived class.
Syntax:
Class base class name
{
------;
------;
};
Class base derived name : visibility specifier base class name
{
-------;
-------;
};
Ex:
Class demo
{
------;
------;
};
Class derived : public demo
{
-------;
-------;
};
Multiple Inheritance: In this approach, multiple base classes and a single derived
class is existed.
Syntax:
Class base1
{
------;
------;
};
Class base2
{
PRKP/KMK
C++ Material
------;
------;
};
Class derived : visibility specifier base1, visibility specifier base2....
{
-------;
-------;
};
Multi-level Inheritance: In multi-level, more than one base & derived classes are
existed. A class that acts as both base & derived class is referred as intermediate base
class.
Class base
{
------;
------;
};
Class intermediate base : visibility specifier base
{
------;
------;
};
Class derived : visibility specifier intermediate base
{
-------;
-------;
};
Hierarchical Inheritance: In hierarchical, one single base class is being inherited by
multiple derived classes.
Class base
{
------;
------;
};
Class derived1: visibility specifier base
{
------;
------;
};
Class derived2 : visibility specifier base
{
-------;
-------;
};
Class derived3 : visibility specifier base
{
PRKP/KMK
C++ Material
-------;
-------;
};
Hybrid Inheritance: A inheritance that includes more than one type of inheritance or
a inheritance that is combination of multiple inheritances is referred as hybrid
inheritance.
Access Specifiers in C++
C++ supports three different access specifiers called private, public and protected.
They specify how the data members of the classes that are involved in inheritance may
be accessed.
Private data members are always private. They are highly restrictive data
members.
Public data members have global accessibility. They can be directly accessed or
indirectly through the object of the class.
Protected data members acts sometimes as private & sometimes as public. This
can be implemented only in inheritance concept. In case of independent classes
that do not inherit any of the existing classes protected data members act as
private, i.e., for all non-derived classes protected data members are private. For
all derived classes, protected data members act as public.
Function Type
Private
Public
Protected
Class member
Yes
Yes
Yes
No
Yes
Yes
Friend
Yes
Yes
Yes
Yes
Yes
Yes
PRKP/KMK
C++ Material
Constructors in Inheritance:
In inheritance, constructors & destructors may be implemented based on the
requirement. Both base & derived classes can have constructors. In such cases, if we
create object for the derived class, the corresponding base class constructor gets
invoked first, then the derived class constructor. Even a base class constructor may be
there without having to create derived class constructor.
Ex:
Class sample
{
public:
sample()
{
cout<<Base class constructor<<endl;
}
};
class test : public sample
{
public:
test()
{
cout<<Derived class constructor;
}
};
void main()
{
test t; // object of derived class that invokes constructors.
}
o/p:-
C++ Material
};
class test : public sample
{
int b;
public:
test(int m, int n) : sample(n)
{
b = m;
cout<<Derived :<<b;
}
};
void main()
{
test t(33,99); // object of derived class that invokes constructors.
}
Note: Here 33 and 99 are passed to derived class constructor as m & n. From there
value of n is sent to the base class constructor.
Virtual Base Classes: In multi-path inheritance, multiple copies of the base class will
exist in the corresponding derived class through intermediate base classes. In such
situations, ambiguity comes into picture. Here we are required to ignore any one of the
copies from the existed. In order to achieve this we have two ways to follow:
a. Make the base class as virtual base class.
b. Use scope resolution operator.
PRKP/KMK
C++ Material
Example:
#include <iostream.h>
class DEMO
{
public:
int a;
};
class SUB_DEMO1:public DEMO
{
public:
int b;
};
class SUB_DEMO2:public DEMO
{
public:
int c;
};
class SUB_DEMO3:public SUB_DEMO1, public SUB_DEMO2
{
public:
int sum;
};
void main()
{
SUB_DEMO3 d;
d.SUB_DEMO1::a = 1;
d.SUB_DEMO2::a = 2;
d.b = 6;
d.c = 7;
d.sum=d.SUB_DEMO1::a + d.b + d.c;
// 1 + 6 + 7
// Displays 1
PRKP/KMK
C++ Material
// 5 + 2 + 3
PRKP/KMK
C++ Material
Virtual Functions
A virtual function is a member function that is declared within a base class and
redefined by a derived class. To create a virtual function, precede the functions
declaration in the base class with the keyword virtual.
To be more specific, virtual functions concept allows users to have more than
one definition to the same function signature i.e., it allows One interface multiple
methods.
In some other way, a class may have a function whose definition is available in the
corresponding derived class.
polymorphism. When a base pointer points to a derived object that contains a virtual
function, C++ determines which version of that function to call based upon the type of
object pointed to by the pointer.
Usually the process of providing multiple definitions to the same function signature in
both base & derived classes may be referred as function overriding. Such function
overriding can be achieved by virtual functions. A class that has virtual function may
be referred as polymorphic class. In order to achieve flexibility of virtual functions, one
has to implement object pointers.
Example:
Class base
{
public:
virtual void demo()
{
cout<<Base class function;
}
};
class first : public base
{
public:
void demo()
{
cout<<Frist Derived class function;
}
};
class second : public base
{
public:
void demo()
{
PRKP/KMK
C++ Material
void main()
{
base *p; //base class pointer
base v;
first f;
second s;
p = &v;
p->demo(); //base class function
p = &f;
p->demo();//first derived class function
p = &s;
p->demo(); //second class function
}
Note: In fact, if we try to access demo() through the object of derived class, it always
accesses the derived class function.
Some times the user may not have anything to implement the base class function. In
such cases, the function may be defined as a pure virtual function i.e., a pure virtual
function that has no definition within the base class. To define a pure virtual function,
use the following:
Syntax:
Example:
Virtual void show() = 0;
Rules for Virtual Functions:
1. A virtual function may not be static.
2. It can be a friend function to another class.
3. Object pointers access them.
4. It should be in public section of the class.
5. Prototype in the base & derived must be identical.
6. There can be virtual destructors but not virtual constructors.
7. Use object pointers for the base class only.
8. It is used majorly in hierarchical inheritance.
C++ maintains a virtual table that holds the addresses of the function. When C++
statements call these member functions, the correct address is fetched from the table;
PRKP/KMK
C++ Material
this process may consume some time. However, virtual functions provide lot of
flexibility to the users.
Abstract Class: A class that contains at least one pure virtual function is said to be an
abstract class. Moreover, we cant create an object for such classes.
Finally we conclude that virtual functions achieve runtime polymorphism. In this
approach, we find new words like early binding and late binding.
Early Binding refers to events that occur at compile time i.e., early binding occurs
when all information needed to call a function is known at compile time. In some other
way, object and the corresponding function call may bound at compilation. This is
referred to static binding or early binding.
On the other hand, late binding is opposite to early binding. It refers to the function
calls that are not resolved until runtime. This is also referred as runtime binding or
dynamic binding.
PRKP/KMK
C++ Material
I/O Streams
Every program must under go a process of input - computation - output so that it can
take input and send the processed data as output. Usually, c++ provides such a
mechanism through objects like cin and cout with the stream operators >> , <<.
Moreover, streams and their handling mechanism are done with console I/O and disk
I/O.
A stream is a collection of or sequence of character data. In some other way, a stream
is series of bytes, which act either as a source from which input data can be extracted
or as a destination to which the output can be sent.
The input and output are managed by and I/O system and it in turn is designed to
operate on a wide variety of devices including consoles, disks and printers etc.,
The following diagram resembles the whole system:
Streams are classified into two categories:
Input streams.
Output streams.
An input stream allows the user to perform only input operations (read operations)
where as output streams allow to perform output operations(write operations).
The I/O operations are also categorized as follows:
Console I/O.
File I/O or Disk I/O
Predefined C++ stream objects:
C++ provides these predefined stream objects:
Cin
Standard input
Cout
Standard output
cerr
Standard error
Clog
PRKP/KMK
usually keyboard,
corresponding to stdin
in C
usually screen,
corresponding to stdout
in C
usually screen,
corresponding to stderr
in C
A fully-buffered version
of cerr (no C equivalent)
C++ Material
You can redirect cin, cout, cerr, and clog from and to other devices and files.
IOStream Class
What It Does
Streambuf
ios
istream
ostream
iostream
istream_withassign
ostream_withassign
(IOSTREAM.H)
ios
istream
streambuf
ostream
iostream
Istream_
withassig
n
PRKP/KMK
Iostream_
withassign
Ostream_
withassig
n
C++ Material
Unformatted Console I/O operations : The most commonly used objects throughout the c++ program are cin & cout. They
are predefined
<< respectively.
The other functions are :
Void get( char &); - to read a single character.
Int get();
- to read a single integer value.
Istream& getline(char *, int length) - to read a char. Array.
Ostream :: write(char * buffer, int length) used to write any char. Data.
Formatted Console I/O operations : Most programs need to output data in various styles. A common requirement is to
reserve an area to format the output. To do this, there must be a provision for
alignment of the data. C++ provides variety of features to perform i/o in different
formats. This can be achieved using :
a) ios stream class member functions and flags.
b) Predefined manipulators.
The ios stream class class provides several member functions to assist in designing the
output in number of ways. The general functions are :
1) width ( )
2) precision ( ) :
3) Fill( )
4) setf ( )
5) unsetf( )
PRKP/KMK
C++ Material
The following is the list of flags that have bit field option : -
FLAGS
BITFIELDS
EFFECTS PRODUCED
ios::left
ios::right
ios::internal
ios::adjustfield
ios::adjustfield
ios::adjustfield
ios::dec
ios::oct
ios::hex
ios::basefield
ios::basefield
ios::basefield
decimal conversion.
octal conversion.
hexadecimal conversion.
ios::scientific
ios::floatfield
ios::fixed
ios::floatfield
Effect Produced
Ios:: showbase
Ios:: showpos
Ios:: showpoint
Ios:: uppercase
Ios::stdio
Manipulators : A mainpulator is a function that can be used in association of << and >> operators
to format the output or to alter the behaviour of the cin and cout objects. Manipualtors
are classified into two categories :
1) parameterized manipulators.
2) Non parameterized manipulators.
PRKP/KMK
C++ Material
Manipulator
action performed
equivalent to
width( ).
precision().
3) setbase(int base)
4) setfill ( char)
Fill().
5) setiosflags(long flag)
Setf ( ).
Unsetf( ).
The non parameterized maniputlators are endl, ends, ws, dec, oct, hex etc.,
FILE I/O
A file is a collection of related information stored permanently in disk or a file is a
collection of character data.
between the programs and files. The streams that supply the data to programs are
referred as input streams and the one that receive data from the program is known as
output stream.
In other words, we say an input stream reads data from the file & an output stream
writes data to the file.
In fact, no external device will be in direct communication and hence a stream is
associated with each device.
The stream object itself performs the necessary
operation.
The general operations that can be performed with a file are :
i.
ii.
iii.
iv.
PRKP/KMK
Naming a file.
Opening a file.
Processing the file( i.e., performing read/write operation).
Closing the file.
C++ Material
streamb
ios
uf
ostream
istream
Streamb
uf
ifstream
fstream
ofstream
filebuf
fstreambase
PRKP/KMK
FILE MODE
MEANING
Ios:: app
C++ Material
Go to end
To open a
To open a
To open a
Open fails
of file on opening.
binary file .
file in read mode.
file in write mode.
if the file doesnt exists.
By creating objects to these objects one can achieve i/o operations to the disk files.
The objects create file pointers to perform operations. The file pointers are get pointer
(input pointer) & put pointer (output pointer). These pointers facilitate the movement
across the file while reading and writing.
ex1 : - (for writing data on to a file )
#include <iostream.h>
void main()
{
char name[20];
int marks;
ofstream myobject (st.dat); //creation of output object
cout<<enter name;
cin>>name;
cout<<enter marks;
cin>>marks;
myobject << name<<endl<<marks<<endl; // this allows to store name & marks in
the file
st.dat through the object myobject.
}
ex2 : - ( reading the contents of a file)
#include <iostream.h>
void main()
{
char name[20];
int marks;
ifstream myobject (st.dat); //creation of input object to read contents.
myobject >> name;
myobject >> marks;
cout << name<<endl<<marks<<endl; // this allows to read name & marks from the
file
st.dat through the object myobject.
}
Actually, sequential access of data is done in files. These files allow random access
i.e., the file pointers can be kept at required location in the disk file. To place the
pointers at the required location, there is a list of functions.
PRKP/KMK
C++ Material
Seekg( ) - ifstream
C++ Material
cin>>marks;
myobject.write((char *) &s,sizeof(s)); // this allows to store name & marks in the file
st.dat through the object myobject.
}
myobject.seekg(0,ios::beg);
cout<<Name of student<<Group<<Marks<<endl;
cout<<-------------------<<--------<<--------<<endl;
for(int I=0;I<5;I++)
{
myobject . read((char *) &s,sizeof(s));
cout<<s.name<<\t<<s.group<<\t<<s.marks<<endl;
}
}
PRKP/KMK
C++ Material
Templates
A template is a generic function that creates a generalized function that works
for all primitive or standard data types. In some other way a template defines a
general set of operations that will be applied to various types of data. The type of data
that the function operates upon is passed as a parameter. The process of creation of
such generic function is referred as generic programming.
Usually a program may consist of several functions that have a common
functionality but the operating data might be different. In such situations often we
define overloading concept. However, an extended version of overloading may be
observed in templates. With templates one can avoid rewriting of code again & again.
A generic function to be created uses a keyword called template. In fact, the
literal meaning of a template is nothing but a framework. The general form of a
template function definition is:
template <class Ttype>
return type function name( arguments list)
{
// body of function
}
Here Ttype is a placeholder name for a data type used in the function. It is only used
for replacing the actual data with it self. The keyword class specifies the generic data
type in the template declaration.
Example:
* More no. of generic data types may be defined. The following is the syntax for it:
Syntax:
PRKP/KMK
C++ Material
Points to be noted:
Template function can be overloaded.
Template function can have any no. of generic data types.
Even normal primitive data types may be associated with
generic data types.
Template keyword is to be used before every generic function.
Template classes:
A template class is a generalized class that uses any generic data type i.e., not only
generic functions even we can have generic classes, which are known to be template
classes. Generic classes are useful when a class uses logic that can be generalized.
The general form of a generic function follows:
Template <class Ttype>
Class class name
{
..
..
};
Here Ttype is a place holder name which will be specified when a class is instantiated.
Once you have created a generic class, you create a specific instance (or object) of
that class using the following format:
Class name <type> object name;
PRKP/KMK
C++ Material
Sometimes when a program is executing, something occurs that is not quite normal.
For example, a user might enter an invalid filename; a file might contain corrupted
data; a network link could fail; the user may do illegal memory access. Circumstances
of this type are called exception conditions in any object-oriented languages & are
represented using objects.
Literally, a program may cause several errors during the process of execution. An error
can be a syntactical error or logical error. In other words, we say an error could be a
compile time error or runtime error. Such errors are supposed to be handled by the
user explicitly. A process of handling such errors is required.
Here a compile time error is an error occurred during compilation of program and a
runtime error occurs during execution. In C++, such runtime errors are known to be
Exceptions and the process of dealing such runtime errors or exceptions is said to be
exception handling. Clearly an exception is a runtime error.
PRKP/KMK
C++ Material
Dynamic Arrays
PRKP/KMK