0% found this document useful (0 votes)
72 views101 pages

OOP Lab Manual

9ucyycx6 c7

Uploaded by

artisthiphop2
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
72 views101 pages

OOP Lab Manual

9ucyycx6 c7

Uploaded by

artisthiphop2
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 101

LAB MANUAL

Lab Name : Object Oriented Programming Lab

Lab Code : 3CS4-22

Branch : Computer Science & Engineering

Year : II Year/III Semester

Arya Institute of Engineering


Technology & Management

Department of Computer Science & Engineering


(Rajasthan Technical University, KOTA)
TABLE OF CONTENTS

1. Syllabus

2. List of Experiments

3. Do’s and Don’ts

4. Instruction to the students

5. Programs Education Objective and Outcomes

6. Course Outcomes and Mapping

7. Experiments with Viva Questions


SYLLABUS
3CS4-22 : Object Oriented Programming Lab

Credit-1.5 Max. Marks : 100 (IA:60, ETE:40) 0L+0T+3P

SN Experiment as per RTU

1 Understand the basics of C++ library, variables, data input-output.


2 C++ program using with the concept of structures.
3 Implement class and object concepts and function overloading.
4 Write programs to understand dynamic memory allocation and array of objects.
5 Program to understand different types of constructors and destructor.

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

Understand the basics of C++ library, variables, data input-output.


1. WAP to find to sum of n natural numbers
Exp:- 1
2. WAP to understand concept of scope resolution operator.
Viva Question
C++ program using with the concept of structures.
1. WAP to implement calculator using structure.
Exp:- 2
2. WAP TO store student information.
Viva Question
Implement class and object concepts and function overloading.
1. Write a program to write absolute value using function overloading
Exp:- 3
2. WAP to perform implement function overloading in class
Viva Question
Write programs to understand dynamic memory allocation and array of objects.
1. WAP to illustrate dynamic allocation and de-allocation of memory using new and
Exp:- 4 delete.
2. WAP to dynamic memory allocation of objects.
Viva Question
Program to understand different types of constructors and destructor.
1. WAP to implement a class without constructor.
Exp: - 5 2. WAP to implement a class with zero argument constructors.
3. WAP to implement a class with parameterized constructor.
Viva Question
Implement friend function to access private data of a class and usage of this pointer.
1. WAP to calculate cube of a number using friend function.
Exp:- 6 2. WAP for swapping using friend function.
3. WAP to understand concept of this pointer.
Viva Question
Write programs to understand the usage of constant data member and member Function,
static data member and member function in a class.
Exp:- 7 1. WAP to implement static data function.
2. WAP to implement static data member.
3. WAP to implement constant data member.
Viva Question
Implement different types of inheritance, function overriding and virtual function
1. WAP to perform inheritance in different classes?
Exp:- 8
2. WAP to understand concept of function overriding.
Viva Question
Implement Operator overloading concepts.
1. WAP to add two complex numbers class object by overloading + ?
Exp:- 9 2. WAP to overload decrement operator.

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.

2. Read the manual carefully before starting the 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.

5. Get your readings checked by the teacher.

6. Apparatus must be handled carefully.

7. Maintain strict discipline.

8. Keep your mobile phone switched off or in vibration mode.

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.

2. Do not overcrowd the tables.

3. Do not tamper with equipments.

4. Do not leave the without permission from the teacher.


Instructions to the Students
General Instructions

 Maintain separate observation copy for each laboratory.


 Observations or readings should be taken only in the observation copy.
 Get the readings counter signed by the faculty after the completion of the experiment.
 Maintain Index column in the observation copy and get the signature of the faculty before leaving the lab.

Before Entering the Lab

 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.

When Working in the Lab

 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.

Before Leaving the Lab

 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

S. No LIST OF PROGRAM EDUCATION OBJECTIVES

Graduate students will have thorough knowledge in science and engineering


PEO-1 disciplines and have broad-based education in areas of computer science, including
hardware, software learning in the structural form of course and curriculum.

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.

Graduates will be trained with good engineering breadth so as to comprehend,


PEO-3 analyze, design, and create novel products and solutions for real-life problems and as
per industry requirements by bridging extra certification courses.

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.

To develop the academic environment and pursue excellence in leadership,


