0% found this document useful (0 votes)
6 views26 pages

OOP Imp

Uploaded by

vaibhav kore
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)
6 views26 pages

OOP Imp

Uploaded by

vaibhav kore
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/ 26

1) Explain line command argument in C++. Write a program to explain it.

Command Line Arguments are values or parameters passed to a program through the command line or
terminal when it is executed. They allow users to customize program behaviour or pass data to a program
without modifying the code.
#include <iostream>

using namespace std;

int main(int argc, char* argv[]) {

if (argc < 2) {

cout << "Usage: " << argv[0] << " <name>" << endl;

return 1;

cout << "Program Name: " << argv[0] << endl;

cout << "Hello, " << argv[1] << "!" << endl;

return 0;


argc is an integer representing the number of command-line arguments.

argv is an array of strings (char*), where each element is a pointer to a string containing one of
the command-line arguments.
• argv[0] is the program name.
• argv[1] is the first command-line argument, argv[2] is the second, and so on.
Before running the program, compile it using a C++ compiler. For example, if the program is saved in a
file named CommandLineArgs.cpp, you can compile it with a command like:
1) g++ CommandLineArgs.cpp -o CommandLineArgs
2) ./CommandLineArgs John
3) Program Name: ./CommandLineArgs
Hello, John!

2) What is generic programming? How is it implemented in C++.


Generic Programming is a programming paradigm that allows programmer to write a general
algorithm which will work with all data types.
Templates provide a way to write generic code that works with different data types.
Function Templates: Function templates allow you to define a template for a function without
specifying the types of its parameters.
#include <iostream>

using namespace std;

template <typename T> // Function template to add two values of any type

T add(T a, T b) {

return a + b;

}
int main() {

float num1, num2; // User input for two float numbers

cout << "Enter the first float number: ";

cin >> num1;

cout << "Enter the second float number: ";

cin >> num2;

float result = add(num1, num2); // Using the template function to add two float numbers

cout << "Sum of " << num1 << " and " << num2 << " is: " << result << endl;

return 0;

Class Templates: They allow you to create a template for a class without specifying the types of its
members or methods.
#include <iostream>

using namespace std;

template <typename T1, typename T2> // Class template for a simple Pair

class Pair {

public:

T1 first;

T2 second;

Pair(T1 f, T2 s) : first(f), second(s) {}

};

int main() {

Pair<int, double> myPair(5, 3.14); // Creating a Pair of int and double

cout << "Pair: " << myPair.first << ", " << myPair.second << endl;

return 0;

STL (Standard Template Library): The Standard Template Library is a collection of generic classes
and functions in C++. It provides generic algorithms, containers, iterators, and other components that
can be used with different data types.For example, the std::vector class is a template class that can
hold elements of any type.

3) What are cin and cout ? Explain I/O stream.


cin and cout are objects in C++ that are part of the Input/Output (I/O) stream library, which is
designed for handling input and output operations. These objects are instances of the istream and
ostream classes, respectively, and are associated with the standard input and output streams.
• cout (character output):
• cout is used to output data to the standard output stream (usually the console or terminal).
• It is an instance of the ostream class, which stands for output stream.
• You use << (the insertion operator) with cout to send data to the standard output.
#include <iostream>
using namespace std;
int main() {
cout << "Hello, World!" << endl;
return 0;
}
In this example, "Hello, World!" is sent to the standard output.
• cin (character input):
• cin is used to read data from the standard input stream (usually provided by the user through
the console or terminal).
• It is an instance of the istream class, which stands for input stream.
• You use >> (the extraction operator) with cin to receive data from the standard input.
#include <iostream>
using namespace std;
int main() {
int userInput;
cout << "Enter a number: ";
cin >> userInput;
cout << "You entered: " << userInput << endl;
return 0;
}
• I/O Stream Library:
• The I/O Stream Library in C++ provides a set of classes that handle input and output
operations. The library includes classes like istream (input stream), ostream (output stream),
and their derived classes such as ifstream, ofstream, stringstream, etc.
• The library is designed to be extensible, allowing you to create your own stream classes or
extend existing ones.
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ofstream outputFile("example.txt");
if (outputFile.is_open()) {
outputFile << "This is an example file." << endl;
outputFile.close();
}
return 0;
}
4) What are various functions used to manipulate file pointer.
seekg and seekp (Seek Get and Seek Put):
• seekg is used to move the get pointer (read position) in the file.
• seekp is used to move the put pointer (write position) in the file.
tellg and tellp (Tell Get and Tell Put):
• tellg returns the current position of the get pointer.
• tellp returns the current position of the put pointer.
open and close for Files:
• open is used to open a file, associating it with a file stream.
• close is used to close the file, releasing the associated resources
getline:
• getline is a function in C++ that is used to read a line from an input stream.
eof()
• eof stands for "end of file." It is a condition that occurs when attempting to read from an input
stream (like a file or keyboard input) and reaching the end of the file.
get()
• The get() reads a single character from the input stream.
#include <iostream>
#include <fstream>
using namespace std;
struct Record { // Structure to represent a simple record
int id;
string name;
};

