402
402
❖ What is extraction and insertion operator → Also, specific namespace. Accessing Global Variables:
the operator whose use takes place to take the When you have a local variable with the same
input is called the extraction or get from operator name as a global variable, the scope resolution
(>>), while the operator that is used for displaying operator lets you access the global variable from
the output is called the insertion or put to within a function or block.
operator (<<). ❖ what are the access specifiers used in c++→ In
❖ Explain any two manipulation→ Manipulation is C++, there are three access specifiers: public -
the skillful handling, controlling or using of members are accessible from outside the class.
something or someone. Whether it's the sculpture private - members cannot be accessed (or viewed)
you made in art class or how you convinced your from outside the class. protected - members
friend to do your homework — both are cannot be accessed from outside the class,
considered manipulation. however, they can be accessed in inherited
❖ What is constructor→ C++ Constructors. classes.
Constructors are methods that are automatically ❖ what is tellg() and tellp() with syntax→ tellp()
executed every time you create an object. The tellg() This function is used with output streams
purpose of a constructor is to construct an object and returns the current “put” position of the
and assign values to the object's members. A pointer in the stream. The function is used with
constructor takes the same name as the class to input streams and returns the current “get”
which it belongs, and does not return any values. position of the pointer in the stream. Syntax:
❖ What is inline function→ The inline keyword pos_type tellp();
suggests that the compiler substitute the code ❖ Explain any two manipulators→ Some important
within the function definition in place of each call manipulators in <iomanip> are: setw (val): It is
to that function. In theory, using inline functions used to set the field width in output operations.
can make your program faster because they setfill (c): It is used to fill the character 'c' on
eliminate the overhead associated with function output stream. setprecision (val): It sets val as the
calls. new value for the precision of floating-point
❖ What is reference variable? what is major use → values.
A reference variable is one that refers to the ❖ What is destructor→ A destructor is a member
address of another variable. It represents the function that is invoked automatically when the
name of another variable, location, or value. Once object goes out of scope or is explicitly destroyed
you initialize the variable references, that variable by a call to delete or delete[] . A destructor has
will be referred to using the variable name or the same name as the class and is preceded by a
reference name tilde ( ~ ). For example, the destructor for class
❖ What is abstraction and encapsulation. → String is declared: ~String() .
Abstraction is the method of hiding the unwanted ❖ what are the visibility labels used in c++→ In C++,
information. Whereas encapsulation is a method there are three access specifiers: public -
to hide the data in a single entity or unit along members are accessible from outside the class.
with a method to protect information from private - members cannot be accessed (or viewed)
outside. 4. We can implement abstraction using from outside the class. protected - members
abstract class and interfaces. cannot be accessed from outside the class,
❖ What is compile time polymorphism → Compile- however, they can be accessed in inherited
time polymorphism, often referred to as static classes.
polymorphism or method overloading, is a ❖ What is default argument function→ A default
cornerstone of Java development. It occurs when argument is a value provided in a function
a class has multiple methods with the same name declaration that is automatically assigned by the
but differing parameter lists. The compiler compiler if the caller of the function doesn't
determines which method to call based on the provide a value for the argument when the
method signature during compile-time. function is called.
❖ What is default argument→ Functions A default ❖ write any two uses of scope resolution operator
argument is a value provided in a function in c++ → Scope resolution operator in C++ can be
declaration that is automatically assigned by the used for: Accessing a global variable when there is
compiler if the caller of the function doesn't a local variable with same name. Defining a
provide a value for the argument when the function outside a class. Accessing a class's static
function is called. variables. Referring to a class inside another class.
❖ What is the use of scope resolution operator→ In case of multiple Inheritance. Namespace.
The scope resolution operator allows you to
❖ what is static polymorphism→ When the ❖ State the need of virtual keywords→ The virtual
relationship between the definition of different keyword can be used when declaring overriding
functions and their function calls, is determined functions in a derived class, but it is unnecessary;
during the compile-time, it is known as compile- overrides of virtual functions are always virtual.
time polymorphism. This type of polymorphism is Virtual functions in a base class must be defined
also known as static or early binding unless they are declared using the pure-specifier.
polymorphism ❖ state the user defined data type in C++→ User
❖ explain structure of c++ program→ The structure Defined Data type in c++ is a type by which the
of a C++ program is made up of multiple source data can be represented. The type of data will
code files that cater to different components such inform the interpreter how the programmer will
as main function, member functions, class use the data. A data type can be pre-defined or
definition, headers/ standard headers, comments, user-defined. Examples of pre-defined data types
variables, data types, namespaces, input/ output are char, int, float, etc.
statements, etc. ❖ explain the use of scope resolution operator→
❖ Define early binding→ An object is early bound The scope resolution operator allows you to
when it is assigned to a variable declared to be of access variables, functions, or classes within a
a specific object type. Early bound objects allow specific namespace. Accessing Global Variables:
the compiler to allocate memory and perform When you have a local variable with the same
other optimizations before an application name as a global variable, the scope resolution
executes. operator lets you access the global variable from
❖ Define late binding→Late binding is also called within a function or block.
dynamic binding. Late binding occurs when we
make implicit or indirect function calls in our
program. An example of this is using function
pointers or virtual functions when using classes.
Here, the function call's memory reference is not
determined at compile-time, but rather at run-
time.
❖ Explain`get()` and put() functions→ The get()
function is used to retrieve or fetch data from a
specific location or variable. It allows you to access
the value stored in a variable or retrieve data from
a specific data structure. On the other hand, the
put() function is used to store or save data to a
specific location or variable. It allows you to assign
a value to a variable or store data in a specific data
structure.
❖ What is stream→ A C++ stream is a flow of data
into or out of a program, such as the data written
to cout or read from cin. For this class we are
currently interested in four different classes:
istream is a general purpose input stream. cin is
an example of an istream. ostream is a general
purpose output stream.
❖ Define friend function→ A friend function is a
function that isn't a member of a class but has
access to the class's private and protected
members. Friend functions aren't considered class
members; they're normal external functions that
are given special access privileges.
❖ explain the use of new operator state the
syntax→ The new operator is often used with a
default constructor to initialize an allocated
object. For example, if you want to allocate
memory for an integer variable named "number",
you can use the new operator as follows: int*
number = new int(20);
Chapter no 1 abstraction and are defined as a list of abstract
❖ Need of OOP → The use of structured attributes such as size, weight and cost and
programming made more complex programs, less functions to operate these attributes. Classes are
complex and easier to understand. But even with also known as ADTS.
structured programming, when a program reaches ❖ Encapsulation → The wrapping up of data and
a certain size, its complexity exceeds that which a functions into a single unit i.e. class is called as
programmer can manage. To deal with this Encapsulation. In other words, "the binding of
approach, a new way to program, was invented data and function into a single unit (class) is called
"Object Oriented Programming". This method of as encapsulation". The data is not accessible to
programming reduces the program complexity by the outside world and only those functions which
incorporate rating features like inheritance, are wrapped in the class can access it. These
encapsulation and polymorphism. OOP is a way of functions which are wrapped in the class provide
programming help the programmer to the interface between the objects data and the
comprehend and manage large and complex program. Encapsulation is a mechanism that keeps
programs. Object Oriented Programming models the data and code safe from external interference
real-world objects with software counterparts. It and misuse. This insulation of the data from direct
takes advantage of class relationships where access by the program is called data hiding which
objects of certain class have the same is also known as data encapsulation.
characteristics. Object Oriented Programming ❖ Inheritance → In inheritance process we can
(OOP) allows us to decompose a problem into a create new classes known as derived or child or
number of entities called objects. sub- class from the existing class known as base or
❖ Classes → A class is a group of objects with similar parent or super class. Inheritance is a process by
properties (attributes), common behaviour which object of one class (derived class) can
(operations), common relationship to other acquire the properties of objects of another class
objects and common semantics. Classes are user, (base class). .The concept of inheritance provides
defined datatypes and behave like the built-in the idea of reusability. This means that we can add
types of programming languages. The entire set of additional features to an existing class without
data and code of an object can be made user modifying it. This is made possible by deriving a
defined data type with the help of class. Once, a new class from the existing one. The new class will
class has been defined we can create any number have the combined features of both the classes.
of objects belonging to the same class. Person, ❖ Polymorphism→ In Polymorphism, "poly" means
company, process, window are some examples of many and "orphism" means form which forms
classes. many forms of one things. In other words,
❖ Objects → Objects are discrete, distinguishable "Polymorphism means one thing different or
entities. Objects are basic run-time entities A many forms" i.e. the ability to take more than one
paragraph in a document, a window on a form. Polymorphism plays an important role in
workstation, the white queen in a chess game is allowing objects having different internal
some examples of Objects. Objects can be structures to share the same external interfaces.
concrete such as a file in a file system or In OOP, polymorphism refers to the fact that a
conceptual such as scheduling policy in a single operation can have different behaviour in
multiprocessing operating system. Each object has different objects. In other words, different objects
its own inherent identity. react differently to the same message. • For
❖ Data Abstraction → Abstraction is the selective example, consider the operation of addition. For
examination of certain aspects of a problem. The two numbers, the addition should generate the
goal of abstraction is to isolate those aspects that sum. The operation of addition is expressed by a
are important for some purpose and suppress single operator +. You can use the expression x + y
those aspects that are unimportant. In other to denote the sum of x and y for many different
words, we can say that abstraction is the act of types of x and y integers, floating point numbers
representing essential features without including and complex numbers and even the concatenation
the background details or explanations. Data of two strings.
abstraction is the process of defining a data type, ❖ FEATURES OF OOP → OOP treats data as a critical
often called Abstract Data Type (ADT), together element in the program development and does
with the principle of data hiding. The definition of not allow it to flow freely around the system. It
an ADT involves specifying the internal ties data more closely to the functions that
representation of the ADTs data as well as the operate on it and protects it from accidental
functions to be used by others to manipulate the modification from outside functions. OOP allows
ADT. In OOP, classes use the concept of decomposition, (breaking into small modules) of a
problem into number of entities called objects and ❖ Identifiers→ An Identifier is any name of
then builds data and functions around these variables, functions, classes etc. given by the
objects. The organization of data and functions in programmers. • Identifiers are the fundamental
OOP is shown in Fig. 1.5. The data of an object can requirement of any language The identifier is a
be accessed only by the functions associated with sequence of characters taken from C++ character
that object. However, functions of one object can set. The rules for the formation of an identifier
access the functions of other objects. The are: 1. An identifier can consist of alphabets, digits
organization of data and function is payroll and/or underscores. 2. An identifier must not start
system. with a digit. It start with an alphabet or
❖ ADVANTAGES AND APPLICATIONS OF OOP → underscore(_). 3. C++ is case sensitive that is
1.Advantages of OOP :- 1. By the use of property uppercase and lowercase letters are considered
inheritance, we can eliminate redundant code and different from each other. 4. Identifier should not
extend the use of existing class. 2. We can map be a reserved word. 5. Identifier contains
objects in the problem domain to the object in the maximum 32 characters. Some valid identifiers
program. 3. We can modularise the program by are: result, x, _n1, acc_no, basicpay
dividing it into classes and objects. 4. The data ❖ Constants→ Constant refer to fixed values that
centered design approach enables to capture the program cannot alter or change. A constant is
more details of a model in implementable form. 5. an explicit number or character (such as 1, 0.5, or
In OOP, complex softwares can be easily managed. 'c') that does not change. As with variables, every
❖ Applications of OOP → 1. Real time systems, for constant has a type. A number which does not
example, oil exploration plant. 2. CAM/CAD change its value during execution of a program is
systems. 3. Object oriented databases. 4. Artificial known as a constant. A constant in C++ can be of
Intelligence (AI) and expert systems, for example, any of the basic data types, const qualifier can be
Disease knowledge base. 5. Hypertext, used to declare constant as shown below: const
hypermedia and expertext, for example, web page float pi = 3.1415; The above declaration means
designing. 6. Decision support and office that pi is a constant of float types having a value
automation systems. 7. Neural networks and 3.1415. Examples of valid constant declarations
Parallel programming. are: const int rate 50; const float pi = 3.1415;
❖ Features of C++ → 1. C++ provides overloading of const char ch = 'A';
functions and operators. 2. Exception handing in ❖ KEYWORDS→ The keyword implements specific
C++ is done by the try, catch and throw keywords. C++ language features. Keywords are explicitly
3. C++ provides static methods, friends, reserved identifiers and cannot be used as name
constructors and destructors for the class object. for the program variables. It is mandatory that all
4. It focuses on function template and class the keywords should be in lowercase letters. The
template for handling parameterized data types. keywords are reserved words, predefined by the
5. C++ gives the simplest and easiest way to language and user cannot change. Keywords are
handle encapsulation and data hiding with the used for specific purposes in C++ and compiler can
help of powerful keywords such as private, class, interprets these words.
public and protected and so on. 6. Inheritance ❖ User Defined Data Types → 1. Enumerations: An
concept in C++, one of the most powerful and enumeration is a user defined type consisting of a
important design concept is supported with single set of named constant called enumerators.
inheritance and multiple inheritances of base class Enumerations are a way of defining constants.
and derived class. 7. In C++, the polymorphism is Syntax: enum tag (member1, member2,
done through virtual functions, virtual base membern}; 2. Structure: 'C' structure is a
classes and virtual destructors give the late collection of data items of different data types.
binding of the compiler. Structure is a collection of variables under a single
Chapter no 2 name. Variables can be of any type such as, int,
❖ Tokens → The smallest individual units in a float, char etc. The main difference between
program are known as Tokens. A token is a group structure and array is that arrays are collections of
of characters that logically belong together. Token the same data type and structure is a collection of
is a sequence of characters from the character set variables under a single name. Syntax: struct
of C++, which is identified by the compiler. • C++ structure_Name { data_type member 1; data_type
tokens are keywords, literals, identifiers, member 2; }; 3. Union:A union is a user defined
operators, other symbols (separators). A C++ data or class type that, at any given time, contains
program or application is written using these only one object from its list of members,
tokens, white spaces and the syntax of the (although that object can be an array or a class
language. type). Syntax: union tag { member1; member2; :
member n; } objectname; 4. Class: Class is user ❖ Scope of Variables: • A scope is a region of the
define data type with data elements and program and broadly speaking there are three
functions. A class in C++ is an encapsulation of places where variables can be declared: (i) Inside a
data members and functions that manipulate the function or a block which is called local variables.
data. The class can also have some other (ii) In the definition of function parameters which
important members which are architecturally is called formal parameters. (iii) Outside of all
important. functions which is called global variables. All the
❖ Derived Data Types in C++ → 1. Arrays: • In C, variables that we intend to use in a program must
array size is exact same length of the string have been declared with its type specifier in an
constant. For example: char string [5] = 'abcde'; earlier point in the code, like we did in the
But in C++, the array size is one larger than the previous code at the beginning of the body of the
number of characters present in the string. Here, function main when we declared that a, b, and
"\0" is treated as a one character. 2. Functions: A result were of type int. A variable can be either of
function is a discrete block of statements that global or local scope. Variables that are declared
perform certain task. Once, a function has been inside a function or block are local variables. They
written to play a particular role it can be called can be used only by statements that are inside
upon repeatedly throughout the program. that function or block of code. Local variables are
Functions are either created by the user or not known to functions outside their own. A
supplied by the system. We can also write our global variable is a variable declared in the main
own function according to the requirements. A body of the source code, outside all functions,
function must be declared before its use, such a while a local variable is one declared within the
declaration is known as a function prototype it body of a function or a block.
ends with semicolon. Syntax: return_type ❖ Dynamic Initialization of variavies → When
function_name (parameters); declaring a regular local variable, its value is by
❖ VARIABLES→ A variable is a named location in default undetermined. But you may want a
memory that is used to hold a value that may be variable to store a concrete value at the same
modified by the program. Variable is the data moment that it is declared. In order to do that,
name that refers to the stored value. A variable you can initialize the variable. There are two ways
name is an identifier or a symbolic name assigned to do this in C++: (i) The first one, known as C-like
to memory location where data is stored. A initialization, is done by appending an equal sign
variable provides us with named storage that our followed by the value to which the variable will be
programs can manipulate. Each variable in C++ has initialized: type identifier = initial_value; For
a specific type, which determines the size and example, if we want to declare an int variable
layout of the variable's memory; the range of called a initialized with a value of O at the
values that can be stored within that memory; and moment in which it is declared, we could write: int
the set of operations that can be applied to the a = 0; (ii) The other way to initialize variables,
variable. The name of a variable can be composed known as constructor initialization, is done by
of letters, digits, and the underscore character. It enclosing the initial value between parentheses
must begin with either a letter or an underscore. [()]: type identifier (initial_value); For example: int
Upper and lowercase letters are distinct because a(0); Both ways of initializing variables are valid
C++ is case-sensitive. and equivalent in C++.
❖ Declaration of Variables → All variables must be ❖ Memory Management Operator For dynamic
declared before use, although certain declarations memory allocation, C++ provides new operator. In
can be made implicitly by content. A declaration C, we have malloc() and calloc() functions for
of variable specifies a type, and contains a list of dynamic allocation. For dynamic deallocation, C++
one or more variables of that type as follows: provides delete() operator, which is same as free()
Syntax: type variable_list; Here, type must be a function in C. 1. new operator: This operator is
valid C++ data type including char, w_char, int, used for allocation of memory. Syntax: ptr_var
float, double, bool or any user defined object etc., new datatype; For example, char +P; P= new
and variable_list may consist of one or more char[5]; int x; X= new int: 2. Delete operator: The
identifier names separated by commas. Some delete operator deallocates or frees the memory
valid declarations are shown here: int i, j, k; char c, allocated by new. Syntax: delete ptr_var; The
ch; float f, salary; double d; A variable declaration ptr_var is the pointer to a data object which is
with an initializer is always a definition. This created by new. For example, delete P; delete x; If
means that storage is allocated for the variable the array is allocated by new, then to free it we
and could be declared as follows: int i= 100; use the following syntax, delete [size] ptr_var; If
the size is not specified then entire array get may have more than one "return" statement in
deleted. For example, delete [] a; which case the function definition will end
❖ MANIPULATORS→ Manipulators are the execution as soon as the first "return" is reached.
functions used in input/output statement. All the 4. Function declarations are like variable
manipulators are defined in header field declaration, (functions specify which return type
iomanip.h. We can use chain of manipulator that the function will return). 5. A function has to be
is one or more manipulators in statement. 1. declared in a function declaration at the top of the
Setting of field width: setw() is used to define the program and before it can be called by main().
width of field necessary for the output for a ❖ Advantages of Functions: → 1. To reduce the size
variable. For example: setw(5); This function will of a program by calling them at different places in
reserve 5 digits for a number. setw(5); cout << the program. 2. Functions can be compiled
123; 2. Setting precision for float nos: We can separately. 3. Using functions, programs are easier
control number of digits to be displayed after to design, debug and maintain. 4. Reuse of the
decimal point for float numbers by using function is possible in multiple programs. 5. The
setprecision() function. setprecision(2); This functions provide interfaces to communicate with
function will display only two digits after a decimal object.
point. For example: setprecision(2); ❖ Function elements→ 1. A Function
cout<<3.14159; 3. Filling of unused positions: Declaration:→ A function declaration tells the
Filling of unused positions of the field can be done compiler about a function's name, return type and
by using setfill(). setfill('*'); Here, unused positions parameters. This is also referred as Function
will be filled by using sign. setw(5); setfill ('$'); Prototyping. A function is declared with a
cout << 123; 4. setbase(): It is used to show the prototype, which consists of return type, a
base of a number, for example: setbase(10); It function name and argument list. Syntax for
shows that all numbers are decimal numbers. 5. function declaration: return_type
Flags: C++ defines some format flags for standard function_name(argument1, argument2, ...) A
input and output, which can be manipulated with function can be declared either in the main
the flags(), setf() and unsetf() functions. The flags() function or in a class.
function either return the format flags for the 2.Function Definition: → The function definition
current stream or sets the flags for the current tells the compiler what task the function will be
stream to be f. Syntax: fmtflags flags(); fmtflags performed. Function definition consists of
flags (fmtflags f); 6. setf() and unsetf(): setf() function prototype and actual body of a function.
function can also be used with only one argument. It can be written anywhere in C++ program. The
Arguments will be as follows: 7. endl: This function definition consists of two parts: (i)
manipulator used in an output statement, causes Function header or Prototype, and (ii) Function
a linefeed to be inserted. It has the same effect as body.
using the new line character "\n". 3.A Function Call: → Function can be called
❖ FUNCTIONS → Functions are the basic building directly by simply writing the function name with
blocks of C++ and the place where all program arguments or indirectly in the expression if it
activity occurs. A function is a group of statements returns a value. We have to pass the actual
that together perform a task. A function is a parameters (arguments) to the functions. In the
subprogram that acts on the program data and function definition, the arguments are referenced.
often returns values. A program written with Therefore, calling a function is also known as
numerous functions is easier to maintain, update Function Reference. The arguments which we pass
and debug than one very long or large program. should match with the formal parameters which
Functions are used to implements large programs. are declared into the function. The data type and
In structured programming functions are used to the order should also be matched. For example,
break the larger programs into smaller ones; (i) add (x, y); (ii) display(); (iii) larger max(a,b); (iv)
which makes debugging of program easier. Each total add(10, 20)
function has its own name. When that name is 4.Returning from Function: → To return from
encountered in a program, the execution of the function we use return statement. return
program branches to the body of that function. statement pushes a value onto the return stack
❖ Features of Functions: → 1. The structure of a and control is return back to the calling function. If
function definition is look like the structure of return type is void, the function does not return
main(), with its own list of variables declaration any value. Syntax: return; OR return value;
and program statements. 2. A function can have a ❖ FUNCTION PROTOTYPING → One of the most
list of zero or more parameters inside its brackets, important features of C++ is the function
each of which has a separate type. 3. A function prototype. A function prototype is a declaration
that delivers the return type and the parameters method will form a cascade of member function
of a function. A function is declared with a calls. For example: cout << k << a; This statement
prototype. The function prototype tells the is a set of cascaded calls which returns reference
compiler the name of the function, the type of to the object cout.
data returned by the function, the number of ❖ INLINE FUNCTIONS → ++ inline function is
parameters the function expects to receive, the powerful concept that is commonly used with
types of the parameters and the order in which classes. If a function is inline, the compiler places
these parameters are expected. The compiler uses a copy of the code of that function at each point
function prototype to validate function calls. The where the function is called at compile time. Any
function prototype is also called the function change to an inline function could require all
declaration. Functions are declared similar to clients of the function to be recompiled because
variables, but they enclose their arguments in compiler would need to replace all the code once
parenthesis [()]. The function prototype describes again otherwise it will continue with old
the function interface to the compiler by giving functionality. The advantage of using function is to
details like the numbers and type of arguments save the memory space. Consider a situation
and the type of return values. Syntax: return_type where a small function is called number of times
function_name (list of parameters); For examples: calling a function requires certain overheads such
1. int add(x, y); 2. int max(); as:• Passing to the function, • Passing the values
❖ INTERACTION BETWEEN FUNCTIONS → The or push arguments into the stack, o Save the
function [main() and other] interacts with each registers, • Return back to calling function.
other through parameters. We pass the parameter ❖ DEFAULT ARGUMENTS→ C++ allows to define an
to the function for the communication of calling argument whose value will be automatically used
function and the called function. There are two by the compiler, if it is not provided during the
types of parameters actual parameters function call, this argument is called as default
❖ Call by Reference → When a function is called the arguments. When declaring a function, we can
address of the actual parameters are copied on to specify a default value for each parameter in C++.
the formal parameters, though they may be In C++, the concept of default argument is used.
referred by different variable names. This content We know that when a function call is given the
of the variables that are altered within the number of arguments of function definition and
function block are return to the calling function function call should be same; otherwise, error will
program. As the formal and the actual arguments be displayed. But in C++ we can specify a default
are referencing the same memory location or value for each parameter when function is
address. This is known as call by reference, when declared. The parameters which does not have
we use this concept is functions. Called function any default arguments are placed first whereas
makes the alias of the actual variable which is those with default values are placed later.
passed. 0 Actual variables reflect the changes Therefore, we can call the same function with
made on the alias of actual variables. Number of fewer arguments than the defined one in
values can be modified together. • For call by prototype. The default values are specified when
reference concept C++ uses a reference operator the function is declared. Compiler takes care of all
(&). • & operator allows true call by reference the default arguments and values through the
functions, eliminating the need to dereference prototype. In a short way, this means that when a
arguments passed to the function. • The & function uses default arguments, the actual
operator is placed before the variable name of function call has the option to specify new values
argument in the parameter list of the function. or use the default values. • The default arguments
Then the function can be called without passing are generally used in the situation where some
the address and without dereferencing within the arguments are having the same value.
function
❖ Call by Value → In call by value , we called Chapter no 3
function makes the copy of actual variable passed. ❖ ACCESS SPECIFIERS → Access specifiers are used
The actual variables do not reflect the changes to restrict (limits) the accessibility of class
made on the copies of actual variables In call by members. Access specifiers define how the
value only one value can be returned. members of the class can be accessed. Each
❖ Return by Reference → The function can also member of a class is associated with access
return the reference of variable. This reference specifiers. The access specifiers of a member
variable is actually an alias for the referred controls its accessibility as well as determines the
variable. The method of returning reference is part of the program that can directly access the
used generally in operator overloading. This member of the class. In the class declaration
syntax, the keywords private, public and protected memory space is allocated for the data members
are known as access specifiers (also known as of that object, because data members of each
visibility modes). An access specifier specifies the object have different values. For example,
access rules for members following it until the end consider the following class: class sample { int x, y;
of the class or until another access specifier is public: void initialize () { X = 20; y = 30; } };
encountered. When a member is declared private, ❖ STATIC DATA MEMBERS AND STATIC MEMBER
it can be accessed only inside the class while a FUNCTIONS → Both that is function and data
public member is accessible both inside and member of a class can be made static. Static
outside the class. Protected members are variables defined within a function only have a
accessible both inside the class in which they are functions scope so that they may not be accessed
declared as well as inside the derived classes of by any other function. C++ also allows us to use
the same class. static members. The members declared inside the
❖ Defining Data Member→ All the variables inside class but persisting from their declaration to the
the class are called data members. These variables end of program are called static members. The
are of any basic data type, derive data type or static members are both data members as well as
user-defined data type or objects of other class. member functions.
Any function declare inside a class is called a ❖ Static Data Members → In C++, a data member of
member function of that class. Only the member a class can be qualified as static. Static variables
functions can have access to the private data are normally used to maintain values common to
members and private functions. the entire class. A static data member is useful
❖ Defining Member Functions inside and Outside when all objects of the same class must share a
Class Definition → Member functions of a class common item of information. Static data
are defined in following two ways: 1. Inside the members of a class are used to share information
class definition, and 2. Outside the class. In both among the objects of a class. Syntax for declaring
ways, only syntax of definition of member a static data member: Static datatype
function changes but body of function (code) is data_member_name;
remain same. 1. Inside the Class Definition: ❖ Static Member Functions → Member functions
Functions which are defined inside the class are may also be declared as static.A static function can
similar to normal functions and they are handling have access to only other static members declared
automatically and inline functions. Normally, in the sam class. • But there are some restrictions
functions which are small are defined inside the on them. 1. They may only access other static
class. 2. Outside the Class: • The functions are members of the same class directly. 2. They do not
define after the class declaration, however the have a 'this' pointer. 3. There cannot be a static
prototype of function should be appear inside the and a non-static version of the same function. It
class i.e. declaration only (not definition). Since, can be called using class name as, class_name::
the function has defined outside the class, there function_name Syntax of declaring a static
should be some mechanism to know the identity member function: static return_type
of function to which class they belong we have to function_name (arguments);
use scope resolution operator (::) to identify the ❖ ARRAY OF OBJECTS → The array of variables of
function belongs to which class. We can also have class data type is called Array of Objects. An array
a function with the same name and same of objects is an array of a class type is also known
argument list in different classes, since the scope as an array of objects. An array of objects is
resolution operator will resolve the scope of the declared in the same way as an array of any built-
function. Syntax: return type class_name:: in data type. The syntax for declaring an array of
function_name (argument list if any) { //body of objects is as follows: class_name
function } array_name[size]; For example: If class is student
❖ MEMORY ALLOCATION FOR OBJECTS → A class is and we want to define that there are 100 students
a template from which instances i.e. objects can in class. So we define array of student with 100
be created. All the objects created from a class objects and here student is object of class type.
look like and exhibit similar behaviour. When a The size of an object is defined from class
class is declared no storage is allocated for data declaration. So the storage required for array of
members. Memory is allocated for objects when object is defined by complex from class
they are declared. The member functions are declaration.
created and allocated space in memory only once ❖ FRIEND FUNCTION → The functions that are
when they are defined in the class. All the objects declared with the keyword friend are known as
of that class share the same member functions. friend functions. To make an outside function
But when an object is created, then separate friendly to a class, we have to simply declare this
function as a friend of the class. A friend function so this method is known as explicit call of
is a function that is not a member of a class but constructor. For example: Bank b1; b1 Bank(12);
has access to the .class's private and protected 2. Implicit Call: It will not show name of
members. Friend functions are not considered constructor in the program. Values of the variables
class members; they are normal external functions get constructed at the time of objects declaration.
that are given special access privileges. Friends are For example: Bank b1(50):
not in the class's scope, and they are not called ❖ TYPES OF CONSTRUCTOR → 1) Default
using the member selection operators (.and->) Constructor :-The constructor which does not
unless they are members of another class. For accept any argument is called default constructor.
example: class xyz { public: friend void abc (void); In default constructor the argument list is void.
}; The function declaration in above example Default constructor is also called as empty
should be preceded by the keyword friend. constructor because of it has no arguments. A
❖ Characteristics of friend function→ 1) it is not in default constructor is used to initialize all the
the scope of the class to which it has been objects of a class with the same values. There can
declared as friend 2) since it is not in the scope of be only one default constructor in a class. The
the class it cannot be called using the object of default constructor is defined as, "a constructor
that class. 3) it can be invoked like a normal which does not contain any
function without the help of any object. 4) unlike parameters/arguments". A default constructor can
member function it cannot access the member be called directly when an object of the class is
names directly and dot membership operator with created. If no constructor are created, compiler
each member name.5) usually it has the object as will create a default constructor by itself. Syntax:
arguments. class class_name(); { public: class_name() { }
//body of constructor }; For example: student::
Chapter no 4 student() { rollno=0; marks=0.0; } 2)
❖ CONSTRUCTORS→ A constructor is a special Parameterized Constructor:- Sometimes, it is
member function which is used to allocate essential to initialize the various data elements of
memory space and values to the data members of different objects with different values when they
that object. A constructor makes the object are created. This is achieved by passing arguments
functional by converting an object with the to the constructor function when the objects are
unused (uninitialized) memory into a usable created. The constructors which accept any
(initialized) object. Whenever, an object is created, number of formal parameters and that formal
the constructor will be executed automatically and parameters are used to initialize the object are
initialization of data member takes place. It is called parameterized constructors. A
called constructor because it constructs the value parameterized constructor is defined as, "a
of data member of the class. A constructor is a constructor which accepts one or more
special as it has the same name as that of the arguments/parameters at the time of declaration
class and is automatically invoked whenever an of objects and initializes the data members of the
object of the class is created. When we declare an objects with these parameters/arguments". The
object in function main(): 1. Memory will be syntax to define a parametrized constructor is
allocated. 2. Constructors will be called by the given below: class class_name(); { public:
compiler automatically.. 3. Initialization of class_name() (param1, param2, paramN) { }
variables (data member) takes place. • It is not //body of the constructor }; For example:
possible for us to initialize the data member in the student:: student(int r) { } rollno=r; 3) Copy
class declaration itself. Because at that point Constructor:- A copy constructor takes a reference
memory is not allocated for the object. to an object of the same class as itself as an
❖ Constructor Call → For calling of a defined argument. A constructor that initializes an object
constructor there are two ways namely, explicit using values of another object passed to it as
call, and implicit call. If the name of the parameter, is called copy constructor. In C++, a
constructor is not used in the object declaration, new object of a class can also be initialized with an
the call is known as an implicit call to the exiting object of the same class. For this, the
constructor. While, if the name of the constructor compiler of C++ calls the copy constructor. Copy
is used in the object declaration, the call is known constructor creates the copy of the passed object.
as an explicit call to the constructor. 1. Explicit A copy constructor is defined as, "a constructor
Call: In this method name of constructor with the which accepts an already existing object through
values of variables in the bracket are coming in reference to copy the data member values".
the picture, to construct the values. Name of Syntax to define a copy constructor is as follows:
constructor is explicitly mentioned in the program, class class_name { public: class_name(class_name
& object_name) { } // body of the constructor}; 4) ❖ Characteristics of constructor→ 1 The name of
DYNAMIC CONSTRUCTOR:- • Allocation of the constructor is the same as its class name. 2
memory to objects at the time of their Constructors do not return values; hence they do
construction is known as dynamic construction of not have a return type. 3. A constructor gets
objects. • The memory is allocated with the help called automatically when we create the object of
of the new operator. The constructor can also be the class 4. Constructors can be overloaded 5. A
used to allocate memory while creating objects. constructor can not be declared virtual. 6. A
This will enable the system to allocate the right constructor cannot be inherited.
amount of memory for each object when the ❖ Characteristics of destructor → 1. Destructors are
objects are not of the same size, thus resulting in not equipped with parameters or a return form.
saving of the memory. The constructor can also be .Destructors are invoked automatically and cannot
used to allocate memory while creating objects. be invoked manually from a program.
For this purpose new and delete keywords are 3.Destructors cannot be overloaded. 4. Which can
allowed in the body of constructor. A dynamic be a virtual destructor. 5. The Destructor will
constructor is defined as, "a constructor in which execute the reverse order of object creation.
the memory for data members is allocated
dynamically". Dynamic constructors are used to Chapter no 5
allocate memory to objects at run-time rather i.e.,
allocating memory to objects when they are ❖ Inheritance → Inheritance is a form of software
created reusability in which new classes are created fre
❖ CONSTRUCTORS WITH DEFAULT ARGUMENTS → existing classes by absorbing their attributes and
In C++, it is possible to define constructors with behavior and overriding these with capabilities
default argument. For example: complexTest (float the new classes requires. Inheritance is the
real, float imag = 0); In above statement default process by which one object can acquire the
value of the argument imag = 0, then the properties of another object. Inheritance is the
statement. complexTest CT(4.0) assigns the value process of creating new classes from an existing
4.0 to the real variable and 0.0 to imag (by class. The existing class is known as base class and
default). The default argument is checked for its the newly created class is called as: derived class.
data type at the time of its declaration and gets The derived class inherits all capabilities of the
evaluated at the time of call. These arguments are base class. A derived class is more specific than its
evaluated from right to left. Whenever, a call is base class and represents a smaller group of
made to a function without specifying an objects. For example, a Red Delicious apple is part
argument, the program will automatically assign of the classification apple, which in turn is part of
values to the parameter from the default function the fruit class.
prototype declaration. Default arguments are ❖ Advantages of Inheritance : → - It Allows the
useful when user wants same value for the code to be reused as many times as needed. - The
argument. The diagrammatic representation of base class once defined and once it is compiled, it
default argument. Default arguments facilitate need not be reworked. - Saves time and effort as
easy development and maintenance of program. the main code need not be written again.
❖ DESTRUCTOR→ Destructor is a special member ❖ TYPES OF INHERITANCE→ 1) Single Inheritance :-
function which is called automatically whenever a When one base class is derived by one child class,
class object is destroyed. The primary usage of the then it is known as single inheritance. The existing
destructor function is to release space on the base class is known as direct base class whereas,
heap. Whenever, a particular object goes out of they newly created class is called as singly derived
the scope of its existence, destructors will be class. Example: Suppose a college want to store
called automatically and it takes out the allocated information of undergraduate (UG) and
memory. Destructors are invoked by the compiler postgraduate students (PG). Both are having
implicitly when the termination of program takes registration no., name, and address. Each
place. But it is always better to invoke the postgraduate student also have additional
destructor explicitly by writing it into the program attributes along with above attributes are
code. A destructor is also special as it has same placement company name. 2) Multilevel
name as that of the class of which it is a member Inheritance P:- When a base class is derived by a
but with a - (tilde) sign prefixed to its name and child class which further derived by another child
which is used to destroy the objects that have class, then it is known as Multilevel Inheritance.
been created by a constructor. It gets invoked The class which provides link between two classes
when an object's scope is over. is known as intermediate base class. 3) Multiple
Inheritance :- When more than one base classes
are inherited by a derived class, then such type of itself. For example, function overloading and
inheritance is called as multiple inheritance. 4) operator overloading. 2. Run-time polymorphism:
Hierarchical Inheritance :- When one base class is This is also called as dynamic binding or late
inherited by more than one derived classes, it is binding. Sometimes, a situation occurs where
known as hierarchical inheritance. In this, many function name and prototype is same in both the
programming problems can be cast into a base class and in the derived class. Compiler does
hierarchy where certain features of one level are not know what to do, which function to call. In
shared by many other below that level. 5) Hybrid this class appropriate member function is selected
Inheritance :- Sometimes, we may require to to run time. For example, virtual function.
combine two or more types of inheritance to ❖ COMPILE TIME POLYMORPHISM →
design a program; the result is known as Hybrid Polymorphism, in C++, is implemented through
Inheritance. overloaded functions and overloaded operators.
❖ VIRTUAL BASE CLASS → Consider a situation Function Overloading is also referred to as
where multilevel, multiple and hierarchical all the functional polymorphism. The same function can
three kinds of inheritance are involved. the base perform a wide variety of tasks. The same
class is inherited by both Derived1 and Derived2. function can handle different data types. When
Derived3 directly inherits both Derived1 and many functions with the same name but different
Derived2. All the public and protected members of argument lists are defined, then the function to be
Base are inherited into Derived3 twice through invoked corresponding to a function call is known
both Derived1 and Derived2. Therefore, Derived3 during compile time. When the source code is
would have duplicate sets of members inherited. compiled, the functions to be invoked are bound
This causes ambiguity when a member of Base is to the compiler during compile time, as to invoke
used by Derived3. which function depending upon the type and
❖ CONSTRUCTORS IN DERIVED CLASS → There are number of arguments. Such a phenomenon is
two major questions that arise relative to referred to early binding, static linking or compile
constructors and destructors when inheritance is time polymorphism.
involved. First, when are base class and derived ❖ Function Overloading→ C++ provides the facility
class constructor and destructor functions called? of function overloading in which we can define
Second, how can parameters be passed to base multiple functions with the same name but the
class constructor functions? As long as no base types of argument are different. For example, we
class constructor takes any argument, the derived can have a function add with two floating point
class need not have a constructor function. If a numbers as argument, another function add with
base class contains a constructor with one or 3 integers, one add function with 4 doubles and so
more arguments then it is mandatory for a on. But function name is similar. This is called as
derived class to have a constructor pass the Function Overloading. An overlcaded function, is a
arguments to the base class constructor. 1. Order function with the same name as another function,
of calling constructors: When both the derived but with different parameter types.
and base classes contain constructors, then base ❖ Operator Overloading→ Operator overloading is
constructor is executed first and then the closely related to function overloading. In C++,
constructor is the derived class is executed. In you can overload most operators so that they
case of multiple and multilevel inheritance, base perform special operations relative to classes that
classes are constructed in the order in which they you create. Actually, C++ tries to make user
appear in the declaration of derived class. When a defined data types behave in much the same way
derived object is destroyed its destructor is called as built-in types. For instance, C++ permits us to
first and then base class destructor. Constructor's add two variables of user defined types with the
functions are executed in their order of derivation. same syntax that is applied to the basic types. This
Destructor functions are executed in reverse order means that C++ has the ability to provide the
of derivation. operators with a special meaning for a data type.
❖ Polymorphism→ Polymorphism means "one The mechanism of giving such special meanings to
name, many forms". Polymorphism is the process an operator is known as 'Operator Overloading'.
of defining a number of objects at different classes Operators can be overloaded by creating 'operator
into group and call the method to carry out the functions'.
operation of the objects using different function ❖ Rules for Overloading Operators→ 1. Only
calls. There are two types of polymorphism: 1. existing operators can be overloaded. New
Compile time polymorphism: This is also called as operators cannot be created. 2. The overloaded
early or static binding. Selection of an appropriate operator must have at least one operand that is of
function for a particular call at the compile time user defined type. 3. We cannot change the basic
meaning of an operator. That is we cannot ❖ RUNTIME POLYMORPHISM→ Run-time
redefine the plus (+) operator to subtract one polymorphism is also called as dynamic binding or
value from the other. 4. Overloaded operators late binding. Sometimes, a situation occurs where
follow the syntax rules of the original operators function name and prototype is same in both the
that cannot be overridden. 5. There are some base class and in the derived class. Compiler does
operators that cannot be overloaded such as .*,:: not know what to do, which function to call. In
etc. 6. Unary operators, overloaded by means of a this class appropriate member function is selected
member function, take no explicit arguments and to run time. For example, virtual function. To
return no explicit values. But those overloaded by achieve run-time polymorphism C++ supports a
means of a friend function take one reference mechanism known as virtual functions. Dynamic
argument. 7. Binary operators overloaded through binding uses the concept of pointers, i.e. it
a member function take one explicit argument requires to use of pointer to object.
and those which are overloaded through a friend ❖ Virtual Functions → Virtual function is a member
function take two explicit arguments. 8.. When function that is declared within a base class and
using binary operators overloaded through a redefined by a derived class. A virtual function is
member function, the left- hand operand must be declared by preceding the function declaration in
an object of the relevant class. 9. Binary the base class with the keyword virtual. Example:
arithmetic operators such as+,,,/ must explicitly virtual void show(); //show function is virtual.
return a value. They must not attempt to change When virtual functions access normally, it behaves
their own arguments. 10. We cannot use friend just like any other type of class member function.
functions to overload certain operators, which are However, virtual function is used to support
listed below. However, member functions can be runtime polymorphism when it is accessed via a
used to overload them. pointer. A base class pointer can be used to point
❖ Operator Overloading Unary and Binary → 1. to an object of any class derived from that base.
Overloading Unary Operator: The operators can When different objects are pointed to different
be overloaded using two different functions i.e. versions of the virtual functions are executed.
through member functions and friend functions. A Following program shows the usage of it.
unary operator overloaded using a member ❖ Pure Virtual Functions→Most of the times, the
function takes no argument, whereas an virtual function inside the base class is rarely used
overloaded unary operator declared as friend for performing any task. It only serves as a
function takes one argument. First we will placeholder. Such a functions are called do- noting
consider the unary minus (-) operator. A minus functions; which are pure virtual functions. A pure
operator, when used as a unary, takes just one virtual function is a virtual function that has no
operand. We know that this operator changes the definition within the base class. Syntax: virtual
sign of an operand when applied to a basic data <return_type> <function_name> <arg_list>= 0;
item. We will see here how to overload this When a virtual function is made pure, any derived
operator so that it can be applied to an object in class must provide its own definition. If the
much the same way as is applied to an int or float derived class fails to override the pure virtual
variable. The unary minus when applied to an function, compile time error will occur. A class
object should change the sign of each of its data containing such a pure virtual function is called an
items. 2) Overloading Binary Operator: Binary Abstract Class. We can define pure virtual function
operators are operator which require two as "The functions which are only declared but not
operands to perform operation. We have just seen defined in the base class are called as pure virtual
how to overload a unary operator. The same function".
mechanism can be used to overload a binary ❖ Properties of Pure Virtual Functions: → A pure
operator. To add two numbers generally we use virtual function has no implementation in the base
statement like: Csum (A, B) // functional notation• class, hence a class with pure virtual function
The functional notation can be replaced by a cannot be instantiated. A pure virtual member
natural looking expression, // arithmetic notation function can be invoked by its derived class. It is
C=A+B By overloading the + operator using an just placeholder for derived class. The derived
operator + () function. The binary operators class is supposed to fill this empty function.
overloaded through member function take one ❖ this' Pointer → Every object in C++ has access to
argument which is formal. The binary overloaded its own address through an important pointer
operator function takes the first object as an called 'this' pointer. In other words, "The member
implicit operand and the second operand must be functions of each and every object have access to
passed explicitly. a pointer named 'this', which points to the object
itself. The 'this' pointer is an implicit parameter to
all member functions. Therefore, inside a member types of get() functions to fetch a character
function, this may be used to refer to the invoking including the blank space, tab and the newline
object. Friend functions do not have a 'this' character. get(char *) get (void) get(char *) - The
pointer, because friends are not members of a get (char *) version assigns the input character to
class. Only member functions have a 'this' pointer. its argument. Example: char c; cin.get(c); // get a
'this' is a pointer that points to the object for character from keyboard and assign it to e while(c
which the function was called. 'this' pointer is != '\n') { cout<c; cin.get(c); // display the character
predefined pointer variable within every class. on screen // get another character } get (void) :-
'this' pointer is a pointer pointing to the current The get (void) version returns the input character.
object of specified class. "this" is a keyword in Example: char c; e-cin.get(); //cin.get(c); replaced
C++. Syntax: class_name * this; The value returned by the function get() is
❖ Pointer to Objects→ Now we are aware of assigned to the variable c. > put()- The function
accessing class members with the help of pointers. put(), a member of ostream class, can be used to
We can also make a pointer to point to an object output a line of text, character by character. 2)
created by a class similar to that of normal getline() and write() Functions :- We can read and
variables. Now lets declare a object and a pointer display a line of text more efficiently using the
variable of class sample, sample s; sample * ptr; line- oriented input/output functions getline() and
Now initialize the pointer ptr with the address of write(). ➤ getline() :- The getline() function reads
object s. ptr = &s; With the help of pointer we can a whole line of text that ends with a newline
access the class members in the same manner as character This function can be invoked by using
with object. Only, the difference is, while the object cin as follows: ➤ write()- Write()
accessing class member with the help of objects function displays an entire line and has the
the () dot operator is used where as at a time of following form: cout.write(line,size) First argument
pointer (→) arrow operator would be used. The line represents the name of the string to be
following two statements are equivalent. 1. s.get() displayed and the second argument size indicates
2. ptr get(); the number of characters to display.
❖ Unformatted I/O Operators → • The <<, >>
Chapter no 7 operators for shifting are overloaded in ostream
❖ C++ STREAMS → Stream - A stream is a sequence and istream class respectively. The general format
of bytes. It acts either as a source from which the for reading the data from the keyboard is: cin >>
input data can be obtained or as a destination to var1, >> var2 >> >> varn; Where, var1 and var2 are
which the output data can be sent. Input Stream - any, C++ predefined variables. This statement in
The source stream that provides data to the the program will make the compiler to wait for the
program is called the input stream. Output input data from the keyboard. The operator >>
Stream - The destination stream that receives reads the data character by character and assigns
output from the program is called the output it to the indicated location. The reading for the
stream. The data in the input stream can come variable will be terminated at the encounter of a
from the keyboard or any other storage device. white space or a character that does not match
Similarly, the data in the output stream can go to with destination type. The general form for
the screen or any other storage device. As displaying data on screen is:cout << data1 <<
mentioned earlier, a stream acts as an interface data2<<<<datan;
between the program and the input/output ❖ Unformatted I/O functions → 1.get():- the class
device. Therefore, a C++ program handles data istream defines a member function get() which is
(input or output) independent of the devices used to handle single character input/output
used. operations at a time . syntax:- get(char*),get(void)
❖ C++ STREAM CLASSES→ The C++ I/O system 2. Put():- the class ostream defines the member
contains a hierarchy of classes that are used to function put() which is used to output a line of
define various streams to deal with both the text on a screen character by character syntax:-
console and disk files. These classes are called cout.put(char); 3.getline():- the getline() function
stream classes. Figure shows the hierarchy of the reads a whole line of text that ends with a newline
stream classes used for input and output character syntax :- cin.getline(line,size); 4.write():-
operations with the console unit. write function is used to write a set of characters
❖ UNFORMATED I/O OPERATION → 1) get() and into the fie syntax:- cout.write(line ,size); 5.
put() Functions - The classes istream and ostream read(): The read function is used to read a set of
define two member functions get() and put() characters form the file. • Syntax:
respectively to handle the single character fileObject_name.read((char *) and variable_name;
input/output operations. >get()- There are two size of (variable_name)); 6. peek(): It reads
particular char from file. 7. putback(): It places the i<len; i++) file.put(string [i]); file.seekg(0); char ch;
control back to previous character obtained by while(file) { file.get(ch); cout << ch; } return 0; }
get(). 8. ignore(): It skips number of characters ❖ Templates are a feature of the C++ programming
while reading or writing in a file. .9. sizeof(): It language that allows functions and classes to
gives size of memory required for storage. operate with generic types. This allows a function
or class to work on many different data types
Chapter no 8 without being rewritten for each one. Templates
❖ Working with files→ Many real-life problems are a way of making your classes more abstract by
handle large volumes of data and, in such letting you define the behavior of the class
situations, we need to use some devices such as without actually knowing what datatype will be
floppy disk or hard disk to store the data. The data handled by the operations of the class. Templates
is stored in these devices using the concept of can be used in conjunction with abstract
files. File:- A file is a collection of related data datatypes in order to allow them to handle any
stored in a particular area on the disk, Programs type of data. For example, you could make a
can be designed to perform the read and write templated stack class that can handle a stack of
operations on these files. A program typically any datatype, rather than having to create a stack
involves either or both of the following kinds of class for every different datatype for which you
data communication: 1. Data transfer between the want the stack to function.
console unit and the program. 2. Data transfer Chapter no 9
between the program and a disk file. This is
illustrated in Fig. below ❖ Function template → The template declared for
❖ OPENING AND CLOSING A FILE→ A file can be function is Called as function template.
opened in two ways: 1.Opening Files Using Advantages:- 1) The same function takes different
Constructor - We know that a constructor is used types of arguments. 2) It avoids Unnecessary
to initialize an object while it is being created. repetition of function for different data types. 3)
Here, a filename is used to initialize the file stream In function template full data type Checking is
object. This involves the following steps: 1. Create carried out. 4 )The template function does not
a file stream object to manage the stream using specify actual data type that is generic used for for
the appropriate class That is to say, the class or parameterized function
ofstream is used to create the output stream and ❖ Class Template→ The template which is design for
the class ifstream to create the input stream. 2. Classes are called Class template Advantages:- 1 )
Initialize the file object with the desired Class template handle different types of data
filename.2.using member function open() of the types.2) Avoid the testing & debugging time. 3)
class :- the function open() can be used to open Template reduces the effort on codeing for
multiple files that use the stream object different data types.
❖ Functions for Manipulation of File Pointers→ All ❖ Exception Handling → C++ exception handling
the actions on the file pointers as shown in Fig. mechanism uses three keywords: try, catch and
take place automatically by default. How do we throw. try block contains program statements that
then move a file pointer to any other desired we want to monitor for exceptions. When an
position inside the file? This is possible only if we exception is detected it is thrown using a throw
can take control of the movement of the file statement in the try block. The exception is
pointers ourselves. The file stream classes support caught using catch. Typically, a catch(...) block is
the following functions to manage such situations: used to log errors and perform special cleanup
seekp() Moves put pointer(output) to a specified before program execution is stopped. Any
location. tellp() Gives the current position of the exception must be caught by a catch statement
put pointer. seekg() - Moves get pointer (input) to that immediately follows the try statement that
a specified location. tellg() Gives the current throws the exception.
position of the get pointer. ❖ Multiple Catch Statements → We can have more
❖ Put() and get() Functions → The function put() than one catch associated with a try. When the
writes a single character to the associated stream. exception is thrown, the exception handlers are
Similarly, the function get() reads a single searched in order for an appropriate match. When
character from the associated stream. Program the match is found that catch block is executed.
below illustrates how these functions work on a When no match is found, the program is
file. #include <fstream.h> #include <string.h> int terminated
main() { char string[80]; cout<<<< n Enter a string ❖ Catch all Exceptions → Sometimes, we want an
\n"; cin>>string; int len = strlen(string); fstream exception handler to catch all exceptions instead
file; file.open("TEXT", ios::in | ios::out); for(int i=0; of just a certain type.