teamwork, and skills for lifelong learning needed to pursue a successful professional
PEO-5
career through structured learning, independent self-studies, projects, industrial
training, seminars, and internships.
Program Outcomes
List of Program Outcomes
Engineering Knowledge: Apply knowledge of mathematics and science, with
PO-1 fundamentals of Computer Science & Engineering to be able to solve complex
engineering problems related to CSE.
Problem Analysis: Identify, Formulate, review research literature and analyze
complex engineering problems related to CSE and reaching substantiated
PO-2
conclusions using first principles of mathematics, natural sciences and
engineering sciences.
Design/Development of solutions: Design solutions for complex engineering
problems related to CSE and design system components or processes that meet
PO-3
the specified needs with appropriate consideration for the public health and safety
and the cultural societal and environmental considerations.
Conduct Investigations of Complex problems: Use research–based knowledge
PO-4 and research methods including design of experiments, analysis and interpretation
of data, and synthesis of the information to provide valid conclusions.
Modern Tool Usage: Create, Select and apply appropriate techniques, resources
and modern engineering and IT tools including prediction and modeling to
PO-5
computer science related complex engineering activities with an understanding of
the limitations.
The Engineer and Society: Apply Reasoning informed by the contextual
PO-6 knowledge to assess societal, health, safety, legal and cultural issues and the
consequent responsibilities relevant to the CSE professional engineering practice.
Environment and Sustainability: Understand the impact of the CSE
PO-7 professional engineering solutions in societal and environmental contexts and
demonstrate the knowledge of, and need for sustainable development.
Ethics: Apply Ethical Principles and commit to professional ethics and
PO-8
responsibilities and norms of the engineering practice.
Individual and Team Work: Function effectively as an individual and as a
PO-9
member or leader in diverse teams and in multidisciplinary Settings.
Communication: Communicate effectively on complex engineering activities
with the engineering community and with society at large such as able to
PO-10
comprehend and with write effective reports and design documentation, make
effective presentations and give and receive clear instructions.
Project Management and Finance: Demonstrate knowledge and understanding
of the engineering management principles and apply these to one’s own work, as
PO-11
a member and leader in a team, to manage projects and in multi disciplinary
environments.
Life-Long Learning: Recognize the need for and have the preparation and ability
PO-12 to engage in independent and life-long learning the broadest context of
technological change.
Course Outcomes &PSO
List of Course Outcomes
CO 1: Create and explain Basic C++ Programs using i/o variables and
structures.

CO 2: Apply object-oriented programming concepts using class and objects

CO 3: Design and assess the classes for code reuse

CO 4: Analyse and Apply the generic classes concepts in programming


problem

CO 5: Illustrate and evaluate the file Input Output mechanisms

List of Program Specific Outcomes (PSO)


Knowledge Enhancement in Computing: The ability to interpret the foundation
and strategy of hardware and software of computer systems. Graduates can solve
PSO-1 the problems in the areas related to algorithms, multimedia, data analytics, cloud
computing, human computer interface, robotics, artificial intelligence and
networking for efficient design of computer systems.
Software Design and Development: The ability to understand the software
development lifecycle and methodologies of software systems. Graduate will
PSO-2 learn competent skills and knowledge of software design process. Graduate will
be acquaintance to practical proficiency with a broad area of programming
concepts.
MAPPING OF COURSE OBJECTIVE WITH PROGRAM OUTCOMES

PROGRAM OUTCOMES PSO’s


COURSE
PO- PO- PO- PO- PO- PO- PO- PO- PO- PO- PO- PO- PSO- PSO-
OUTCOMES
1 2 3 4 5 6 7 8 9 10 11 12 1 2
CO-1 2 - - - 2 - - - - 2 - - 2 2
CO-2 2 - - 2 - - - - 2 - - 2 2
CO-3 2 2 - - 2 - - - - 2 - - 2 2
CO-4 2 2 - - 2 - - - - 2 - - 2 2

CO-5 2 2 - - 2 - - - - 2 - - 2 2

Note: Correlation levels 1, 2 or 3 as defined below:


1: Slight (Low) 2: Moderate (Medium) 3: Substantial (High)
Covered Beyond the Syllabus/Additional Contents:
Along with the above stated topics allotted in the syllabus we covered following topics in this subject which are important
for the student:

Sr.
Beyond Syllabus topic Source
sNo.
File Handling in C++ How to program C++,Dietel,Pearson
1

Text Books /Reference Books:

Text/
S.N. Author Name Book Title Publisher
Reference

How to program
1 Dietel Pearson Reference
C++