int main() {
ofstream outFile("records.txt"); // Create and write to a text file

if (outFile.is_open()) {
outFile << "1 John Doe" << endl; // Write records to the file
outFile << "2 Jane Smith" << endl;

outFile.close(); // Close the file


} else {
cerr << "Failed to open the file for writing." << endl;
return 1;
}
ifstream inFile("records.txt"); // Open the file for reading

if (inFile.is_open()) {
Record record1; // Read records from the file using getline and get
if (inFile >> record1.id) {
inFile.ignore(); // Ignore the space between id and name
getline(inFile, record1.name);

cout << "Record 1: ID=" << record1.id << ", Name=" << record1.name << endl;
} else {
cerr << "Failed to read record 1." << endl;
inFile.close();
return 1;
}

inFile.seekg(0, ios::beg); // Move the file pointer to the beginning


Record record2; // Read records using read
if (inFile.read(reinterpret_cast<char*>(&record2), sizeof(Record))) {
cout << "Record 2: ID=" << record2.id << ", Name=" << record2.name << endl;

// Display the current position of the get pointer


cout << "Current get pointer position: " << inFile.tellg() << endl;

if (inFile.eof()) { // Check if the end of the file has been reached


cout << "End of file reached." << endl;
}
} else {
cerr << "Failed to read record 2." << endl;
}
inFile.close();
} else {
cerr << "Failed to open the file for reading." << endl;
return 1;
}

return 0;
}
5) Write program to implement map using STL.
#include <iostream>
#include <map>
using namespace std;
int main() {
map<int, string> myMap; // Declare a map with int keys and string values

myMap[1] = "Alice"; // Insert key-value pairs into the map


myMap[2] = "Bob";
myMap[3] = "Charlie";

cout << "Value at key 1: " << myMap[1] << endl; // Access and display values using keys
cout << "Value at key 2: " << myMap[2] << endl;
cout << "Value at key 3: " << myMap[3] << endl;

int keyToFind = 2; // Check if a key exists in the map


if (myMap.find(keyToFind) != myMap.end()) {
cout << "Key " << keyToFind << " exists in the map. Value: " << myMap[keyToFind] << endl;
} else {
cout << "Key " << keyToFind << " does not exist in the map." << endl;
}

cout << "Iterating through the map:" << endl; // Iterate through the map
for (const auto& pair : myMap) {
cout << "Key: " << pair.first << ", Value: " << pair.second << endl;
}

return 0;
}
6) Give advantage and disadvanatage of 1)Vector & 2)List.
std::vector:
Advantages:
• Random Access: Provides fast access to individual elements using indexing (operator[]). It
has constant time complexity for element access.
• Contiguous Memory: The elements in a vector are stored in contiguous memory locations,
which can lead to better cache locality and improved performance for certain operations.
• Dynamic Sizing: Automatically manages memory and can dynamically resize itself when the
number of elements changes. This avoids the need for manual memory management.
• Efficient End Operations: Efficient for adding or removing elements at the end of the vector
(push_back, pop_back), as it doesn't invalidate iterators or references.
Disadvantages:
• Insertion and Deletion: Inserting or deleting elements in the middle of a vector can be
inefficient, as it may require shifting elements to maintain contiguous storage.
• Fixed Capacity: The vector has a fixed capacity that may need to be resized when elements are
added beyond its current capacity, which involves copying elements to a larger memory space.
std::list:
Advantages:
• Dynamic Size: Can efficiently insert and delete elements at any position, as it doesn't require
shifting elements or reallocating memory.
• No Reallocation: Unlike vectors, lists do not need to be reallocated when elements are added
or removed, making insertions and deletions more efficient.
• Iterators Remain Valid: Inserting or deleting elements does not invalidate iterators or
references to other elements in the list.
Disadvantages:
• Sequential Access: Accessing elements sequentially is slower compared to vectors due to the
non-contiguous memory structure.
• Memory Overhead: Each element in the list requires additional memory for pointers,
resulting in higher memory overhead compared to vectors.
• Less Cache Friendly: The non-contiguous nature of a linked list can lead to poorer cache
locality, impacting performance.
• No Random Access: No direct indexing (operator[]) is supported, requiring traversal from
the beginning to reach a specific element.

7) What is stack ? How it is implemented using STL.


A stack is a data structure that follows the Last In, First Out (LIFO) principle. It means that the last
element added to the stack is the first one to be removed. Think of it as a collection of elements with
two main operations: push, which adds an element to the top of the stack, and pop, which removes the
top element.
#include <iostream>
#include <stack>
using namespace std;
int main() {
stack<int> myStack; // Declare a stack of integers
myStack.push(10); // Push elements onto the stack
myStack.push(20);
myStack.push(30);

cout << "Top element: " << myStack.top() << endl; // Display the top element
myStack.pop(); // Pop elements from the stack

cout << "Top element after pop: " << myStack.top() << endl; // Display the new top element

cout << "Is the stack empty? " << (myStack.empty() ? "Yes" : "No") << endl; / / Check if the stack is empty

cout << "Size of the stack: " << myStack.size() << endl; // Size of the stack
return 0;
}
8) What is stream? Explain types of streams available in C++?
In C++, a stream is a sequence of bytes or characters that can be read from or written to.Types of
Streams in C++:
Input Streams (std::istream):
• std::cin: Standard input stream representing the keyboard. It is used for reading input from
the user.
• File Input Streams (std::ifstream): Used for reading from files. You can open a file using
Output Streams (std::ostream):
• std::cout: Standard output stream representing the console. It is used for writing output to
the console.
• String Output Streams (std::ostringstream): Used for writing to strings.
File Streams (std::fstream):
• std::fstream is a bidirectional stream that allows both input and output operations. It can be
used to read from and write to files.
String Streams (std::stringstream):
• std::stringstream is a bidirectional stream that allows both input and output operations on
strings.

