OOP C++ Assignment
OOP C++ Assignment
SEMESTER II
SET – (I)
Question No.
1. Describe the various data types available in c++ ?
ANS.
A number of data types are available in C++, a statically-typed general-purpose programming
language, to handle various forms of data. These data types fall into three general categories: user-
defined, derived, and built-in (primitive).
❖ User defined data types
1. Structure
• used to unify many variable types under a common name.
• syntax: struct StructureName {
type1 member1;
type2 member2; // ...};
2. Classes
• Like structures, but with private, restricted, and public access controls.
• class ClassName {
private:
type1 member1;
type2 member2; // ...
public: // Member functions};
3. Unions
• Like structures, but with every member having the same address in memory.
• union UnionName {
type1 member1;
type2 member2; // ...};
4. Enumerations
• used to define a variable to which one of several preset values can be assigned.
• enum EnumName { value1, value2, value3 };
❖ Derived data types
1. Arrays
• a group of identically typed components kept in close proximity in memory.
• syntax : type arrayName[arraySize];
2. Pointers
• Variables that hold another variable's address.
• type* pointerName; is the syntax.
3. References
• Another variable's alias.
• Syntax is the type&referenceName = existingvariable;
4. Function type
• Show functions that may take parameters and return a particular type.
• returnType functionName(parameterType1, parameterType2) is the syntax used.
SET – (II)
Question No.
4. Define exception. Define exception handling mechanism.
ANS.
➢ Exception: An event that interferes with a program's usual execution flow is called an exception.
Errors such as faulty input, unavailable resources, or other unforeseen circumstances are typically the
cause. The programme may respond to these fault scenarios without crashing suddenly thanks to
exceptions, which offer a mechanism to treat them gently.
➢ Exception handling mechanism: A method for identifying, managing, and recovering from
exceptions is called exception handling. This method in C++ enables you to create programmes that
are more resilient and fault-tolerant. To handle exceptions, a number of keywords and structures are
used:
1. Try: A code segment that allows for exceptions. It has code that has the potential to throw an
exception.
2. Catch: A section of code meant to manage exceptions. The exceptions thrown by the try block are
caught and handled by it.
3. Throw: Indicates the presence of an incorrect condition by throwing an exception.
Exception handling in C++
Basic syntax:
try {
catch (exception_type1 e1)
catch (exception_type2 e2)
}
Let's look at an example where a division by zero exception is handled.
#include <iostream>
#include <stdexcept>
double divide(int numerator, int denominator) {
if (denominator == 0) {
throw std::runtime_error("Division by zero error"); }
return static_cast<double>(numerator) / denominator; }
int main() {
int num1, num2;
std::cout << "Enter two integers: ";
std::cin >> num1 >> num2;
try {
double result = divide(num1, num2);
std::cout << "Result: " << result << std::endl; }
catch (const std::runtime_error &e) {
std::cerr << "Error: " << e.what() << std::endl; }
return 0;}
In this example
• The main function consists of a try block that executes the divide function;
• If an exception is produced, the catch block catches it and outputs an error message.
• The divide function checks if the denominator is zero and throws a runtime error if it is.
1. Making Exceptions:
• To indicate the occurrence of an exceptional condition, use the throw keyword.
2. Exceptions for Catching:
• To define a block of code that handles the exception, use the catch keyword.
• Exceptions can be caught using a value, reference, or pointer.
3. Several Catch Blocks:
• To handle various kinds of exceptions, you can have more than one catch block.
4. Custom Exceptions:
• By deriving from std::exception or any of its derived classes, you can define your own exception
classes.
5. Standard Exceptions:
• A standard library of exceptions described in is provided by C++.
• std::runtime_error, std::logic_error, std::out_of_range, and other exceptions are frequently
encountered.
Advantages of Exceptional Management
Error Detection: Offers a transparent method for identifying errors as soon as they happen.
Error-Handling Code Separation: This makes the programme easier to comprehend and maintain by
separating the error-handling code from the primary logic.
Resource management: Assures that resources, such as file handles and memory, are appropriately
relinquished in the event of a mistake.
Sturdy Programmes: Increases the program's stability and dependability by offering an organised
method for managing unforeseen circumstances.
C++'s sophisticated exception handling functionality enables programmers to handle mistakes and
exceptional conditions in an organised and effective way. Try, catch, and throw are useful programming
constructs that help you create resilient and fault-tolerant applications that can manage unforeseen
circumstances with grace.
Question No.
5. List and explain the STL components.
ANS.
A robust library that offers a collection of common classes and methods for data structures and
algorithms is the Standard Template Library (STL) in C++. Four general categories can be used to
group STL components: containers, algorithms, iterators, and functors. An outline of each part and
its function in the STL is provided below:
1. Container
Data structures called containers are used to hold groups of items. They offer member functions to
access and manipulate the components, and they oversee the storage area for their elements.
Container Types:
➢ Order Containers: Preserve the elements' order.
• vector: An elastic array with self-adjusting dimensions.
• deque: A double-ended queue with two possible endpoints for insertion and deletion.
• list: A bidirectionally traversable double linked list.
➢ Associative Containers: To arrange and control the elements, use keys.
• set: A group of distinct components arranged according to value.
• Multisets: Multisets enable duplicate elements and are similar to sets.
• map: An enumeration of distinct key-value pairs arranged according to their keys.
• multimap: A map-like structure that permits duplicate keys.
➢ Unordered Containers: The elements should not be kept in order.
• Unordered set: A grouping of distinct components without a set hierarchy.
Identical to an unordered_set, but allowing duplicate elements is the unsegmented_multiset.
• Unordered_map: An arbitrary set of key-value pairings with a single key in each pair.
• Unsorted_multimap: This type of map resembles an unordered_map but permits duplicate keys.
➢ Container Adapters: Adjust the current containers' interface.
• stack: Modifies a container to allow access based on Last In First Out (LIFO).
• queue: Modifies a container so that access is granted FIFO (First In First Out).
• priority_queue: Modifies a container to enable access based on priority, accessing the element
with the highest priority first.
2. Algorithm
A set of functions for carrying out operations on containers are called algorithms, and they can be
used to do a variety of tasks, such as sorting, counting, searching, and modifying items.
common algorithms
➢ Sequence operations that do not modify: Don't change the container's contents.
• For each: A function is applied to a set of elements.
• find: Locates a value's first instance within a range.
• count: Counts how many times a value appears inside a range.
➢ Changing the way sequence operations are performed: Modify the container's contents.
• copy: Transfers elements between ranges.
• transform: Gives each element a function, then saves the outcome.
• replace: Changes a value's occurrences to another value.
➢ Sorting and associated processes:
• sort: Assigns items to a higher or lower order.
• stable_sort: Arranges items in a way that maintains their relative order.
• partial_sort: Sorts the range's first section.
➢ Operational sets:
• Combines two sorted ranges into one.
• comprises: determines whether every element in one sorted range is present in another sorted
range.
• set_union: Determines how two sorted ranges are united.
3. Iterators:
Iterators offer a method of sequentially accessing container elements without disclosing the
underlying representation. They traverse containers and serve as pointers.
➢ Different Iterator Types:
• Single-pass, read-only input iterators are available.
• Single-pass, write-only output iterators.
• Forward Iterators: Multi-pass, read/write access.
• Bidirectional Iterators: traversing both forward and backward.
• Random Access Iterators: Like pointers, they provide direct access to any element.
4. Functors (function objects):
Class instances that override the operator() are called functors, and they are objects that can be used
as if they were functions or function pointers.
➢ Functor Use:
• State can be stored by functors.
• Algorithms may accept them as arguments.
• They have the ability to encapsulate tasks that must be completed on container items.
A complete framework for interacting with data structures and carrying out different operations on them is
offered by the STL components, which include containers, algorithms, iterators, and functors. These
elements are a potent tool for C++ programmers since they are made to be adaptable, effective, and simple
to utilise.
Question No.
6. Explain a type of methods to open a file.
ANS.
The header's Standard Library classes in C++ can be used to open and edit files. These classes are
fstream (file stream for both input and output), ofstream (output file stream), and ifstream (input file
stream). Using the class constructors and the open member function are the two main ways to open a
file. You can choose how the file should be opened with flexibility using either of these approaches.
1. Using the ‘open’ member function:
One flexible method for opening files is the open member function. Objects with the types ifstream,
ofstream, and fstream can be used with this function. The file name and mode in which the file shall
be opened can be specified.
void open(const char* filename, ios_base::openmode mode = ios_base::in | ios_base::out);
➢ Modes of File Opening:
• std::ios::in: By default, ifstream opens for reading.
• std::ios::out: By default, ofstream is open for writing.
• Std::ios::binary: In binary mode, open.
• Std::ios::app: All output procedures are carried out at the end of the file; it is open for
appending.
• Std::ios::ate: Open the file right away and work your way through it.
• std::ios::trunc: The file's contents are shortened if it already exists.
• Std::ios::in Std::ios::out: Both reading and writing are allowed (fstream default)
➢ Ifstream constructor
• The following sentence adds infile to the data for reading (input) and declares it as an
ifstream object.
• Iftream in file("data"); // only input
The programme may contain the following statements:
outfile\\ "total"; outfile\\ sum; infile\\ number; infile \\ string;
• #includeiostream.h> #includefstream.h>
// Programme to create file with one constructor
{ofstream outf(" file1"); int main(); // joins ifile1 and outf
cout\\ "Type the item name here:";
char name[30];
// copy the name from the keyboard to the file called file1.
cin>> name;
float cost; outf \\ name
\\ "\n"; cout \\ "Enter item cost:"; cin>>
// connect file named file1 to inf inf >> name;
// read name from file1 inf >> cost;
// write to file file1 outf.close();
// disconnect file named file1 from outf ifstream inf("file1");
// input the value of cost outf \\ cost \\ "\n";
"" is output by cout; "Item name:" is output by cout; "Item cost:" is output by cout;
inf.close(); //disconnect file named file1 from inf
return 0;}
➢ ofstream constructor
• To manage the stream using the appropriate class, create a file stream object.
• In other words, utilise ofstream classes to build the input and output streams, respectively.
• First, initialise the object with any chosen filename.
• The following statement, for instance, opens the filename "results" for output:
outfile("results"); ofstream; //only output
• The output stream is managed by the outfile, which is constructed as an ofstream object.
• You can use any acceptable C++ name as this object. This statement also opens the "results"
file. and attaching it to the output stream outfile as a result
fout<<"USA \n";
fout<<"UK \n";
fout.close(); //disconnect "country"
fout.open("capital"); //disconnect "capital";
fout.<<"DELHI\n";
fout<<"WASHINGTON\n";
fout<<"LONDON\n";
four.close();
cons tint N=80; // line size
char line[N];
ifstream fin;
fin.open("country"); //join "country" with it