2 K. R. Venugopal Mastering C++ TMH Text

Object Oriented
3 Robert Lafore Programming in Pearson Reference
C++
Experiment: 1

Objective: Understand the basics of C++ library, variables, data input-output.


Theory: C++ is used by programmers to create computer software. It is used to create general systems software,
drivers for various computer devices, software for servers and software for specific applications and also widely
used in the creation of video games.

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.

Object-Oriented Programming and C++


C++ supports object-oriented programming (OOP), with four major principles of object-oriented development:

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:

DATA TYPE SIZE (IN BYTES) RANGE

short int 2 -32,768 to 32,767

unsigned short int 2 0 to 65,535

unsigned int 4 0 to 4,294,967,295

Int 4 -2,147,483,648 to 2,147,483,647

long int 4 -2,147,483,648 to 2,147,483,647


unsigned long int 4 0 to 4,294,967,295

long long int 8 -(2^63) to (2^63)-1

unsigned long long int 8 0 to 18,446,744,073,709,551,615

signed char 1 -128 to 127

unsigned char 1 0 to 255

Float 4

Double 8

long double 12

wchar_t 2 or 4 1 wide character


(i) Write a program to sum of n natural numbers?

Source Code:
#include <iostream>
using namespace std;

int main()
{
int n, sum = 0;

cout << "Enter a positive integer: ";


cin >> n;

for (int i = 1; i <= n; ++i) {


sum += i;
}

cout << "Sum = " << sum;


return 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:

Q.1 What is diff between c and c++?

Ans. C is often used for system-level programming, while C++ is favored for applications that benefit
from OOP and complex data structures.

Q.2 What is class?

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.

Q.3 What is object?

Ans. An object is an instance of a class in object-oriented programming (OOP). It represents a specific


entity that combines both data (attributes) and behaviors (methods) defined by its class.

Q.4 What is object oriented programming language?

Ans. An object-oriented programming (OOP) language is a programming language that is based on


the concept of "objects," which can encapsulate data and behavior.

Q.5 What is procedural language?

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.

Q.6 What is purpose of data hiding?

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).

Q.7 What do you mean by modularity?

Ans. Modularity is a design principle in software development that emphasizes breaking down a
program into smaller, manageable, and independent components or modules.

Elaborate the term cin and cout.


Q.8

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.

rollno, name, age, and marks are structure members.

Declaring Variables of Type struct

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;
}

Alternate method of declaring variables of type struct:


struct Student
{
int rollno, age;
char name[80];
float marks;
} s1, s3;

Accessing of data members


The accessing of data members is done by using the following format:
structure variable.member name
for example
cin >> s1.rollno >> s1.age >> s1.name >> s1.marks;

Initialization of structure variable


Initialization is done at the time of declaration of a variable. For example
Student s2 = {100, 17, "Aniket", 92};
Structure variable in assignment statement

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;

cout << "\nDisplaying Information," << endl;


cout << "Name: " << s.name << endl;
cout << "Roll: " << s.roll << endl;
cout << "Marks: " << s.marks << endl;
return 0;
}

Output:
Sample viva questions:

Q.1 How to create a structure?

Ans. struct StructureName {


DataType member1;
DataType member2;
// Add more members as needed
};
Q.2 How to declare structure variable?

Ans. struct Person {


std::string name; // Member of type string
int age; // Member of type int
};
Person person1;
Q.3 How to initialize structure member?
Ans. Dot Operator: Use after declaring a variable to assign values.
Initializer List: Initialize at the time of declaration (C++11 and later).
Aggregate Initialization: Common in C for initializing multiple membe
Q.4 How to access structure element?
Ans. Dot Operator (.): Use it for accessing members of a structure variable.
Arrow Operator (->): Use it for accessing members of a structure via a pointer.
Q.5 What is designated initialization?

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. An array of structures is a collection of structure


Q.7 What is structure pointer?

Ans. A structure pointer is a pointer that points to a structure variable.


Q.8 What will be used when terminating a 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

Objective: Implement class and object concepts and function overloading.

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.

Function Overloading in C++


You can have multiple definitions for the same function name in the same scope. The definition of the function
must differ from each other by the types and/or the number of arguments in the argument list. You cannot
overload function declarations that differ only by return type.
If any class have multiple functions with same names but different parameters then they are said to be overloaded.
Function overloading allows you to use the same name for different functions, to perform, either same or different
functions in the same class.
Function overloading is usually used to enhance the readability of the program. If you have to perform one single
operation but with different number or types of arguments, then you can simply overload the function.