8)Write a program to create a file, read & write the record into it. Every record contains
employee name,id & salary. Store and retrieve at least 3 employee data.
#include <iostream>
#include <fstream>
using namespace std;
class Employee {
char Name[20];
int ID;
double salary;
public:
void accept() {
cout << "Enter Name: ";
cin >> Name;
cout << "Enter ID: ";
cin >> ID;
cout << "Enter Salary: ";
cin >> salary;
}
void display() const {
cout << "\nEmployee Information:";
cout << "\nName: " << Name << "\nID: " << ID << "\nSalary: " << salary << "\n";
}
};
int main() {
Employee O[10];
fstream F;
int i, n;
// Open the file in write mode if it exists. If not, create a new file.
F.open("EmployeeRecord.txt", ios::in | ios::out | ios::binary);

cout << "\nEnter the number of employees: "; // Writing records to the file
cin >> n;

cout << "\nEnter details for " << n << " employees:" << endl;
for (i = 0; i < n; ++i) {
cout << "\nEnter details for Employee " << i + 1 << ":" << endl;
O[i].accept();
F.write((char*)&O[i], sizeof(Employee));
}
F.close(); // Close the file

F.open("EmployeeRecord.txt", ios::in | ios::out | ios::binary); // Reopening the file for reading

cout << "\nEmployee Records from File:" << endl; // Reading and displaying records .
for (i = 0; i < n; ++i) {
F.read((char*)&O[i], sizeof(Employee));
O[i].display();
}
F.close();
return 0;
}
9) What is exception? How is exception handled in C++(in case of constructor & destructor)?
Exception in C++:
An exception is an abnormal or unexpected event that occurs during the execution of a program,
disrupting the normal flow of instructions. Exceptions are typically caused by errors, exceptional
conditions, or unforeseen situations that may arise at runtime. Exception Handling in C++:
C++ uses three keywords for exception handling:
• try: The try block encloses a set of statements that may throw an exception.
• catch: The catch block follows the try block and specifies the type of exception it can handle.
If an exception of that type is thrown inside the try block, the corresponding catch block is
executed.
• throw: The throw statement is used to explicitly raise an exception. It is typically used when an
error or exceptional condition is detected.
Exception Handling in Constructors:
• Throwing Exceptions in Constructors:
• Constructors can throw exceptions if they encounter errors during initialization. For example,
if an object's construction requires the allocation of a resource (like memory) and the
allocation fails, the constructor can throw an exception.
class MyClass {
public:
MyClass() {
// Constructor code that may throw an exception
if (someCondition) {
throw std::runtime_error("Error during object construction");
}
}
};
• Handling Exceptions in Constructors:
• If an exception is thrown during the construction of an object, the object's destructor is not
called. Instead, the exception propagates up the call stack, and the client code must handle it.
try {
MyClass obj; // Constructor may throw an exception
} catch (const std::exception& e) {
// Handle the exception here
}

Exception Handling in Destructors:


• Throwing Exceptions in Destructors:
• It's generally advisable to avoid throwing exceptions from destructors. If an exception is
thrown during the destruction of an object, the C++ runtime system might terminate the
program. It is recommended to catch exceptions in destructors and handle them appropriately.
class MyClass {
public:
~MyClass() noexcept {
try {
// Destructor code that may throw an exception
} catch (const std::exception& e) {
// Handle the exception in a controlled way
}
}
};
• Handling Exceptions in Destructors:
• When an exception is thrown from a destructor, it's essential to catch and handle it within the
destructor or in a surrounding context to prevent program termination.
try {
MyClass obj;
// Destructor may throw an exception during obj's destruction
} catch (const std::exception& e) {
// Handle the exception here
}
10) What is the need for exception handling, explain 4 common types of exception?
Need for Exception Handling:
• Error Handling:
• Exception handling allows developers to handle runtime errors in a more controlled and
graceful manner. Instead of crashing the program, exceptions provide a mechanism to catch
and handle errors, improving the overall robustness of the code.
• Separation of Concerns:
• Exception handling separates the error-handling code from the normal flow of the program.
This separation improves code readability and maintainability by isolating error-handling
logic, making the main code more focused on its primary functionality.
• Maintainability:
• By centralizing error-handling code, changes related to error handling can be made in one
place, simplifying maintenance and reducing the risk of introducing bugs. It enhances the
code's maintainability and reduces duplication of error-handling logic.
• Program Stability:
• Proper exception handling contributes to program stability. Unhandled exceptions can lead to
program termination, potentially leaving resources unreleased. With exception handling,
resources can be properly cleaned up, and the program can exit gracefully.
• Debugging and Diagnostics:
• Exception messages and stack traces generated during exception handling provide valuable
information for debugging. They help developers identify the root cause of errors, making it
easier to diagnose and fix issues.
Common Types of Exceptions:
• std::runtime_error:
• Description: Represents errors that can only be determined at runtime.
• Example: File not found, memory allocation failure.
• std::logic_error:
• Description: Represents errors due to logical errors in the program, such as violations of
logical preconditions.
• Example: Accessing an element outside the bounds of an array, division by zero.
• std::invalid_argument:
• Description: A specific type of std::logic_error. Represents errors where a function
argument has an invalid value.
• Example: Passing an invalid argument to a function.
• std::out_of_range:
• Description: A specific type of std::logic_error. Represents errors where an attempt is
made to access an element outside the valid range.
• Example: Accessing an index beyond the valid range of a container.

