OOP Lab Manual
OOP Lab Manual
1. Syllabus
2. List of Experiments
6 Implement friend function to access private data of a class and usage of this pointer.
Write programs to understand the usage of constant data member and member function, static data
7 member and member function in a class.
8 Implement different types of inheritance, function overriding and virtual function
9 Implement Operator overloading concepts.
10 Write programs to understand function template and class template.
11 Write programs to understand exception handling techniques.
12 Write programs to understand file handling techniques.
List of Experiments
Viva Question
Write programs to understand function template and class template.
1. WAP to create a template function to identify larger among two values(int, float,
char)
Exp:- 10
2. WAP to create a class template with a class swapper to swap two values.
Viva Question
Write programs to understand exception handling techniques.
1. WAP to divide two numbers using try catch block.
Exp:- 11 2. WAP to implement throw keyword
Viva question
Write programs to understand file handling techniques.
Exp:-12
Viva question
DO’S AND DONT’S
DO’S
1. Student should get the record of previous experiment checked before starting the new experiment.
3. Before starting the experiment, get circuit diagram checked by the teacher.
4. Before switching on the power supply, get the circuit connections checked.
9. Students should get the experiment allotted for next turn, before leaving the lab.
DONT’S
1. Do not touch or attempt to touch the mains power supply Wire with bare hands.
The previous experiment should have been written in the practical file, without which the students will not
be allowed to enter the lab.
The students should have written the experiment in the observation copy that they are supposed to perform
in the lab.
The experiment written in the observation copy should have aim, apparatus required, circuit
diagram/algorithm, blank observation table (if any), formula (if any), programmed (if any), model graph (if
any) and space for result.
Necessary equipments/apparatus should be taken only from the lab assistant by making an issuing slip,
which would contain name of the experiment, names of batch members and apparatus or components
required.
Never switch on the power supply before getting the permission from the faculty.
The equipments/components should be returned back to the lab assistant in good condition after the
completion of the experiment.
The students should get the signature from the faculty in the observation copy.
They should also check whether their file is checked and counter signed in the index.
PROGRAM EDUCATION OBJECTIVES AND OUTCOMES
Graduates will have solid foundation in engineering field required to solve computing
PEO-2 problems using various programming languages and software/tools, and students can
solve problems through logical and analytical thinking.
To develop the professional and ethical attitude, effective communication skills and
PEO-4 lateral learning for multidisciplinary approach, and an ability to relate engineering
issues to broader social context.
CO-5 2 2 - - 2 - - - - 2 - - 2 2
Sr.
Beyond Syllabus topic Source
sNo.
File Handling in C++ How to program C++,Dietel,Pearson
1
Text/
S.N. Author Name Book Title Publisher
Reference
How to program
1 Dietel Pearson Reference
C++
Object Oriented
3 Robert Lafore Programming in Pearson Reference
C++
Experiment: 1
C++ is used by many programmers of different types and coming from different fields. C++ is mostly used to write
device driver programs, system software, and applications that depend on direct hardware manipulation under real-
time constraints. It is also used to teach the basics of object-oriented features because it is simple and is also used in
the fields of research. Also, many primary user interfaces and system files of Windows and Macintosh are written
using C++. So, C++ is really a popular, strong and frequently used programming language of this modern
programming era.
1. Abstraction
2. Encapsulation
3. Inheritance
4. Polymorphism
C++ Data Types
All variables use data-type during declaration to restrict the type of data to be stored. Therefore, we can say that
data types are used to tell the variables the type of data it can store.
Whenever a variable is defined in C++, the compiler allocates some memory for that variable based on the data-
type with which it is declared. Every data type requires different amount of memory.
Data types in C++ is mainly divided into two types:
1. Primitive Data Types: These data types are built-in or predefined data types and can be used directly by
the user to declare variables. example: int, char , float, bool etc. Primitive data types available in C++ are:
Integer
Character
Boolean
Floating Point
Double Floating Point
Valueless or Void
Wide Character
2. Abstract or user defined data type: These data types are defined by user itself. Like, defining a class in
C++ or a structure.
This article discusses primitive data types available in C++.
Integer: Keyword used for integer data types is int. Integers typically requires 4 bytes of memory space
and ranges from -2147483648 to 2147483647.
Character: Character data type is used for storing characters. Keyword used for character data type
is char. Characters typically requires 1 byte of memory space and ranges from -128 to 127 or 0 to 255.
Boolean: Boolean data type is used for storing boolean or logical values. A boolean variable can store
either true or false. Keyword used for boolean data type is bool.
Floating Point: Floating Point data type is used for storing single precision floating point values or
decimal values. Keyword used for floating point data type is float. Float variables typically requires 4 byte
of memory space.
Double Floating Point: Double Floating Point data type is used for storing double precision floating point
values or decimal values. Keyword used for double floating point data type is double. Double variables
typically requires 8 byte of memory space.
void: Void means without any value. void datatype represents a valueless entity. Void data type is used for
those function which does not returns a value.
Wide Character: Wide character data type is also a character data type but this data type has size greater
than the normal 8-bit datatype. Represented by wchar_t. It is generally 2 or 4 bytes long.
Datatype Modifiers: As the name implies, datatype modifiers are used with the built-in data types to modify
the length of data that a particular data type can hold. Data type modifiers available in C++ are:
Signed
Unsigned
Short
Long
Below table summarizes the modified size and range of built-in datatypes when combined with the type
modifiers:
Float 4
Double 8
long double 12
Source Code:
#include <iostream>
using namespace std;
int main()
{
int n, sum = 0;
Output:
(ii) Write a program to understand the concept of scope resolution operator (::)?
Source Code:
#include <iostream>
using namespace std;
int m=10;
void main()
{
int m=20;
clrscr();
{
int k=m;
int m=30;
cout<<"k:="<<k;
cout<<"\nm:="<<m;
cout<<"\nm:="<<::m;
getch();
}
}
Output:
Sample viva questions:
Ans. C is often used for system-level programming, while C++ is favored for applications that benefit
from OOP and complex data structures.
Ans. A class is a blueprint for creating objects in object-oriented programming (OOP). It defines a
data type by encapsulating data (attributes) and functions (methods) that operate on that data.
Ans. A procedural programming language is a type of programming language that follows a structured
approach to writing code, using procedures or routines to perform tasks.
Ans. Data hiding is a fundamental concept in object-oriented programming (OOP) that focuses on
restricting direct access to certain components of an object, typically its internal state (data).
Ans. Modularity is a design principle in software development that emphasizes breaking down a
program into smaller, manageable, and independent components or modules.
Ans. In C++, cin and cout are objects provided by the standard library for input and output operations,
respectively. They are part of the <iostream> header and utilize the C++ stream library for
handling data flow.
Q.9
What are the various application areas of oops?
Ans.
Key application areas include:Software Development,Game Development,GUI,etc.
Q.10 What is diff between object and instance?
Ans. An object is a general term that refers to any entity created from a class. It encapsulates data
(attributes) and behavior (methods) and represents a specific concept or entity in the program.
An instance refers specifically to a concrete occurrence of an object created from a particular
class.
Experiment: 2
Objective: C++ program using with the concept of structures.
Theory:
Structure
A structure is a collection of variable which can be same or different types. You can refer to a structure as a
single variable, and to its parts as members of that variable by using the dot (.) operator. The power of
structures lies in the fact that once defined, the structure name becomes a user-defined data typeand may be
used the same way as other built-in data types, such as int, double, char.
Defining a structure
When dealing with the students in a school, many variables of different types are needed. It may be necessary
to keep track of name, age, Rollno, and marks point for example.
struct Student
{
int rollno, age;
char name[80];
float marks;
};
Student is called the structure tag, and is your brand new data type, like int, double or char.
The most efficient method of dealing with structure variables is to define the structure globally. This tells "the
whole world", namely main and any functions in the program, that a new data type exists. To declare a
structure globally, place it BEFORE void main(). The structure variables can then be defined locally in main,
for example…
struct Student
{
int rollno, age;
char name[80];
float marks;
};
int main()
{
// declare two variables of the new type
Student s1, s3;
………
………
return 0;
}
s3 = s2;
The statement assigns the value of each member of s2 to the corresponding member of s3. Note that one
structure variable can be assigned to another only when they are of the same structure type, otherwise complier
will give an error.
(i) Write a program to implement a calculator program using structure?
Source Code:
#include <iostream>
using namespace std;
struct Calculator
{
int a,b;
void input()
{
cout<<"Enter the values of a and b:=";
cin>>a>>b;
}
void addition()
{
int c=a+b;
cout<<"\nAddition:=";
cout<<c;
}
void subtraction()
{
int c=a-b;
cout<<"\nSubtraction:=";
cout<<c;
}
void multiplication()
{
int c=a*b;
cout<<"\nMultiplication:=";
cout<<c;
}
void division()
{
int c=a/b;
cout<<"\nDivision:=";
cout<<c;
}
};
void main()
{
Calculator calculate;
clrscr();
calculate.input();
calculate.addition();
calculate.subtraction();
calculate.multiplication();
calculate.division();
getch();
}
Output:
(ii) Write a program to store information of student using structure?
#include <iostream>
using namespace std;
struct student
{
char name[50];
int roll;
float marks;
};
int main()
{
student s;
cout << "Enter information," << endl;
cout << "Enter name: ";
cin >> s.name;
cout << "Enter roll number: ";
cin >> s.roll;
cout << "Enter marks: ";
cin >> s.marks;
Output:
Sample viva questions:
Ans. Designated initialization is a feature in C (and C++) that allows you to initialize specific
members of a structure or array by specifying their names or indices, rather than relying
solely on the order of declaration. This can enhance code readability and maintainability,
especially for structures with many members.
Q.6 What is array of structure?
Ans. When defining a structure in C or C++, the structure is terminated with a semicolon (;).
This semicolon is necessary to indicate the end of the structure definition.
Q.9 The declaration of structure is also called as?
The declaration of a structure is often referred to as a structure definition. This defines
the structure type and its members but does not allocate memory for any instances of that
structure.
Q.10 What will happen when the structure is declared?
Ans. Type Definition: Defines a new type.
No Memory Allocation: Memory is allocated only when you declare an instance.
Available for Use: The structure type can be used throughout the program.
EXPERIMENT: 3
Theory:
Class: The building block of C++ that leads to Object Oriented programming is a Class. It is a user defined data
type, which holds its own data members and member functions, which can be accessed and used by creating an
instance of that class. A class is like a blueprint for an object.
For Example: Consider the Class of Cars. There may be many cars with different names and brand but all of
them will share some common properties like all of them will have 4 wheels, Speed Limit, Mileage range etc. So
here, Car is the class and wheels, speed limits, mileage are their properties.
A Class is a user defined data-type which has data members and member functions.
Data members are the data variables and member functions are the functions used to manipulate these
variables and together these data members and member functions defines the properties and behavior of the
objects in a Class.
In the above example of class Car, the data member will be speed limit, mileage etc and member functions
can be apply brakes, increase speed etc.
An Object is an instance of a Class. When a class is defined, no memory is allocated but when it is instantiated
(i.e. an object is created) memory is allocated.
Defining Class and Declaring Objects
A class is defined in C++ using keyword class followed by the name of class. The body of class is defined inside
the curly brackets and terminated by a semicolon at the end.
Declaring Objects: When a class is defined, only the specification for the object is defined; no memory or storage
is allocated. To use the data and access functions defined in the class, you need to create objects.
Syntax:
ClassName ObjectName;
Accessing data members and member functions: The data members and member functions of class can be
accessed using the dot(‘.’) operator with the object. For example if the name of object is obj and you want to
access the member function with the name printName() then you will have to write obj.printName() .
Accessing Data Members
The public data members are also accessed in the same way given however the private data members are not
allowed to be accessed directly by the object. Accessing a data member depends solely on the access control of
that data member.
This access control is given by Access modifiers in C++. There are three access modifiers public, private and
protected.
C++ allows you to specify more than one definition for a function name or an operator in the same scope, which
is called function overloading and operator overloading respectively.
An overloaded declaration is a declaration that is declared with the same name as a previously declared
declaration in the same scope, except that both declarations have different arguments and obviously different
definition (implementation).
When you call an overloaded function or operator, the compiler determines the most appropriate definition to
use, by comparing the argument types you have used to call the function or operator with the parameter types
specified in the definitions. The process of selecting the most appropriate overloaded function or operator is
called overload resolution.
Source Code:
#include <iostream>
using namespace std;
int main() {
#include <iostream>
using namespace std;
class printData {
public:
void print(int i) {
cout << "Printing int: " << i << endl;
}
void print(double f) {
cout << "Printing float: " << f << endl;
}
void print(char* c) {
cout << "Printing character: " << c << endl;
}
};
int main(void) {
printData pd;
return 0;
}
Output:
Sample viva questions:
Ans. Function overloading is a feature in C++ that allows you to define multiple functions
with the same name but different parameter lists (types or number of parameters).
Q.2 What is operator overloading?Explain with example.
Ans. Operator overloading is a feature in C++ that allows you to redefine the behavior of
standard operators (like +, -, *, etc.) for user-defined types (like classes and structures).
This enables you to perform operations on objects of these types in a way that is intuitive
and similar to built-in types.
Q.3 What is the diff between struct and class in c++?
Ans. Use struct for plain data structures (default public).
Use class for encapsulation and more complex behavior (default private).
Both can be used interchangeably in many cases, but the choice often reflects intent
and design.
Q.4 A member function can always be access the data in..?
Ans. A member function can always access the data members (variables) of its own class.
Q.5 How can we make a class abstract?
Ans. In C++, you can make a class abstract by declaring at least one of its member functions
as a pure virtual function.
Q.6 Where a class member function can be defined?
Ans. Inside the Class: Directly within the class definition for concise implementations.
Outside the Class: Using the scope resolution operator for larger or more complex
functions.
Inline: Indicated for potential optimization by the compiler.
Q.7 Can we declared a member function private?
Ans. In C++, if you want to skip certain elements of an array during iteration or processing,
you can do so using conditional statements (like if) to selectively process or ignore
elements based on your criteria.
Q.9 How many object can present in a single class?
Ans. In C++, you can create multiple objects from a single class.
Q.10 Which special character is used to mark the end of class?
Objective: Write programs to understand dynamic memory allocation and array of objects.
Theory:
Dynamic memory allocation in C/C++ refers to performing memory allocation manually by programmer.
Dynamically allocated memory is allocated on Heap and non-static and local variables get memory allocated
on Stack (Refer Memory Layout C Programs for details).
New operator
The new operator denotes a request for memory allocation on the Heap. If sufficient memory is available, new
operator initializes the memory and returns the address of the newly allocated and initialized memory to the
pointer variable.
Syntax to use new operator: To allocate memory of any data type, the syntax is:
pointer-variable = new data-type;
Here, pointer-variable is the pointer of type data-type. Data-type could be any built-in data type including
array or any user defined data types including structure and class.
Example:
// Pointer initialized with NULL
// Then request memory for the variable
int *p = NULL;
p = new int;
OR
// Combine declaration of pointer
// and their assignment
int *p = new int;
Initialize memory: We can also initialize the memory using new operator:
pointer-variable = new data-type(value);
Example:
int *p = new int(25);
float *q = new float(75.25);
Allocate block of memory: new operator is also used to allocate a block(an array) of memory of
type data-type.
pointer-variable = new data-type[size];
where size(a variable) specifies the number of elements in an array.
Example:
int *p = new int[10]
Dynamically allocates memory for 10 integers continuously of type int and returns pointer to the first
element of the sequence, which is assigned to p(a pointer). p[0] refers to first element, p[1] refers to second
element and so on.
(i) WAP to illustrate dynamic allocation and deallocation of memory using new and delete
#include <iostream>
using namespace std;
int main ()
{
// Pointer initialization to null
int* p = NULL;
if (!q)
cout << "allocation of memory failed\n";
else
{
for (int i = 0; i < n; i++)
q[i] = i+1;
return 0;
}
Output:
(ii) WAP to dynamic memory allocation of objects.
#include <iostream>
using namespace std;
class Box {
public:
Box() {
cout << "Constructor called!" <<endl;
}
~Box() {
cout << "Destructor called!" <<endl;
}
};
int main() {
Box* myBoxArray = new Box[4];
delete [] myBoxArray; // Delete array
return 0;
}
Output:
Sample viva questions:
Ans. new: Used to dynamically allocate memory for a single object or an array of objects. It
also calls the constructor for the object(s).
delete: Used to deallocate memory previously allocated with new. It also calls the
destructor for the object(s).
Q.2 Explain the dynamic object initialization.
Ans. This refers to initializing objects at runtime using dynamic memory allocation (new in
C++). This allows objects to be created and destroyed as needed during program
execution, rather than being fixed at compile-time.
Q.3 Explain the static variable and method.
Ans. Static variable: A variable declared with the static keyword inside a class or function
retains its value between function calls and is shared among all instances of the class.
Static method: A method declared with the static keyword inside a class can be called
without creating an instance of the class.
Q.4 What is the diff between new and malloc?
Ans. new is an operator in C++ used to allocate memory for an object or array of objects and
calls constructors for initialization.
malloc is a function in C used to allocate a block of memory of specified size in bytes,
but it does not initialize the memory and does not call constructors.
Q.5 How memory allocated and deallocated?
Ans. This occurs when free memory becomes divided into small, unusable fragments between
allocated blocks. It can lead to inefficient memory usage and performance degradation
over time.
Q.8 What do you mean by null pointer?
Ans. A null pointer is a pointer that does not point to any memory location. It's a pointer value
reserved by the language to indicate that it is not pointing to a valid object or function.
Q.9 What is the diff between malloc and calloc?
Ans. malloc(size): Allocates a block of memory of size bytes, but the memory contents are
uninitialized.
calloc(num, size): Allocates a block of memory for an array of num elements each of
size bytes, and initializes all bits to zero.
Q.10 What is macro?
Ans. A macro in C/C++ is a fragment of code which has been given a name. When the name is
used, it is replaced by the contents of the macro. Macros are typically used to define
constants or to create short, reusable code snippets.
EXPERIMENT: 5
Theory: The process of creating and deleting objects in C++ is a vital task. Each time an instance of a class is
created the constructor method is called. Constructors is a special member function of class and it is used to
initialize the objects of its class. It is treated as a special member function because its name is the same as the
class name. These constructors get invoked whenever an object of its associated class is created. It is named as
"constructor" because it constructs the value of data member of a class. Initial values can be passed as
arguments to the constructor function when the object is declared.
Types of Constructors
C++ offers four types of constructors. These are:
1. Do nothing constructor
2. Default constructor
3. Parameterized constructor
4. Copy constructor
Do nothing Constructor
Do nothing constructors are that type of constructor which does not contain any statements. Do nothing
constructor is the one which has no argument in it and no return type.
Default Constructor
The default constructor is the constructor which doesn't take any argument. It has no parameter but a
programmer can write some initialization statement there.
Syntax:
class_name()
// Constructor Definition ;
A default constructor is very important for initializing object members, that even if we do not define a
constructor explicitly, the compiler automatically provides a default constructor implicitly.
Parameterized Constructor
A default constructor does not have any parameter, but programmers can add and use parameters within a
constructor if required. This helps programmers to assign initial values to an object at the time of creation.
Copy Constructor
C++ provides a special type of constructor which takes an object as an argument and is used to copy values of
data members of one object into another object. In this case, copy constructors are used to declaring and
initializing an object from another object.
Example:
Calc C2(C1);
Or
Calc C2 = C1;
The process of initializing through a copy constructor is called the copy initialization.
Syntax:
DESTRUCTOR:
As the name implies, destructors are used to destroy the objects that have been created by the constructor within
the C++ program. Destructor names are same as the class name but they are preceded by a tilde (~). It is a good
practice to declare the destructor after the end of using constructor. Here's the basic declaration procedure of a
destructor:
~Cube()
The destructor neither takes an argument nor returns any value and the compiler implicitly invokes upon the
exit from the program for cleaning up storage that is no longer accessible.
(i) Write a program to implement a class wall without using constructor?
Source Code:
#include <iostream>
using namespace std;
// declare a class
class Wall {
private:
double length;
public:
// create a constructor
Void setWall() {
// create an object
Wall wall1;
wall1.setWall();
return 0;
}
Output:
(ii) Write a program to implement a class Wall using zero argument constructor or default constructor?
Source Code:
#include <iostream>
using namespace std;
// declare a class
class Wall {
private:
double length;
public:
// create a constructor
Wall() {
int main() {
// create an object
Wall wall1;
return 0;
}
Output:
iii) Write a program to implement a class Wall using parameterized constructor?
Source Code:
#include <iostream>
using namespace std;
// declare a class
class Wall {
private:
double length;
double height;
public:
// create parameterized constructor
Wall(double len, double hgt) {
// initialize private variables
length = len;
height = hgt;
}
double calculateArea() {
return length * height;
}
};
int main() {
// create object and initialize data members
Wall wall1(10.5, 8.6);
Wall wall2(8.5, 6.3);
return 0;
}
Output:
Sample viva questions:
Ans. A constructor is a special member function that is automatically called when an object of
a class is created. It is used to initialize the object's data members and allocate resources
if necessary.
Q.2 What is destructor?
Ans. A destructor is a special member function that is automatically called when an object goes
out of scope or is explicitly deleted. It is used to release resources allocated by the object
and perform cleanup operations.
Q.3 What is copy constructor?
Ans. A copy constructor is a constructor that creates a new object as a copy of an existing object
of the same class. It is invoked when an object is passed by value, returned by value, or
initialized with another object of the same type.
Q.4 What is virtual destructor?
Ans. A virtual destructor is a destructor declared in a base class that is overridden in derived
classes. It ensures that objects are properly destroyed in the correct order when deleted
through a base class pointer.
Q.5 How should a constructor handle a failure?
Ans. If a constructor fails (e.g., memory allocation failure), it typically throws an exception or
handles the failure gracefully by setting the object to a valid but "empty" state. Proper error
handling ensures that resources are not leaked and the program can recover from failures.
Q.6 What is virtual constructor?
Ans. In C++, there is no concept of a virtual constructor. Constructors cannot be virtual because
they are called during object creation and are determined statically based on the type of
the object being instantiated.
Q.7 Explain diff type of constructor.
Ans. Default constructor: Takes no arguments.
Parameterized constructor: Takes parameters to initialize the object.
Copy constructor: Constructs a new object as a copy of an existing object.
Constructor with default arguments: Allows parameters to have default values.
Destructor: Cleans up resources when an object is destroyed.
Q.8 What do you mean by constructor overloading?
Ans. Constructor overloading refers to having multiple constructors within a class, each with a
different parameter list. This allows objects to be initialized in different ways depending
on the arguments passed.
Q.9 How constructors are diff from normal member functions?
Ans. Constructors are special member functions used for initializing objects when they are
created.
Constructors do not have a return type and are automatically called when an object is
instantiated.
Normal member functions are regular functions within a class that perform operations
on the object's data members and can have any return type.
Q.10 Can we have more than one constructor in class?
Ans. Yes, a class in C++ can have more than one constructor.
EXPERIMENT: 6
Objective: Implement friend function to access private data of a class and usage of this pointer.
Theory: A friend function of a class is defined outside that class' scope but it has the right to access all private
and protected members of the class. Even though the prototypes for friend functions appear in the class definition,
friends are not member functions.
A friend can be a function, function template, or member function, or a class or class template, in which case the
entire class and all of its members are friends.
To declare a function as a friend of a class, precede the function prototype in the class definition with
keyword friend as follows −
class Box {
double width;
public:
double length;
friend void printWidth( Box box );
void setWidth( double wid );
};
Following are some important points about friend functions and classes:
1) Friends should be used only for limited purpose. too many functions or external classes are declared as
friends of a class with protected or private data, it lessens the value of encapsulation of separate classes in
object-oriented programming.
2) Friendship is not mutual. If a class A is friend of B, then B doesn’t become friend of A automatically.
3) Friendship is not inherited
4) The concept of friends is not there in Java.
To understand ‘this’ pointer, it is important to know that how objects look at functions and data members of a
class.
1. Each object gets its own copy of the data member.
2. All access the same function definition as present in the code segment.
Meaning each object gets its own copy of data members and all objects share single copy of member functions.
Compiler supplies an implicit pointer along with the functions names as ‘this’.
The ‘this’ pointer is passed as a hidden argument to all nonstatic member function calls and is available as a
local variable within the body of all nonstatic functions. ‘this’ pointer is a constant pointer that holds the
memory address of the current object. ‘this’ pointer is not available in static member functions as static member
functions can be called without any object (with class name).
For a class X, the type of this pointer is ‘X* const’. Also, if a member function of X is declared as const, then
the type of this pointer is ‘const X *const’ .
(i) Write a program to calculate cube of a number using friend function.
Source Code:
#include <iostream>
using namespace std;
class Demo
{
private:
int num;
public:
void input()
{
cout<<”Enter the value of number:=”;
cin>>num;
}
friend int cube(Demo d);
};
int cube(Demo d)
{
return d.num*d.num*d.num;
}
void main()
{
Demo d;
d.input();
cout<<"cube is:="<<cube(d);
Output:
(ii) Write a program to swapping of two class data using friend function?
Source Code:
#include <iostream>
using namespace std;
class Second;
class First
{
private:
int num1;
public:
void input()
{
cout<<"Enter number 1:=";
cin>>num1;
}
void show()
{
cout<<"Number 1:="<<num1<<endl;
}
friend void swap(First &,Second &);
};
class Second
{
private:
int num2;
public:
void input()
{
cout<<"Enter number 2:=";
cin>>num2;
}
void show()
{
cout<<"Number 2:="<<num2<<endl;
}
friend void swap(First &,Second &)
};
void swap(First &A,Second &B)
{
int t;
t=A.num1;
A.num1=B.num2;
B.num2=t;
}
void main()
{
First F;
Second S;
clrscr();
F.input();
S.input();
cout<<"Before Swapping\n";
F.show();
S.show();
swap(F,S);
cout<<"After Swapping\n";
F.show();
S.show();
getch();
}
Output:
(iii) WAP to understand concept of this pointer.
#include<iostream.h>
using namespace std;
int main()
{
Test obj;
int x = 20;
obj.setX(x);
obj.print();
return 0;
}
Output:
Sample viva questions:
Ans. A friend function in C++ is a function that is not a member of a class but has access to
the class's private and protected members. It is declared with the friend keyword inside
the class whose private or protected members it needs to access.
Q.2 Explain access specifier in c++?
Ans. public: Members are accessible from outside the class through object of the class.
private: Members are only accessible from within the same class. They are not
accessible from outside the class, including derived classes.
protected: Members are accessible from within the same class and derived classes
Q.3 What is this pointer?
Ans. The this pointer is a special pointer available in C++ that points to the object for which
the member function is called. It is automatically passed as a hidden argument to all
non-static member function calls.
Q.4 Which keyword is used to declare a friend function?
Ans. The friend keyword is used to declare a function as a friend of a class. It allows the
friend function to access private and protected members of the class.
Q.5 What is the syntax of friend function?
Ans. class MyClass { private: int privateVar; public: friend void friendFunction(MyClass
obj); // Declaration of friend function };
Q.6 Which is the pointer which denotes the object calling the member function?
Ans. The this pointer denotes the object for which the member function is called. Inside any
non-static member function, this points to the object that invoked the member function.
Q.7 The this pointer is accessible…?
Ans. The this pointer is accessible within non-static member functions of a class. It points to
the object on which the member function is called.
Q.8 What is the result of sizeof() function?
Ans. The sizeof() function in C++ returns the size in bytes of its operand, which can be a
type, variable, or expression. It is evaluated at compile-time and yields a result of type
size_t.
Q.9 Non static member function is called?
Ans. Non-static member functions in C++ are called using an instance (object) of the class.
They have access to the this pointer and can operate on the data members of the object.
Q.10 What is the importance of muatable keywords?
Ans. The mutable keyword in C++ is used to declare a non-const data member of a const
object. This allows the member to be modified within const member functions of the
class. It is particularly useful when a class needs to maintain logical constness but still
modify certain members.
EXPERIMENT: 7
Objective: Write programs to understand the usage of constant data member and member function, static data
member and member function in a class.
Theory:
Const keyword is used to make any element of a program constant. Let's see its significance with different
program elements.
Const Variables
If we declare a variable as const, we cannot change its value. A const variable must be assigned a value at the
time of its declaration.
Once initialized, if we try to change its value, then we will get compilation error. The following two cases will
give us an error since in both these cases, we are trying to change the value of a const variable.
When we declare a normal variable (data member) in a class, different copies of those data members create with
the associated objects.
In some cases when we need a common data member that should be same for all objects, we cannot do this using
normal data members. To fulfill such cases, we need static data members.
In this post, we are going to learn about the static data members and static member functions, how they declare,
how they access with and without member functions?
It is a variable which is declared with the static keyword, it is also known as class member, thus only single
copy of the variable creates for all objects.
Any changes in the static data member through one member function will reflect in all other object’s member
functions.
Declaration
#include <iostream.h>
using namespace std;
class Demo
{
private:
static int X;
public:
static void fun()
{
cout <<"Value of X: " << X << endl;
}
};
//defining
int Demo :: X =10;
int main()
{
Demo X;
X.fun();
return 0;
}
Output
Value of X: 10
(ii) WAP to implement static data member.
#include <iostream>
using namespace std;
class Demo
{
public:
static int ABC;
};
//defining
int Demo :: ABC =10;
int main()
{
x"<<Demo::x; ;
x
}
Output:
(iii) WAP to implement constant data member.
#include<iostream.h>
using namespace std;
class Test {
int value;
public:
Test(int v = 10)
{value = v;}
int getValue() const
{return value;}
};
int main() {
const Test t;
cout << t.getValue();
return 0;
}
Output:
Sample viva questions:
Ans. The static keyword is used to declare a static variable in C++. It can be applied to both
member variables and local variables within functions.
Q.2 The static data members are?
Ans. Static data members are shared among all instances (objects) of a class. There is only one
copy of a static data member that is shared by all objects of the class.
Q.3 The syntax for defining the static data member?
Ans. To define a static data member outside the class declaration, you need to use the class
name and scope resolution operator ::
class MyClass { public: static int staticVar; // Declaration of static data member }; int
MyClass::staticVar = 10;
Q.4 What is static class data?
Ans. Static class data refers to static data members within a class. These members are shared
across all instances of the class and can be accessed without requiring an object of the
class.
Q.5 What is static and dynamic type checking?
Ans. Static type checking: Type checking done at compile-time to ensure type correctness.
It verifies that operations are performed on data of the correct type.
Dynamic type checking: Type checking done at runtime, often associated with
polymorphic behavior (like virtual function calls in C++). It ensures that the correct
function is called based on the actual type of the object.
Q.6 What are the static variables?
Ans. Static variables in C++ are variables that retain their values across function calls, making
them suitable for maintaining state or sharing data among instances of a class.
Q.7 What is static method?
Ans. A static method in C++ is a method that belongs to the class rather than to instances
(objects) of the class. It can be called using the class name without needing an object of
the class.
Q.8 How to access private static data member?
Ans. Private static data members can be accessed only by member functions (including static
member functions) of the same class. There is no direct way to access private static data
members from outside the class.
Q.9 Where should a static data member be initialized?
Ans. Static data members should ideally be initialized outside the class declaration, typically in
a source file (.cpp). This ensures that there is only one definition of the static member
across all translation units.
Q.10 What is the use of static class data?
Ans. Static class data is useful for maintaining shared state among all instances of a class or for
maintaining global-like variables within the scope of the class. It is commonly used for
constants, counters, or configuration values that need to be consistent across all objects of
the class.
EXPERIMENT: 8
Objective: Implement different types of inheritance, function overriding and virtual function.
The capability of a class to derive properties and characteristics from another class is called Inheritance.
Inheritance is one of the most important feature of Object Oriented Programming.
Sub Class: The class that inherits properties from another class is called Sub class or Derived Class.
Super Class:The class whose properties are inherited by sub class is called Base Class or Super class.
The article is divided into following subtopics:
1. Why and when to use inheritance?
2. Modes of Inheritance
3. Types of Inheritance
Why and when to use inheritance?
Consider a group of vehicles. You need to create classes for Bus, Car and Truck. The methods fuelAmount(),
capacity(), applyBrakes() will be same for all of the three classes. If we create these classes avoiding inheritance
then we have to write all of these functions in each of the three classes as shown in below figure:
You can clearly see that above process results in duplication of same code 3 times. This increases the chances of
error and data redundancy. To avoid this type of situation, inheritance is used. If we create a class Vehicle and
write these three functions in it and inherit the rest of the classes from the vehicle class, then we can simply
avoid the duplication of data and increase re-usability. Look at the below diagram in which the three classes are
The below table summarizes the above three modes and shows the access specifier of the members of base class
in the sub class when derived in public, protected and private modes:
Multilevel Inheritance: In this type of inheritance, a derived class is created from another derived class.
3. Hierarchical Inheritance: In this type of inheritance, more than one sub class is inherited from a single
base class. i.e. more than one derived class is created from a single base
class.
4. Hybrid (Virtual) Inheritance: Hybrid Inheritance is implemented by combining more than one type of
inheritance. For example: Combining Hierarchical inheritance and Multiple Inheritance.
Below image shows the combination of hierarchical and multiple inheritance:
C++ Function Overriding
If derived class defines same function as defined in its base class, it is known as function overriding in C++. It is
used to achieve runtime polymorphism. It enables you to provide specific implementation of the function which
is already provided by its base class.
A virtual function a member function which is declared within base class and is re-defined (Overridden) by
derived class. When you refer to a derived class object using a pointer or a reference to the base class, you can
call a virtual function for that object and execute the derived class’s version of the function.
Virtual functions ensure that the correct function is called for an object, regardless of the type of reference
(or pointer) used for function call.
They are mainly used to achieve Runtime polymorphism
Functions are declared with a virtual keyword in base class.
The resolving of function call is done at Run-time.
(i) Write a program to perform inheritance in different classes?
Source Code:
#include <iostream>
using namespace std;
class A
{
protected:
int m1;
void get_m1();
};
class B
{
protected:
int m2;
void get_m2();
};
class C
{
protected:
int m3;
void get_m3();
};
void A::get_m1()
{
cout<<"Enter marks of physics:=";
cin>>m1;
}
void B::get_m2()
{
cout<<"Enter marks of chemistry:=";
cin>>m2;
}
void C::get_m3()
{
cout<<"Enter marks of mathematics:=";
cin>>m3;
}
class D:public A,public B,public C
{
private:
int n,i,total;
float per;
char name[20];
public:
void final();
};
void D::final()
{
cout<<"Enter the number of students:=";
cin>>n;
for(i=0;i<n;i++)
{
cout<<" "<<endl;
cout<<"Enter the name of student:=";
cin>>name;
get_m1();
get_m2();
get_m3();
total=m1+m2+m3;
per=(total/300.00)*100;
cout<<" "<<endl;
cout<<"Name:="<<name<<endl;
cout<<"Total marks of student is:="<<total<<endl;
cout<<"Percentage of student is:="<<per<<endl;
if(per>=75)
{
cout<<"GRADE IS EXCELLENT"<<endl;
}
else if((per>=50)&&(per<75))
{
}
}
else
{
cout<<"GRADE
IS GOOD"<<endl;
cout<<"GRADE
IS POOR"<<endl;
}
cout<<" ";
}
void main()
{
D p;
p.final();
Output:
(ii) WAP to understand concept of function overriding.
#include<iostream.h>
using namespace std;
class BaseClass
{
public:
virtual void Display()
{
cout << "\nThis is Display() method"
" of BaseClass";
}
void Show()
{
cout << "\nThis is Show() method "
"of BaseClass";
}
};
class DerivedClass : public BaseClass
{
public:
// Overriding method - new working of
// base class's display method
void Display()
{
cout << "\nThis is Display() method"
" of DerivedClass";
}
};
int main()
{
DerivedClass dr;
BaseClass &bs = dr;
bs.Display();
dr.Show();
}
Output:
Sample viva questions:
Ans. Multilevel inheritance refers to a chain of inheritance where a derived class inherits
from a base class, and then another class inherits from this derived class, forming a
hierarchical relationship.
Q.4 What is multiple inheritance?
Ans. Multiple inheritance occurs when a derived class inherits from more than one base
class. It allows a class to inherit attributes and behaviors from multiple sources.
Q.5 What is single inheritance?
Ans. Single inheritance involves one base class and one derived class. The derived class
inherits attributes and behaviors from a single base class.
Q.6 What is hybrid level inheritance?
Ans. Hierarchical inheritance involves multiple derived classes inheriting from a single
base class. Each derived class forms a level in the hierarchy of inheritance.
Q.8 What is function overriding?
Ans. Function overriding occurs when a derived class provides a specific implementation
of a function that is already defined in its base class. It allows a subclass to provide a
specialized implementation of a method that is already provided by one of its
superclasses.
Ans. A virtual function is a member function in a base class that is declared using the
virtual keyword. It is intended to be overridden in derived classes and allows dynamic
polymorphism.
Q.10 What are abstract classes?
Ans. Abstract classes are classes that cannot be instantiated on their own because they
contain one or more pure virtual functions. They serve as base classes designed to be
inherited by other classes, which provide implementations for the pure virtual
functions .
EXPERIMENT: 9
Theory:
However, for user-defined types (like: objects), you can redefine the way operator works. For example:
If there are two objects of a class that contains string as its data members. You can redefine the meaning of +
operator and use it to concatenate those strings.
This feature in C++ programming that allows programmer to redefine the meaning of an operator (when they
operate on class objects) is known as operator overloading.
To overload an operator, a special operator function is defined inside the class as:
class className
{
... .. ...
public
returnType operator symbol (arguments)
{
... .. ...
}
... .. ...
};
Source Code:
#include<iostream>
using namespace std;
class Complex {
private:
int real, imag;
public:
Complex(int r = 0, int i =0) {real = r; imag = i;}
int main()
{
Complex c1(10, 5), c2(2, 4);
Complex c3 = c1 + c2; // An example call to "operator+"
c3.print();
}
Output:
(ii) WAP to overload decrement operator
#include <iostream>
using namespace std;
class Test
{
private:
int count;
public:
Test(): count(5){}
int main()
{
Test t;
--t;
t.Display();
return 0;
}
Output:
Sample viva questions:
Ans. Operator overloading is a feature in C++ that allows operators to be redefined for user-
defined types (classes or structs). This means you can define how an operator should
behave with operands of a user-defined type.
Q.2 Why is it necessary to overload an operator?
Ans. Operator overloading provides a way to extend the functionality of operators beyond their
predefined operations. It allows for natural and intuitive use of operators with user-defined
types, making the code more readable and expressive.
Q.3 Give name of operators we cannot overload?
Ans. :: (scope resolution operator)
.* (member pointer operator)
?: (ternary conditional operator)
Q.4 What is an operator function?
Ans. An operator function is a function defined within a class (or as a global function) that
defines the behavior of an operator when applied to objects of that class (or types).
Q.5 What is diff between overloading and overriding?
Ans. Overloading: Involves redefining an operator or function with the same name but
different parameters (in the case of operators, the type of operands).
Overriding: Involves redefining a base class function in a derived class to provide a
specific implementation, typically using inheritance and polymorphism.
Q.6 Can main () be overridden?
Ans. No, main() cannot be overridden in C++. The main() function is the entry point of a C++
program and must be declared exactly as int main() or int main(int argc, char *argv[]).
Q.7 What is overloading unary operator?
Ans. Unary operators operate on a single operand. To overload a unary operator, you define a
member or a friend function that takes one operand.
Q.8 Give rules for overloading operators?
Ans. Operators can be overloaded either as member functions or as global (non-member)
functions.
Some operators must be overloaded as member functions (=, [], (), ->).
Operators like &&, ||, ,, and ?: cannot be overloaded.
Overloaded operators retain their precedence and associativity, but you cannot change
the number of operands or their types.
Q.9 Give name of operator which friend function cannot be overload?
Ans. The assignment operator (=) cannot be overloaded using a friend function. It must be
overloaded as a member function.
Ans. Yes, operator overloading allows us to change the behavior or meaning of an operator when
applied to user-defined types.
EXPERIMENT: 10
Theory:
Templates are powerful features of C++ which allows you to write generic programs. In simple terms, you can
create a single function or a class to work with different data types using templates. Templates are often used in
larger codebase for the purpose of code reusability and flexibility of the programs.
Function Templates
Class Templates
Function Templates
A function template works in a similar to a normal function, with one key difference.
A single function template can work with different data types at once but, a single normal function can only
work with one set of data types.
Normally, if you need to perform identical operations on two or more types of data, you use function
overloading to create two functions with the required function declaration.
However, a better approach would be to use function templates because you can perform the same task writing
less and maintainable code.
A function template starts with the keyword template followed by template parameter/s inside < > which is
followed by function declaration.
Like function templates, you can also create class templates for generic class operations.
Sometimes, you need a class implementation that is same for all classes, only the data types used are different.
Normally, you would need to create a different class for each data type OR create different member variables
and functions within a single class.
This will unnecessarily bloat your code base and will be hard to maintain, as a change is one class/function
should be performed on all classes/functions.
However, class templates make it easy to reuse the same code for all data types.
How to declare a class template?
template <class T>
class className
{
... .. ...
public:
T var;
T someOperation(T arg);
... .. ...
};
In the above declaration, T is the template argument which is a placeholder for the data type used.
Inside the class body, a member variable var and a member function someOperation() are both of type T.
To create a class template object, you need to define the data type inside a < > when creation.
className<dataType> classObject;
(i) WAP to create a template function to identify larger among two values(int, float, char)
#include <iostream>
using namespace std;
// template function
template <class T>
T Large(T n1, T n2)
{
return (n1 > n2) ? n1 : n2;
}
int main()
{
int i1, i2;
float f1, f2;
char c1, c2;
return 0;
}
Output:
(ii) WAP to create a class template with a class swapper to swap two values.
#include<iostream.h>
#include<conio.h>
template < class T>
class Swapper{
private:
T mem1, mem2;
public:
Swapper(T t1, T t2){
mem1 = t1;
mem2 = t2;
}
void display(){
cout<<"mem1 = "<<mem1<<" and mem2 = "<<mem2<<endl;
}
void swapp(){
T temp;
temp = mem1;
mem1 = mem2;
mem2 = temp;
}
};
int main(){
Swapper <int>int_swapper(2,6);
Swapper <float>float_swapper(6.7777, 8.5555);
cout<<"Before swapping integer :"<<endl;
int_swapper.display();
cout<<"Before swapping float :"<<endl;
float_swapper.display();
int_swapper.swapp();
float_swapper.swapp();
cout<<"After swapping integer :"<<endl;
int_swapper.display();
cout<<"After swapping float :"<<endl;
float_swapper.display();
return 0;
}
Output:
Sample viva questions:
Ans. Templates in C++ are a powerful feature that allows you to write generic classes and
functions. They enable you to define functions and classes that work with any data type
without having to rewrite the code for each specific type.
Q.2 What is generic programming?
Ans. Generic programming is a programming paradigm that emphasizes writing algorithms and
data structures in a way that they can operate on any data type, rather than specific types.
Templates in C++ enable generic programming.
Q.3 What is diff between overloaded functions and function templates?
Ans. Overloaded functions: In C++, overloaded functions are multiple functions with the
same name but different parameter lists. Each overloaded function can have a different
implementation or behavior based on the type and number of arguments passed.
Function templates: Function templates are a single function definition that can operate
with different data types. They use template parameters to represent different types or
values that are specified when the function is called.
Q.4 What is templates class?
Ans. A template class is a class that is parameterized by one or more types. It allows you to
define a generic class that can work with any data type.
Q.5 What are class templates?
Ans. Class templates are templates that define a family of classes. They enable you to create a
single class definition that can work with different data types specified as template
arguments.
Q.6 Can there be more than one argument to templates?
Ans. Yes, templates in C++ can have more than one template argument. You can specify
multiple template parameters separated by commas (,) within angle brackets (<>).
Q.7 Can we specify default value for template argument?
Ans. Yes, you can specify default values for template arguments in C++. This allows you to
provide a default type or value that will be used if the caller does not explicitly specify it.
Q.8 Give the syntax of function templates?
Theory:
An exception is a problem that arises during the execution of a program. A C++ exception is a response to an
exceptional circumstance that arises while a program is running, such as an attempt to divide by zero.
Exceptions provide a way to transfer control from one part of a program to another. C++ exception handling is
built upon three keywords: try, catch,and throw.
throw − A program throws an exception when a problem shows up. This is done using a throw keyword.
catch − A program catches an exception with an exception handler at the place in a program where you
want to handle the problem. The catch keyword indicates the catching of an exception.
try − A try block identifies a block of code for which particular exceptions will be activated. It's followed
by one or more catch blocks.
Assuming a block will raise an exception, a method catches an exception using a combination of
the try and catch keywords. A try/catch block is placed around the code that might generate an exception. Code
within a try/catch block is referred to as protected code, and the syntax for using try/catch as follows −
try {
// protected code
} catch( ExceptionName e1 ) {
// catch block
} catch( ExceptionName e2 ) {
// catch block
} catch( ExceptionName eN ) {
// catch block
}
You can list down multiple catch statements to catch different type of exceptions in case your try block raises
more than one exception in different situations.
Throwing Exceptions
Exceptions can be thrown anywhere within a code block using throwstatement. The operand of the throw
statement determines a type for the exception and can be any expression and the type of the result of the
expression determines the type of exception thrown.
Catching Exceptions
The catch block following the try block catches any exception. You can specify what type of exception you
want to catch and this is determined by the exception declaration that appears in parentheses following the
keyword catch.
try {
// protected code
} catch( ExceptionName e ) {
// code to handle ExceptionName exception
}
Above code will catch an exception of ExceptionName type. If you want to specify that a catch block should
handle any type of exception that is thrown in a try block, you must put an ellipsis, ..., between the parentheses
enclosing the exception declaration as follows −
try {
// protected code
} catch(...) {
// code to handle any exception
}
(i) WAP to divide two numbers using try catch block.
#include <iostream>
#include <conio.h>
using namespace std;
int main()
{
int a,b;
cout << "Enter 2 numbers: ";
cin >> a >> b;
try
{
if (b != 0)
{
float div = (float)a/b;
if (div < 0)
throw 'e';
cout << "a/b = " << div;
}
else
throw b;
}
catch (int e)
{
cout << "Exception: Division by zero";
}
catch (char st)
{
cout << "Exception: Division is less than 1";
}
catch(...)
{
cout << "Exception: Unknown";
}
return 0;
}
Output:
(ii) WAP to implement throw keyword
#include<iostream.h>
using namespace std;
int main()
{
int p,c,m,err=0;
string name;
do
{
try //using try block to check error;
{
cout<<"Enter sudentname : ";
cin>>name;
cout<<"Enter physics marks : ";
cin>>p;
Output:
Sample viva questions:
Ans. An exception is an event that occurs during the execution of a program that disrupts the
normal flow of instructions. It is typically caused by an error, like a runtime error or an
unusual condition that prevents the program from continuing as expected.
Q.2 What is an error?
Ans. An error is a deviation from correct behavior of a program. Errors can occur at compile-
time (syntax errors), runtime (exceptions, segmentation faults), or during execution due to
unexpected conditions.
Q.3 What is Exception Handling?
Ans. Exception handling is a mechanism in programming languages that allows you to handle
exceptional conditions (exceptions) gracefully. It provides a way to separate error-handling
code from normal code, improving the robustness and reliability of programs.
Q.4 Explain try block.
Ans. A try block is used in C++ to enclose the code that may throw an exception. It is followed
by one or more catch blocks to handle different types of exceptions that may be thrown
within the try block.
Q.5 Explain catch block?
Ans. A catch block is used to handle exceptions thrown by code within a preceding try block.
Each catch block specifies the type of exception it can handle.
Q.6 Explain throw block?
Ans. The throw statement is used to manually throw an exception within a C++ program. It can
throw any data type, including fundamental types, pointers, objects, and even literals.
Q.7 Explain terminate() and unexpected() function?
Ans. terminate(): This function is called when the exception handling mechanism cannot
find an appropriate handler for a thrown exception. It is the default behavior to terminate
the program.
unexpected(): This function is called when an exception is thrown that is not expected
by any of the function's exception specifications (deprecated in C++11).
Q.8 Explain rethrowing exceptions with example.
Ans. Rethrowing an exception means catching an exception in one part of the program and then
throwing it again to be caught by another handler elsewhere. This can be useful for adding
additional context or handling at different levels of abstraction.
Q.9 Which is the Parent class for all exceptions?
Ans. In C++, the parent class for all exceptions is std::exception. It is defined in the <exception>
header and is the base class for all standard exceptions thrown by the C++ Standard
Library.
Q.10 Which alternative can replace the throw statement?
Ans. An alternative to using the throw statement directly is to use the std::throw_with_nested
function.
EXPERIMENT: 12
Theory: So far, we have been using the iostream standard library, which provides cinand cout methods for
reading from standard input and writing to standard output respectively.
This tutorial will teach you how to read and write from a file. This requires another standard C++ library
called fstream, which defines three new data types −
1 Ofstream
This data type represents the output file stream and is used to create files and
to write information to files.
2 Ifstream
This data type represents the input file stream and is used to read information
from files.
3 Fstream
This data type represents the file stream generally, and has the capabilities of
both ofstream and ifstream which means it can create files, write information
to files, and read information from files.
To perform file processing in C++, header files <iostream> and <fstream> must be included in your C++ source
file.
Opening a File
A file must be opened before you can read from it or write to it. Either ofstream or fstream object may be used
to open a file for writing. And ifstream object is used to open a file for reading purpose only.
Following is the standard syntax for open() function, which is a member of fstream, ifstream, and ofstream
objects.
void open(const char *filename, ios::openmode mode);
Here, the first argument specifies the name and location of the file to be opened and the second argument of
the open() member function defines the mode in which the file should be opened.
Sr.No Mode Flag & Description
1 ios::app
Append mode. All output to that file to be appended to the end.
2 ios::ate
Open a file for output and move the read/write control to the end of the file.
3 ios::in
Open a file for reading.
4 ios::out
Open a file for writing.
5 ios::trunc
If the file already exists, its contents will be truncated before opening the file.
You can combine two or more of these values by ORing them together. For example if you want to open a file
in write mode and want to truncate it in case that already exists, following will be the syntax −
ofstream outfile;
outfile.open("file.dat", ios::out | ios::trunc );
Similar way, you can open a file for reading and writing purpose as follows −
fstream afile;
afile.open("file.dat", ios::out | ios::in );
Closing a File
When a C++ program terminates it automatically flushes all the streams, release all the allocated memory and
close all the opened files. But it is always a good practice that a programmer should close all the opened files
before program termination.
Following is the standard syntax for close() function, which is a member of fstream, ifstream, and ofstream
objects.
void close();
Writing to a File
While doing C++ programming, you write information to a file from your program using the stream insertion
operator (<<) just as you use that operator to output information to the screen. The only difference is that you
use an ofstream or fstream object instead of the cout object.
Reading from a File
You read information from a file into your program using the stream extraction operator (>>) just as you use that
operator to input information from the keyboard. The only difference is that you use
an ifstream or fstream object instead of the cin object.
The argument to seekg and seekp normally is a long integer. A second argument can be specified to indicate the
seek direction. The seek direction can be ios::beg (the default) for positioning relative to the beginning of a
stream, ios::cur for positioning relative to the current position in a stream or ios::end for positioning relative to
the end of a stream.
The file-position pointer is an integer value that specifies the location in the file as a number of bytes from the
file's starting location. Some examples of positioning the "get" file-position pointer are −
// position to the nth byte of fileObject (assumes ios::beg)
fileObject.seekg( n );
Output:
Sample viva questions:
Ans. To use file I/O operations in C++, you need to include the <fstream> header file. This
header provides classes like ifstream (input file stream), ofstream (output file stream), and
fstream (file stream, supports both input and output).
Q.2 What is the use of ios::trunc mode?
Ans. The ios::trunc mode is used when opening a file for writing (ofstream) to truncate the file to
zero length if it already exists. This means that if the file exists, its contents are deleted
before opening.
Q.3 What is the return type open() method?
Ans. The open() method in C++ file streams (ifstream, ofstream, fstream) returns void. It is used
to open a file with a specified mode (like ios::in, ios::out, ios::binary, etc.).
Q.4 What is file handling in ooops?
Ans. File handling in object-oriented programming (OOPs) refers to the ability to read from and
write to files using objects of file stream classes (ifstream, ofstream, fstream). It allows data
to be persisted to storage (like disk) and retrieved as needed.
Q.5 What is the default mode of the opening using the ofstream class?
Ans. The default mode of opening a file using the ofstream class is ios::out. This mode opens a
file for writing. If the file does not exist, it creates a new file; if it exists, it truncates the file
to zero length.
Q.6 What is the use of ios::app mode?
Ans. The ios::app mode (append mode) is used when opening a file (ofstream) to append data to
the end of the file. If the file does not exist, it creates a new file. It preserves the existing
contents of the file and appends new data at the end.
Q.7 What is the default mode of the opening using the ifstream class?
Ans. The default mode of opening a file using the ifstream class is ios::in. This mode opens a file
for reading.
Q.8 Which function is used to reposition the file pointer?
Ans. The seekg() and seekp() functions are used to reposition the file pointer (get and put
pointers) for input and output operations, respectively.
Q.9 What is used to move the file pointer to start of a file?
Ans. To move the file pointer to the start of a file, you use the seekg() function with an offset of
0 from the beginning (std::ios::beg).
Q.10 What is Stream Class in C++?
Ans. In C++, a stream class (std::ios, std::istream, std::ostream, std::fstream, etc.) represents an
abstract base class for input (istream), output (ostream), and file stream (fstream)
operations. These classes provide functionality to read from and write to streams of data,
including files, standard input/output devices, and memory buffers.