Ways to overload a function

1. By changing number of Arguments.


2. By having different types of argument.
(i) Write a program to write absolute value using function overloading?

Source Code:

#include <iostream>
using namespace std;

// function with float type parameter


float absolute(float var){
if (var < 0.0)
var = -var;
return var;
}

// function with int type parameter


int absolute(int var) {
if (var < 0)
var = -var;
return var;
}

int main() {

// call function with int type parameter


cout << "Absolute value of -5 = " << absolute(-5) << endl;

// call function with float type parameter


cout << "Absolute value of 5.5 = " << absolute(5.5f) << endl;
return 0;
}
Output:
(ii) WAP to implement function overloading in class

#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;

// Call print to print integer


pd.print(5);

// Call print to print float


pd.print(500.263);

// Call print to print character


pd.print("Hello C++");

return 0;
}

Output:
Sample viva questions:

Q.1 What is function overloading?give an example in c++.

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. Yes, you can declare a member function as private in C++.


Q.8 How to skip some of the array elements in c++?

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?

Ans. semicolon (;)


EXPERIMENT: 4

Objective: Write programs to understand dynamic memory allocation and array of objects.

Theory:

new and delete operators in C++ for dynamic memory

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).

What are applications?


 One use of dynamically allocated memory is to allocate memory of variable size which is not possible with
compiler allocated memory except variable length arrays.
 The most important use is flexibility provided to programmers. We are free to allocate and deallocate
memory whenever we need and whenever we don’t need anymore. There are many cases where this
flexibility helps. Examples of such cases are Linked List, Tree, etc.

How is it different from memory allocated to normal variables?


For normal variables like “int a”, “char str[10]”, etc, memory is automatically allocated and deallocated. For
dynamically allocated memory like “int *p = new int[10]”, it is programmers responsibility to deallocate
memory when no longer needed. If programmer doesn’t deallocate memory, it causes memory leak (memory is
not deallocated until program terminates).

How is memory allocated/deallocated in C++?


C uses malloc() and calloc() function to allocate memory dynamically at run time and uses free() function to
free dynamically allocated memory. C++ supports these functions and also has two
operators new and delete that perform the task of allocating and freeing the memory in a better and easier way.

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;

// Request memory for the variable


// using new operator
p = new(nothrow) int;
if (!p)
cout << "allocation of memory failed\n";
else
{
// Store value at allocated address
*p = 29;
cout << "Value of p: " << *p << endl;
}

// Request block of memory


// using new operator
float *r = new float(75.25);

cout << "Value of r: " << *r << endl;

// Request block of memory of size n


int n = 5;
int *q = new(nothrow) int[n];

if (!q)
cout << "allocation of memory failed\n";
else
{
for (int i = 0; i < n; i++)
q[i] = i+1;

cout << "Value store in block of memory: ";


for (int i = 0; i < n; i++)
cout << q[i] << " ";
}

// freed the allocated memory


delete p;
delete r;

// freed the block of allocated memory


delete[] q;

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:

Q.1 Explain the use of new and delete operator.

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. Memory allocation in C/C++ can be static, stack-based, or dynamic (heap-based)


Q.6 What is static and dynamic memory allocation?
Ans. Static memory allocation: Memory is allocated at compile-time and cannot be resized
during runtime. Examples include global variables and static variables.
Dynamic memory allocation: Memory is allocated at runtime and can be resized as
needed. Examples include memory allocated using new (C++) or malloc (C).
Q.7 What is dynamic memory fragmentation?

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

Objective: Program to understand different types of constructors and destructor.

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.

This can be done in two ways:

 By calling constructor explicitly


 By calling constructor implicitly
Special characteristics of Constructors:

 They should be declared in the public section


 They do not have any return type, not even void
 They get automatically invoked when the objects are created
 They cannot be inherited though derived class can call the base class constructor
 Like other functions, they can have default arguments
 You cannot refer to their address
 Constructors cannot be virtual

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:

class-name (class-name &)

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() {

// initialize private variables


length = 5.5;

cout << "Creating a wall." << endl;


cout << "Length = " << length << endl;
}
};
int main() {

// 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() {

// initialize private variables


length = 5.5;

cout << "Creating a wall." << endl;


cout << "Length = " << length << endl;
}
};

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);

cout << "Area of Wall 1: " << wall1.calculateArea() << endl;