User-defined Exception
• Custom Exception Classes:
• User-defined exceptions involve creating custom exception classes derived from standard
exception classes (e.g., std::exception). These classes encapsulate specific error conditions
relevant to the application's domain.
• Meaningful Error Messages:
• User-defined exceptions allow developers to provide meaningful error messages associated
with specific error conditions. This enhances the readability of error reports and aids in
debugging.
• Consistent Exception Handling:
• By defining custom exception classes, developers can ensure consistent and standardized
exception handling throughout their codebase. This promotes a unified approach to dealing
with errors, making the code more maintainable.
• Context-Specific Handling:
• Custom exceptions enable context-specific handling of errors. Developers can catch and handle
these exceptions at appropriate levels in the code, tailoring the error-handling logic based on
the specific requirements of different parts of the application.

#include<iostream>
#include <exception>
using namespace std;
class MyException: public exception{
const char *what() const throw(){
return "Attempted to divide by zero!\n";
}
};
int main(){
try{
float x,y;
cout<<"Enter two numbers : \n";
cin>>x>>y;
if (y==0){
MyException z;
throw z;
}else{
cout<<"x/y = "<<x/y<<endl;
}
}
catch(const exception& e)
{
cerr << e.what() << '\n';
}
}
11) What is exception specification? Explain with an example.
1. C++ provides a mechanism to ensure that a given function is limited to throw only a specified
list of exceptions.
2. An exception specification at the beginning of any function acts as a guarantee to the function's
caller that the function will throw only the exceptions contained in the exception specification
#include <iostream>
#include <stdexcept>
using namespace std;
void safeDivision(int numerator, int denominator) noexcept {
if (denominator == 0) {
throw invalid_argument("Division by zero is not allowed.");
}
int result = numerator / denominator;
cout << "Result of division: " << result << endl;
}
int main() {
try {
safeDivision(10, 2);
safeDivision(8, 0); // This will throw an exception
} catch (const exception& e) {
cerr << "Exception caught: " << e.what() << endl;
}
return 0;
}
12) What is a container? List container classes in C++. Explain associative containers using a
program.
Container in C++:
In C++, a container is a data structure that holds and organizes a collection of other objects, often
referred to as elements. Containers provide a way to store, retrieve, and manipulate groups of items.
List of Container Classes in C++ (STL):
Sequence Containers:
• std::vector: Dynamic array.
• std::deque: Double-ended queue.
• std::list: Doubly linked list.
• std::forward_list: Singly linked list.
Associative Containers:
• std::set: Ordered set of unique keys.
• std::multiset: Ordered set of keys (allows duplicates).
• std::map: Ordered key-value pairs.
• std::multimap: Ordered key-value pairs (allows duplicate keys).
Unordered Containers:
• std::unordered_set: Unordered set of unique keys.
• std::unordered_multiset: Unordered set of keys (allows duplicates).
• std::unordered_map: Unordered key-value pairs.
• std::unordered_multimap: Unordered key-value pairs (allows duplicate keys).
Container Adapters:
• std::stack: LIFO (Last-In-First-Out) stack.
• std::queue: FIFO (First-In-First-Out) queue.
• std::priority_queue: Priority queue.
Associative Containers in C++:
Associative containers in C++ are designed to provide fast access to elements using keys. These
containers maintain a specific order (sorted) based on the keys. The key serves as the primary means
of accessing elements, and each key must be unique within the container.
#include <iostream>
#include <map>
using namespace std;
int main() {
map<int, string> myMap; // Declare a map with int keys and string values

myMap[1] = "Alice"; // Insert key-value pairs into the map


myMap[2] = "Bob";
myMap[3] = "Charlie";

cout << "Value at key 1: " << myMap[1] << endl; // Access and display values using keys
cout << "Value at key 2: " << myMap[2] << endl;
cout << "Value at key 3: " << myMap[3] << endl;

int keyToFind = 2; // Check if a key exists in the map


if (myMap.find(keyToFind) != myMap.end()) {
cout << "Key " << keyToFind << " exists in the map. Value: " << myMap[keyToFind] <<
} else {
cout << "Key " << keyToFind << " does not exist in the map." << endl;
}

cout << "Iterating through the map:" << endl; // Iterate through the map
for (const auto& pair : myMap) {
cout << "Key: " << pair.first << ", Value: " << pair.second << endl;
}
return 0;
}
13) Run time vs Compile time polymorphism

Compile-Time Polymorphism Example (Function Overloading):


#include <iostream>

using namespace std;

class Complex {

private:

int real, imag;

public:

Complex(int r = 0, int i = 0) : real(r), imag(i) {}

Complex operator+(const Complex& other) const {

Complex result;

result.real = real + other.real;

result.imag = imag + other.imag;

return result;

void input() {

cout << "Enter real part: ";

cin >> real;

cout << "Enter imaginary part: ";

cin >> imag;


}

void display() const {

cout << "Complex Number: " << real << " + " << imag << "i" << endl;

};

int main() {

Complex complex1, complex2;

cout << "Enter values for the first complex number:" << endl;

complex1.input();

cout << "\nEnter values for the second complex number:" << endl;

complex2.input();

Complex sum = complex1 + complex2;

cout << "\nSum of Complex Numbers:" << endl;

complex1.display();

cout << " + " << endl;

complex2.display();

cout << " = " << endl;

sum.display();

return 0;

Runtime Polymorphism Example (Virtual Functions):


#include <iostream>

using namespace std;

class Shape { // Base class with a virtual function

public:

virtual void draw() const {

cout << "Drawing a shape." << endl;

};

class Circle : public Shape { // Derived class with overridden virtual function

public:

void draw() const override {

cout << "Drawing a circle." << endl;

};

int main() {

Shape baseShape; // Creating objects


Circle circle;

Shape* shapePtr = &baseShape; // Using pointers to achieve runtime polymorphism

shapePtr->draw(); // Calls the base class function

shapePtr = &circle;

shapePtr->draw(); // Calls the overridden function in the derived class

return 0;

14) Explain functions of vector/Deque STL.Write a program to explain the same.


1. push_back: Adds an element to the end of the vector/deque.
2. pop_back: Removes the last element from the vector/deque.
3. size: Returns the number of elements in the vector/deque.
4. empty: Returns true if the vector/deque is empty, false otherwise.
5. clear: Removes all elements from the vector/deque.
6. at: Accesses the element at a specified position with bounds checking.
7. front: Accesses the first element of the vector/deque.
8. back: Accesses the last element of the vector/deque.
9. begin and end: Returns iterators pointing to the beginning and past-the-end of the
vector/deque, respectively.
10. insert: Inserts elements at a specified position.
11. erase: Removes elements from a specified position or a range.
12. resize: Changes the size of the vector/deque.
13. reserve: Allocates space for a specified number of elements without changing their values.
14. capacity: Returns the current capacity (maximum number of elements that can be held without
reallocation).
15. emplace_back and emplace_front: Constructs and inserts a new element directly at the back or
front.(D)
16. swap: Swaps the contents of two deques. (D)
VECTOR :
#include <iostream>

#include <vector>

using namespace std;

int main() {

vector<int> myVector; // Declare a vector of integers

myVector.push_back(1); // Add elements using push_back

myVector.push_back(2);

myVector.push_back(3);

cout << "Elements in the vector:"; // Display the elements using iterators

for (auto it = myVector.begin(); it != myVector.end(); ++it) {

cout << " " << *it;

cout << endl;

cout << "Element at index 1: " << myVector.at(1) << endl; // Access elements using at.
cout << "First element: " << myVector.front() << endl;

cout << "Last element: " << myVector.back() << endl;

// Check if the vector is empty

cout << "Is the vector empty? " << (myVector.empty() ? "Yes" : "No") << endl;

myVector.resize(5, 42); // Resize the vector & Set additional elements to 42

cout << "Resized vector:"; // Display the resized vector

for (const auto& element : myVector) {

cout << " " << element;

cout << endl;

myVector.pop_back(); // Remove the last element using pop_back

cout << "Vector after pop_back:"; // Display the vector after pop_back

for (const auto& element : myVector) {

cout << " " << element;

cout << endl;

return 0;

DEQUE :
#include <iostream>

#include <deque>

using namespace std;

int main() {

deque<int> myDeque; // Declare a deque of integers

myDeque.push_back(1); // Add elements using push_back and push_front

myDeque.push_back(2);

myDeque.push_front(0);

myDeque.push_back(3);

cout << "Elements in the deque:"; // Display the elements using iterators

for (auto it = myDeque.begin(); it != myDeque.end(); ++it) {

cout << " " << *it;

cout << endl;

// Access elements using at, front, and back

cout << "Element at index 1: " << myDeque.at(1) << endl;

cout << "First element: " << myDeque.front() << endl;

cout << "Last element: " << myDeque.back() << endl;


// Check if the deque is empty

cout << "Is the deque empty? " << (myDeque.empty() ? "Yes" : "No") << endl;

// Resize the deque

myDeque.resize(5, 42); // Set additional elements to 42

// Display the resized deque

cout << "Resized deque:";

for (const auto& element : myDeque) {

cout << " " << element;

cout << endl;

// Remove the first and last elements using pop_front and pop_back

myDeque.pop_front();

myDeque.pop_back();

// Display the deque after pop_front and pop_back

cout << "Deque after pop_front and pop_back:";

for (const auto& element : myDeque) {

cout << " " << element;

cout << endl;

return 0;

15) Write notes on given points,i) Virtual function ii) Pure virtual function iii) Abstract class iv)
Type name v)Explicit and mutable.
1) Virtual Function:
Definition: A virtual function is a member function in a base class that is declared using the virtual
keyword and can be overridden by derived classes.
Points:
• Virtual functions are declared in the base class and overridden in derived classes.
• The virtual keyword is used in the base class to indicate that a function is virtual.
• Function resolution is determined at runtime, allowing dynamic binding.
• Virtual functions provide a mechanism for achieving runtime polymorphism.
Use:
• Allows polymorphism, where a base class pointer can be used to invoke a function in a derived
class.
• Simplest Example:
#include <iostream>
using namespace std;
class Shape {
public:
virtual void draw() const {
cout << "Drawing a shape." << endl;
}
};
class Circle : public Shape {
public:
void draw() const override {
cout << "Drawing a circle." << endl;
}
};
int main() {
Shape* shapePtr = new Circle();
shapePtr->draw(); // Calls the overridden function in the derived class
delete shapePtr;

return 0;
}
2) Pure Virtual Function:
Definition: A pure virtual function is a virtual function with no implementation in the base class,
marked by the = 0 syntax. It must be overridden by derived classes.
Points:
• A class containing a pure virtual function is termed an abstract class.
• Derived classes must provide a concrete (non-virtual) implementation for the pure virtual
function.
• Objects of abstract classes cannot be instantiated.
• Allows for polymorphic behavior and dynamic binding.
Use:
• Forces derived classes to provide an implementation.
Simplest Example:
#include <iostream>
using namespace std;
class AbstractShape {
public:
virtual void draw() const = 0; // Pure virtual function
};
class ConcreteCircle : public AbstractShape {
public:
void draw() const override {
cout << "Drawing a concrete circle." << endl;
}
};

int main() {
ConcreteCircle circle;
circle.draw();
AbstractShape* shapePtr = new ConcreteCircle();
shapePtr->draw();
delete shapePtr;
return 0;
}
3) Abstract Class:
Definition: An abstract class is a class that contains one or more pure virtual functions. Instances of an
abstract class cannot be created, but it can serve as a base class for other classes.
Points:
• An abstract class may have both concrete and pure virtual functions.
• Objects of abstract classes cannot be created; they are meant to be used as base classes.
• It may contain member variables and member functions with implementations.
• Derived classes must provide implementations for all pure virtual functions.
Use:
• Provides an interface that derived classes must implement.
• Simplest Example:
#include <iostream>
using namespace std;
class AbstractShape {
public:
virtual void draw() const = 0; // Pure virtual function
};
class ConcreteCircle : public AbstractShape {
public:
void draw() const override {
cout << "Drawing a concrete circle." << endl;
}
};
int main() {
// AbstractShape* shapePtr = new AbstractShape(); // Error: Cannot instantiate an abstract class
AbstractShape* shapePtr = new ConcreteCircle();
shapePtr->draw();
delete shapePtr;
return 0;
}
4) Type Name :
typename:
Definition: The typename keyword in C++ is used to indicate that a dependent qualified name (often a
type name) is a type, even when the compiler might not be able to determine it. It is commonly used in
template programming.
Use:
• Specifies that a dependent name represents a type, helping the compiler in template
metaprogramming.
Points:
• Often used in template code where the compiler may be uncertain about whether a dependent
name refers to a type or another entity.
• Required when referring to dependent types in templates to resolve ambiguity.
• The use of typename helps the compiler understand that a name inside a template definition
represents a type.
• Typically used with template parameters and nested dependent types.
#include <iostream>
#include <typeinfo>
using namespace std;
template <typename T>
class MyTemplate {
public:
void printType() {
// Without 'typename', the following line would result in a compilation error
typename T::InnerType inner;
cout << "Type inside template: " << typeid(inner).name() << endl;
}
};

class MyClass {
public:
using InnerType = int;
};
int main() {
MyTemplate<MyClass> myInstance;
myInstance.printType();
return 0;
}
5) explicit Keyword:
Definition: The explicit keyword is used in C++ to specify that a particular constructor or conversion
function should not be implicitly invoked by the compiler for automatic type conversions.
Use:
• Prevents unintended implicit conversions and enhances code clarity.
Points:
• It is often applied to single-argument constructors to prevent implicit type conversions.
• Ensures that a constructor is called only when there is a direct request for it.
• Can be used to avoid unexpected behavior caused by implicit conversions.
• Commonly used in situations where clarity and type safety are crucial.
#include <iostream>
using namespace std;
class MyClass {
public:
explicit MyClass(int x) {
cout << "Explicit Constructor: " << x << endl;
}
};
int main() {
MyClass obj1 = 42; // Error without 'explicit' - implicit conversion
MyClass obj2(42); // Okay with 'explicit' - explicit constructor call
return 0;
}
6) mutable Keyword:
Definition: The mutable keyword is used in C++ to declare a non-const data member of a class that can
be modified even if an object is declared as const.
Use:
• Allows modification of specific data members within a const member function.
Points:
• It is particularly useful when a logical state needs to be modified within a const member function.
• Applied to individual data members rather than the entire object.
• Enables changes to specific data members without violating const-correctness.
• Should be used judiciously to maintain the integrity of const-correctness.
#include <iostream>
using namespace std;
class MutableExample {
private:
mutable int mutableValue;
public:
MutableExample(int value) : mutableValue(value) {}
// Const member function with a mutable data member
void printValue() const {
cout << "Mutable Value: " << mutableValue << endl;
}
void incrementValue() const { // Function to modify the mutable data member
++mutableValue;
}
};
int main() {
MutableExample obj(10);
obj.printValue();
obj.incrementValue(); // Calling a const member function that modifies the mutable data member
obj.printValue();
return 0;
}
16) Write function tempalte to find minimum value conatined in array.
#include <iostream>
Using namespace std;
template <typename T, size_t N> // Function template to find the minimum value in an array
T findMinimum(const T (&arr)[N]) {
T minVal = arr[0];
for (size_t i = 1; i < N; ++i) {
if (arr[i] < minVal) {
minVal = arr[i];
}
}
return minVal;
}
int main() {
int intArray[5];
cout << "Enter 5 integers separated by spaces: ";
for (int i = 0; i < 5; ++i) {
cin >> intArray[i];
}
int minInt = findMinimum(intArray);
cout << "Minimum value in intArray: " << minInt << endl;
return 0;
}
17)What is STL? Why should C++ programmers be interested in STL? What is design
philosophy of STL? What are major components of STL?
The STL defines powerful, template-based, reusable components that implement many common data
structures and algorithms used to process those data structures. Collection of these generic classes &
functions is called STL.
• Reusability: STL provides generic and reusable components, allowing programmers to use
well-tested and efficient algorithms without having to implement them from scratch.
• Productivity: By using STL components, developers can focus more on solving specific
problems rather than implementing basic data structures and algorithms, thus increasing
productivity.
• Standardization: STL is part of the C++ Standard Library, making it widely supported and
ensuring consistent behavior across different compilers and platforms.
• Efficiency: STL components are implemented using templates and optimized for performance.
They provide efficient algorithms that are thoroughly tested and proven.
Design Philosophy of STL:
• Generic Programming: STL promotes the use of generic programming, allowing algorithms
and data structures to work with different data types while maintaining high efficiency.
• Efficiency: STL components are designed to be highly efficient, and their implementations
often leverage advanced features of C++.
• Flexibility: STL provides a flexible framework that allows users to customize certain aspects of
algorithms and data structures without modifying the underlying code.
• Ease of Use: STL aims to be easy to use, with clear and consistent interfaces for various
containers and algorithms.
Major Components of STL:
• Containers: Containers are objects that store data. Common containers include vectors, lists,
queues, stacks, maps, and sets.
• Algorithms: STL provides a set of generic algorithms that can operate on different types of
containers. Examples include sort, find, accumulate, etc.