cout << "Area of Wall 2: " << wall2.calculateArea() << endl;

return 0;
}
Output:
Sample viva questions:

Q.1 What is constructor?

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.

This’ pointer in C++

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;

/* local variable is same as a member's name */


class Test
{
private:
int x;
public:
void setX (int x)
{
// The 'this' pointer is used to retrieve the object's x
// hidden by the local variable 'x'
this->x = x;
}
void print() { cout << "x = " << x << endl; }
};

int main()
{
Test obj;
int x = 20;
obj.setX(x);
obj.print();
return 0;
}

Output:
Sample viva questions:

Q.1 What is friend function?

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?

C++ static data member

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

static data_type member_name;


(i) WAP to implement static data function.

#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:

Q.1 Which keyword should be used to declare static variable?

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.

Theory: Inheritance in C++

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

inherited from vehicle class:


Using inheritance, we have to write the functions only one time instead of three times as we have inherited rest
of the three classes from base class(Vehicle).
Implementing inheritance in C++: For creating a sub-class which is inherited from the base class we have to
follow the below syntax.
Syntax:
class subclass_name : access_mode base_class_name
{
//body of subclass
};
Here, subclass_name is the name of the sub class, access_mode is the mode in which you want to inherit this
sub class for example: public, private etc. and base_class_name is the name of the base class from which you
want to inherit the sub class.
Note: A derived class doesn’t inherit access to private data members. However, it does inherit a full parent
object, which contains any private members which that class declares.
Output:
Child id is 7
Parent id is 91
In the above program the ‘Child’ class is publicly inherited from the ‘Parent’ class so the public data members
of the class ‘Parent’ will also be inherited by the class ‘Child’.
Modes of Inheritance
1. Public mode: If we derive a sub class from a public base class. Then the public member of the base class
will become public in the derived class and protected members of the base class will become protected in
derived class.
2. Protected mode: If we derive a sub class from a Protected base class. Then both public member and
protected members of the base class will become protected in derived class.
3. Private mode: If we derive a sub class from a Private base class. Then both public member and protected
members of the base class will become Private in derived class.
Note : The private members in the base class cannot be directly accessed in the derived class, while protected
members can be directly accessed. For example, Classes B, C and D all contain the variables x, y and z in below
example. It is just question of access.

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:

Types of Inheritance in C++


1. Single Inheritance: In single inheritance, a class is allowed to inherit from only one class.
i.e. one sub class is inherited by one base class only
2. Multiple Inheritance: Multiple Inheritance is a feature of C++ where a class can inherit from more than
one classes. i.e one sub class is inherited from more than one base classes.

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.

Virtual Function in C++

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:

Q.1 What is inheritance?

Ans. Inheritance is a fundamental feature of object-oriented programming where a class


(known as the derived or child class) can inherit attributes and behaviors from
another class (known as the base or parent class). It promotes code reusability and
allows the creation of hierarchical classifications.
Q.2 What are the diff forms of inheritance?
Ans. Single Inheritance: A derived class inherits from only one base class.
Multiple Inheritance: A derived class inherits from multiple base classes.
Multilevel Inheritance: A derived class serves as the base class for another
derived class, creating a chain of inheritance.
Hierarchical Inheritance: Multiple derived classes inherit from a single base
class.
Hybrid (or Virtual) Inheritance: Combination of multiple and multilevel
inheritance.
Q.3 What is multi level inheritance?

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. Hybrid or virtual inheritance is a combination of multiple and multilevel inheritance.


It allows inheriting from multiple base classes through a multilevel inheritance chain.
Q.7 What is hierarchical 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.

Q.9 What is virtual function?

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

Objective: Implement Operator overloading concepts.

Theory:

C++ Operator Overloading


The meaning of an operator is always same for variable of basic types like: int, float, double etc. For example: To add two
integers, + operator is used.

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.

How to overload operators in C++ programming?

To overload an operator, a special operator function is defined inside the class as:

class className
{
... .. ...
public
returnType operator symbol (arguments)
{
... .. ...
}
... .. ...
};

 Here, returnType is the return type of the function.


 The returnType of the function is followed by operator keyword.
 Symbol is the operator symbol you want to overload. Like: +, <, -, ++
 You can pass arguments to the operator function in similar way as functions.
(i) Write a program to add two complex numbers class object by overloading + ?

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;}

// This is automatically called when '+' is used with