Iterators: Iterators are used to iterate over the elements of a container. They provide a
uniform interface for accessing elements, allowing algorithms to work with different
containers.
18) Write a program to illustrate the stream error concept?
#include <iostream>

using namespace std;

int main() {

int number;

cout << "Enter an integer: ";

cin >> number; // Try to read an integer from the user

if (cin.fail()) { // Check for stream errors

cin.clear(); // Clear the error flags

// Consume any remaining characters in the input buffer

cin.ignore(numeric_limits<streamsize>::max(), '\n');

cout << "Invalid input. Please enter an integer." << endl;

} else {

cout << "You entered: " << number << endl; // Display the entered integer

return 0;

19) What is the purpose of iterators and algorithms in STL?


Iterators in STL:
Iterators in the Standard Template Library (STL) serve as a means to traverse and manipulate
elements of containers. They provide a uniform interface for accessing the elements of different data
structures.
Purpose of Iterators:
• Uniform Access to Elements:
• Iterators provide a consistent way to access elements across various containers, abstracting
away the underlying implementation details.
• Algorithms in STL can operate on any container as long as it supports the iterator interface.
• Traversal and Modification:
• Iterators allow sequential traversal of container elements, supporting operations like advancing
to the next element and moving backward.
• They enable the modification of container elements during traversal.
• Algorithm Integration:
• Iterators play a crucial role in facilitating the integration of algorithms with different containers.
• Algorithms operate on a range defined by iterators, allowing generic and reusable code.
• Support for Custom Containers:
• Custom containers can leverage iterators to enable compatibility with STL algorithms without
requiring modifications to the algorithms themselves.
• Users can define iterators for their containers to participate in generic algorithms seamlessly.
Algorithms in STL:
Algorithms in STL are generic functions that perform various operations on ranges of elements
defined by iterators. They cover a wide range of tasks, including sorting, searching, transforming, and
modifying container elements.
Purpose of Algorithms:
• Code Reusability:
• Algorithms encapsulate common operations on containers, promoting code reuse and
eliminating the need for developers to implement these algorithms manually.
• Generic Programming:
• Algorithms are designed to work with iterators, allowing them to operate on different containers
regardless of their specific implementations.
• Generic programming principles enable algorithmic code to be written once and used with
various data structures.
• Efficiency and Correctness:
• STL algorithms are optimized for performance and have undergone rigorous testing. Using them
reduces the chances of introducing errors and ensures efficient implementations.
• Consistent Interface:
• Algorithms provide a consistent interface across different containers. Regardless of the
container type, the same algorithm can be applied, promoting a uniform coding style.

20) Explain forward, bidirectional & random-access iterator?


Forward Iterator:
Definition: Forward iterators allow sequential access to the elements in a container. They support
moving forward (from the beginning to the end) and reading or modifying the elements during
traversal.
• Forward Movement Only: Forward iterators allow traversing elements in a container
sequentially from the beginning to the end. They support the increment (++) operation for
moving to the next element.
• Read and Modify: Forward iterators provide read and modify access to elements during
traversal. You can read the current element using *it and modify it if needed.
• Example:
#include <iostream>
#include <forward_list>
using namespace std;
int main() {
forward_list<int> numbers = {1, 2, 3, 4, 5};
// Using forward iterator to traverse and print elements
for (auto it = numbers.begin(); it != numbers.end(); ++it) {
cout << *it << " ";
}
return 0;
}
Bidirectional Iterator:
Definition: Bidirectional iterators extend the capabilities of forward iterators by allowing both
forward and backward traversal. They support moving backward using the -- operator.
• Forward and Backward Movement: Bidirectional iterators extend the capabilities of forward
iterators by allowing traversal in both forward and backward directions. They support both ++
(forward) and -- (backward) operations.
• Read, Modify, and Reverse: Bidirectional iterators support reading, modifying, and reversing
the direction of traversal using the -- operation.
• Example:
#include <iostream>
#include <list>
using namespace std;
int main() {
list<int> numbers = {1, 2, 3, 4, 5};
// Using bidirectional iterator to traverse and print elements backward
for (auto it = prev(numbers.end()); it != prev(numbers.begin()); --it) {
cout << *it << " ";
}
return 0;
}
Random Access Iterator:
Definition: Random access iterators provide the most flexibility, allowing direct access to any
element in the container. They support forward, backward, and direct access using +, -, and []
operations.
• Random Access: Random access iterators provide the most flexibility, allowing direct access to
any element in the container. They support forward, backward, and direct access using +, -, and
[] operations.
• Arithmetic Operations: Random access iterators support arithmetic operations like +, -, ++, --
, and subscript [] for direct access.
• Example:
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> numbers = {1, 2, 3, 4, 5};
// Using random access iterator to traverse and print elements
for (auto it = numbers.begin(); it != numbers.end(); ++it) {
cout << *it << " ";
}
// Direct access to the third element
cout << "\nThird element: " << numbers[2] << endl;
return 0;
}
21) Explain error handling in file I/O with suitable program.
Error handling in file I/O involves checking for potential errors that may occur during file operations
and taking appropriate actions to handle those errors. Common errors include file not found,
permissions issues, or failure to open or close a file.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main() {

string filePath = "example.txt"; // File path

try {
ifstream inputFile(filePath); // Attempt to open the file

if (!inputFile.is_open()) { // Check if the file is open


// Throw an exception if the file cannot be opened
throw runtime_error("Error: Unable to open the file.");
}
string line; // Read and display content from the file
while (getline(inputFile, line)) {
cout << line << endl;
}

inputFile.close(); // Close the file


} catch (const exception& e) {
cerr << "Exception: " << e.what() << endl; // Catch and handle exceptions
}

return 0;
}
22) Differentiate between overloaded function and function template, How are overloaded
function and function template related to each other.State valid example.