// between two Complex objects
Complex operator + (Complex const &obj) {
Complex res;
res.real = real + obj.real;
res.imag = imag + obj.imag;
return res;
}
void print() { cout << real << " + i" << imag << endl; }
};

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){}

void operator --()


{
count = count-1;
}
void Display() { cout<<"Count: "<<count; }
};

int main()
{
Test t;

--t;
t.Display();
return 0;
}

Output:
Sample viva questions:

Q.1 What is operator overloading?

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.

Q.10 Can we change the basic meaning of operator?

Ans. Yes, operator overloading allows us to change the behavior or meaning of an operator when
applied to user-defined types.
EXPERIMENT: 10

Objective Write programs to understand function template and class template.

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.

The concept of templates can be used in two different ways:

 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.

How to declare a function template?

A function template starts with the keyword template followed by template parameter/s inside < > which is
followed by function declaration.

template <class T>


T someFunction(T arg)
{
... .. ...
}
In the above code, T is a template argument that accepts different data types (int, float), and class is a keyword.
Class Templates

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.

How to create a class template object?

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;

cout << "Enter two integers:\n";


cin >> i1 >> i2;
cout << Large(i1, i2) <<" is larger." << endl;

cout << "\nEnter two floating-point numbers:\n";


cin >> f1 >> f2;
cout << Large(f1, f2) <<" is larger." << endl;

cout << "\nEnter two characters:\n";


cin >> c1 >> c2;
cout << Large(c1, c2) << " has larger ASCII value.";

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:

Q.1 What are templates?

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?

Ans. template <typename T> T add(T a, T b) { return a + b; }

Q.9 What is macro?


Ans. A macro in 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.
Q.10 Difference between templates and macro?
Ans. Templates: Templates are type-safe and can work with any data type. They are
processed by the compiler and support type checking and error detection at compile-time.
Templates also support function overloading and specialization.
Macro: Macros are simple textual replacements performed by the preprocessor before
compilation. They are not type-safe and do not perform type checking or error detection.
Macros do not support function overloading and cannot be specialized based on data types.
EXPERIMENT: 11

Objective: Write programs to understand exception handling techniques.

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;

if(!(p>=0 && p<=100)) //checking that marks entered is valid or not;


{
throw(p); //using throw block to transfer error to catch block;
}
cout<<"Enter chemistry marks : ";
cin>>c;

if(!(c>=0 && c<=100)) //checking that marks entered is valid or not;


{
throw(c); //using throw block to transfer error to catch block;
}

cout<<"Enter mathsmarks : ";


cin>>m;

if(!(m>=0 && m<=100)) //checking that marks entered is valid or not;


{
throw(m); //using throw block to transfer error to catch block;
}
err=0; //if all the conditions are false then value of error variable is 0
}
catch(int e)
{
cout<<"Invalid Marks"<<endl; //Showing error;
err=1; //Changing value of variable to retke input;
}
}while(err); //it takes input until all inputs are valid;
}

Output:
Sample viva questions:

Q.1 What is exception?

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

Objective: Write programs to understand file handling techniques.

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 −

Sr.No Data Type & Description

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.

File Position Pointers


Both istream and ostream provide member functions for repositioning the file-position pointer. These member
functions are seekg ("seek get") for istream and seekp ("seek put") for ostream.

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 );

// position n bytes forward in fileObject


fileObject.seekg( n, ios::cur );

// position n bytes back from end of fileObject


fileObject.seekg( n, ios::end );

// position at end of fileObject


fileObject.seekg( 0, ios::end );
Example:
#include <fstream.h>
#include <iostream.h>
using namespace std;
int main () {
char data[100];
// open a file in write mode.
ofstream outfile;
outfile.open("afile.dat");
cout << "Writing to the file" << endl;
cout << "Enter your name: ";
cin.getline(data, 100);
// write inputted data into the file.
outfile << data << endl;
cout << "Enter your age: ";
cin >> data;
cin.ignore();
// again write inputted data into the file.
outfile << data << endl;
// close the opened file.
outfile.close();
// open a file in read mode.
ifstream infile;
infile.open("afile.dat");
cout << "Reading from the file" << endl;
infile >> data;
// write the data at the screen.
cout << data << endl;
// again read the data from the file and display it.
infile >> data;
cout << data << endl;
// close the opened file.
infile.close();

Output:
Sample viva questions:

Q.1 Which header file is required to use file I/O operations?

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.

You might also like