#include <iostream>

using namespace std; // Use namespace std globally

int add(int a, int b) { // Overloaded function to add two integers

cout << "Using overloaded function for integers: ";

return a + b;

double add(double a, double b) { // Overloaded function to add two doubles

cout << "Using overloaded function for doubles: ";

return a + b;
}

template <typename T> // Function template to add two values of any type

T add(T a, T b) {

cout << "Using function template for generic type: ";

return a + b;

int main() {

// Overloaded functions

cout << add(3, 4) << endl; // Calls add(int, int)

cout << add(3.5, 4.2) << endl; // Calls add(double, double)

// Function template

cout << add(3, 4) << endl; // Calls add<T>(T, T) with T=int

cout << add(3.5, 4.2) << endl; // Calls add<T>(T, T) with T=double

return 0;

23)What is file mode. Describe various file mode options available.


The term "file mode" typically refers to the mode in which a file is opened or created using file streams.
The file mode specifies the operations that can be performed on the file.

24) Write progarm to create files using constructor function.


#include <iostream>

#include <fstream>

#include <string>

using namespace std;

class FileCreator {

public:

// Constructor that takes a filename and content to create a file

FileCreator(const string& filename, const string& content) {


ofstream outputFile(filename);

if (outputFile.is_open()) {

outputFile << content;

cout << "File '" << filename << "' created successfully with content:\n" << content << endl;

} else {

cerr << "Error creating file '" << filename << "'." << endl;

};

int main() {

// Create a file named "example.txt" with content "Hello, File!"

FileCreator file1("example.txt", "Hello, File!");

// Create another file named "data.txt" with different content

FileCreator file2("data.txt", "This is some data.");

return 0;

You might also like