0% found this document useful (0 votes)
23 views

OOP Micro

Uploaded by

godseyash65
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views

OOP Micro

Uploaded by

godseyash65
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

Q) Explain the polymorphism feature of OOP.

What are the different ways to Integer: 5 }; To overload the '+' operator for adding two complex numbers, we can define
achieve polymorphism in C++ Language? Explain them along with examples a function named 'operator+' inside the Complex class. This function should
Double: 3.14 int main() {
take two Complex objects as arguments and return a new Complex object
Ans: Polymorphism is one of the key features of Object-Oriented
2. Virtual Functions: It is another type of polymorphism in which a function in Shape* s1 = new Circle(); that represents the sum of the two input objects.
Programming (OOP) that allows objects of different classes to be treated as if
the base class is declared as virtual and overridden in the derived class. When
they were objects of the same class. It is a powerful concept that enables Shape* s2 = new Rectangle(); Here's an example program that demonstrates how to overload the '+'
an object of the derived class is created, it can be referred to by a pointer or
code reusability and flexibility. operator for adding two Complex objects:
reference of the base class type. s1->draw();
In C++, there are two ways to achieve polymorphism: #include <iostream>
Example: s2->draw();
1. Function Overloading: It is a type of polymorphism in which multiple using namespace std;
#include <iostream> delete s1;
functions can have the same name but different parameters. The compiler
class Complex {
decides which function to call based on the number, type, and order of using namespace std; delete s2;
arguments passed to it. private:
class Shape { return 0;
Example: int real, imag;
public: }
#include <iostream> public:
virtual void draw() { Output:
using namespace std; Complex() {
cout << "Drawing a shape..." << endl; Drawing a circle...
void print(int x) { real = 0;
} }; Drawing a rectangle...
cout << "Integer: " << x << endl; imag = 0;
class Circle : public Shape { In the above example, we have a base class Shape and two derived classes
} Circle and Rectangle. The draw() function is declared as virtual in the base }
public:
class and overridden in the derived classes. When we create objects of the
void print(double x) { Complex(int r, int i) {
void draw() { derived classes and refer to them by pointers of the base class type, the
cout << "Double: " << x << endl; draw() function of the appropriate derived class is called at runtime. This is real = r;
cout << "Drawing a circle..." << endl;
known as dynamic binding.
} imag = i;
} };
Q) What is operator overloading? Write a program to overload '+' operator
int main() { }
class Rectangle : public Shape { for adding two complex numbers which are object of below complex class.
print(5); [6] Class Complex { Private: int real, imag; }; Complex operator+(Complex c) {
public:
print(3.14); Ans: Operator overloading is a feature of C++ that allows operators such as +, Complex temp;
void draw() {
-, *, /, etc. to be redefined or overloaded for user-defined classes. This means
return 0; temp.real = real + c.real;
cout << "Drawing a rectangle..." << endl; that we can define how these operators behave when used with objects of
} our own classes. temp.imag = imag + c.imag;
}
Output: return temp;

} The '+' operator is overloaded using the 'operator+' function inside the class. public: Drawing a square
This function takes a Complex object 'c' as an argument and returns a new
void display() { void draw() { In the above program, we define an abstract base class 'Shape' with a pure
Complex object 'temp' that represents the sum of the current object and 'c'.
virtual function 'draw'. This means that 'Shape' cannot be instantiated on its
cout << real << " + " << imag << "i" << endl; cout << "Drawing a circle" << endl;
In the main function, we create three Complex objects 'c1', 'c2', and 'c3'. We own, but can be used as a base class for other classes.
} add 'c1' and 'c2' using the '+' operator and store the result in 'c3'. Finally, we }
We also define two derived classes 'Circle' and 'Square' that inherit from
display the values of all three objects using the 'display' function.
}; }; 'Shape' and provide their own implementation of the 'draw' function.
Q) What is Pure virtual function? Illustrate the use of Pure virtual function
int main() { class Square : public Shape { In the main function, we create two pointers of type 'Shape' and assign them
Ans: A pure virtual function is a virtual function in C++ that is declared in a to objects of type 'Circle' and 'Square'. We then call the 'draw' function on
Complex c1(2, 3), c2(4, 5), c3; public:
base class but has no implementation in the base class. Instead, the both objects, which calls the appropriate implementation of the function in
c3 = c1 + c2; implementation of the pure virtual function is provided by the derived void draw() { the derived classes.
classes that inherit from the base class.
cout << "c1 = "; cout << "Drawing a square" << endl; Finally, we delete the objects using the pointers to free up memory.
A pure virtual function is declared using the syntax:
c1.display(); } Q) What is runtime polymorphism? How it is achieved in C++. Explain it
virtual return_type function_name(parameters) = 0;
cout << "c2 = "; }; along with example.
The '= 0' at the end of the declaration indicates that the function is pure
c2.display(); int main() { Ans: Runtime polymorphism is the ability of a program to determine at
virtual and has no implementation in the base class.
runtime which implementation of a function to call based on the actual
cout << "c3 = "; Shape* shape1 = new Circle();
The use of pure virtual functions is to create an abstract base class that object that is being used, rather than the type of the pointer or reference to
c3.display(); cannot be instantiated on its own, but can be used as a base class for other Shape* shape2 = new Square(); that object. This is achieved through the use of virtual functions in C++.
classes. The derived classes must provide their own implementation of the
return 0; } In C++, virtual functions allow a derived class to provide its own
pure virtual function to become concrete classes.
implementation of a function that is already defined in the base class. When
Output: shape1->draw();
Here's an example program that illustrates the use of pure virtual functions: a function is marked as virtual in the base class, any derived class can
shape2->draw(); override that function with its own implementation. When a virtual function
#include <iostream>
is called using a pointer or reference to an object, the actual implementation
c1 = 2 + 3i delete shape1;
using namespace std; that is called depends on the type of the object being used, not the type of
c2 = 4 + 5i delete shape2; the pointer or reference.
class Shape {
c3 = 6 + 8i return 0; Here's an example program that illustrates runtime polymorphism in C++:
public:
In the above program, we define a class named 'Complex' with two private } #include <iostream>
virtual void draw() = 0;
data members 'real' and 'imag' representing the real and imaginary parts of a
Output: using namespace std;
complex number. We also define a default constructor and a parameterized };
constructor to initialize the data members. Drawing a circle class Shape {
class Circle : public Shape {
public:
virtual void draw() { In this program, we define a base class 'Shape' with a virtual function 'draw'. // Function to add two doubles public void printArea() {
We also define a derived class 'Circle' that overrides the 'draw' function with
cout << "Drawing a shape" << endl; double add(double a, double b) { System.out.println("The area is: " + area);
its own implementation.
} return a + b; } }
In the main function, we create two pointers of type 'Shape' and assign them
}; to objects of type 'Shape' and 'Circle'. We then call the 'draw' function on } In this example, we have defined an abstract class 'Shape' that has one
both objects using their respective pointers. Since 'shape1' points to an abstract method 'calculateArea()' and one non-abstract method 'printArea()'.
class Circle : public Shape { In this example, we have defined three functions with the same name 'add',
object of type 'Shape', the 'draw' function in 'Shape' is called. However, since The 'area' variable is protected, which means it can be accessed by
but each function takes different types of parameters. The first function
public: 'shape2' points to an object of type 'Circle', the 'draw' function in 'Circle' is subclasses.
takes two integers and returns their sum as an integer. The second function
called instead.
void draw() { takes two floats and returns their sum as a float. The third function takes two Since 'Shape' is an abstract class, it cannot be instantiated on its own.
This demonstrates runtime polymorphism in action, as the actual doubles and returns their sum as a double. Instead, we can create subclasses of 'Shape' that implement the
cout << "Drawing a circle" << endl;
implementation of the 'draw' function that is called depends on the type of 'calculateArea()' method:
When we call the 'add' function with different types of arguments, the
} the object being used, not the type of the pointer.
compiler will determine which version of the function to call based on the class Circle extends Shape {
}; Q) What is function overloading? Write defination of three overloaded types of the arguments passed. For example:
private double radius;
functions (add) which will add two integer, float and double numbers
int sum1 = add(2, 3); // Calls the add(int, int) function
respectively public Circle(double radius) {
int main() { float sum2 = add(2.5f, 3.5f); // Calls the add(float, float) function
Ans: Function overloading is the ability to define multiple functions with the this.radius = radius;
Shape* shape1 = new Shape(); same name but different parameters. The compiler determines which double sum3 = add(2.5, 3.5); // Calls the add(double, double) function
}
function to call based on the number, types, and order of the arguments
Shape* shape2 = new Circle(); In each case, the appropriate version of the 'add' function is called based on
passed to it. public void calculateArea() {
the types of the arguments passed. This allows us to write more flexible and
shape1->draw();
Here are three overloaded functions named 'add' that add two integer, float, reusable code by defining functions that can work with different types of area = Math.PI * radius * radius;
shape2->draw(); and double numbers respectively: data.
} }
delete shape1; // Function to add two integers Q) Explain abstract class concept along with example
class Rectangle extends Shape {
delete shape2; int add(int a, int b) { An abstract class is a class that cannot be instantiated on its own and must be
private double length;
subclassed to be used. It is used as a base class for other classes to inherit
return 0; return a + b;
from and provides a common interface for all its subclasses. Abstract classes private double width;
} } can have both abstract and non-abstract methods.
public Rectangle(double length, double width) {
Output: // Function to add two floats Here is an example of an abstract class:
this.length = length;
Drawing a shape float add(float a, float b) { abstract class Shape {
this.width = width;
Drawing a circle return a + b; protected double area;
}
} public abstract void calculateArea();

public void calculateArea() { #include <iostream> // Get the current positions of the get and put pointers command line arguments passed to the program, and `argv` is an array of
strings containing the actual arguments.
area = length * width; #include <fstream> std::streampos getPosition = file.tellg();
The program starts by printing the number of command line arguments using
} } int main() { std::streampos putPosition = file.tellp();
`argc`. Then, it iterates over the `argv` array using a loop and prints each
In these subclasses, we have implemented the 'calculateArea()' method to std::fstream file("example.txt", std::ios::in | std::ios::out); std::cout << "Current get position: " << getPosition << std::endl; argument along with its index.
calculate the area of a circle and a rectangle respectively. We can then use
if (!file) { std::cout << "Current put position: " << putPosition << std::endl; For example, if you compile and run the program with the following
these subclasses to create objects and call the 'printArea()' method:
command:
std::cout << "Failed to open the file." << std::endl; file.close();
Circle circle = new Circle(5);
./program arg1 arg2 arg3
return 1; return 0; }
circle.calculateArea();
The output will be:
} Q) What are command line arguments in C++? Write a program to explain the
circle.printArea(); // The area is: 78.53981633974483
same. Number of command line arguments: 4
// Move the get pointer 10 bytes ahead from the beginning
Rectangle rectangle = new Rectangle(4, 6);
Ans: Command line arguments in C++ are values provided to a program when Command line arguments:
file.seekg(10, std::ios::beg);
rectangle.calculateArea(); it is executed from the command line. These arguments are passed as strings
Argument 0: ./program
// Read and print the content from the new position and can be accessed within the program to perform specific tasks or modify
rectangle.printArea(); // The area is: 24.0
its behavior based on the provided input. Argument 1: arg1
char c;
In this example, we have used the abstract class 'Shape' as a base class for
Here's an example program that demonstrates the usage of command line Argument 2: arg2
the 'Circle' and 'Rectangle' classes. By doing so, we have provided a common while (file.get(c)) {
arguments:
interface for these subclasses and made it easier to add new shapes in the Argument 3: arg3
std::cout << c;
future. #include <iostream>
Here, `./program` is the name of the program itself, and `arg1`, `arg2`, and
}
Q) What are various functions used to manipulate file pointers? Explain using int main(int argc, char* argv[]) { `arg3` are the command line arguments passed to the program.
example. // Move the put pointer 5 bytes back from the current position
std::cout << "Number of command line arguments: " << argc << std::endl; By accessing and processing command line arguments, you can create more
Ans: In C++, file pointers can be manipulated using various functions file.seekp(-5, std::ios::cur); flexible and customizable programs that can be controlled by the user at
std::cout << "Command line arguments:" << std::endl;
provided by the <fstream> library. Here are some commonly used functions runtime.
// Write some content at the new position
to manipulate file pointers in C++: 1) seekg(): This function is used to set the for (int i = 0; i < argc; ++i) {
Q) What are fstream, ifstream and ofstream? Illustrate with help of example
position of the get (input) file pointer. It takes an offset value and a seek file << "Modified content";
std::cout << "Argument " << i << ": " << argv[i] << std::endl;
direction as arguments. 2)seekp(): This function is used to set the position of Ans: In C++, `fstream`, `ifstream`, and `ofstream` are classes that provide
// Move the put pointer to the end of the file
the put (output) file pointer. It takes an offset value and a seek direction as } functionality for reading from and writing to files. They are part of the
arguments. 3) tellg() and tellp(): These functions are used to get the current file.seekp(0, std::ios::end); Standard Library's `<fstream>` header.1. )`fstream` is a class that represents a
return 0; }
position of the get and put file pointers, respectively. They return the file stream and provides both input and output operations. It can be used to
// Append some content at the end
position as a streampos value. In this program, the `main` function has two parameters: `argc` (argument read data from and write data to files. 2). `ifstream` is a derived class of
file << "\nAppended content"; count) and `argv` (argument vector). `argc` represents the number of `fstream` and is used specifically for reading input from files. It inherits all the
Certainly! Here's an example in C++ that demonstrates the usage of various
functionality of `fstream` and adds additional methods for input operations.
functions to manipulate file pointers in a single code:
3 )`ofstream` is also a derived class of `fstream` and is used for writing output return 1; } } outputFile.close();
to files. It inherits from `fstream` and provides additional methods for output
return 0; } void readEmployeeRecord(std::ifstream& inputFile) { // kOpen the file for reading
operations.
In this example, we first create an `ofstream` object named `outputFile` to std::string name; std::ifstream inputFile("employees.txt");
Here's an example that demonstrates the usage of these classes:
write data to the file "example.txt". We check if the file was opened
int id; if (!inputFile) {
#include <iostream> successfully using the `is_open()` method and then write "Hello, world!" to
the file using the `<<` operator. Finally, we close the file using the `close()` double salary; std::cerr << "Failed to open the file for reading." << std::endl;
#include <fstream>
method.
inputFile >> name >> id >> salary; return 1; }
int main() {
Next, we create an `ifstream` object named `inputFile` to read data from the
std::cout << "Name: " << name << ", ID: " << id << ", Salary: " << salary << // Read and display employee records
// Writing to a file using ofstream same file. Again, we check if the file was opened successfully and then read a
std::endl;
line from the file using the `getline()` method. We output the read line to the std::cout << "Employee Records:" << std::endl;
std::ofstream outputFile("example.txt"); // Create an ofstream object
console. Finally, we close the file using the `close()` method. }
readEmployeeRecord(inputFile);
if (outputFile.is_open()) {
This example demonstrates the basic usage of `fstream`, `ifstream`, and int main() {
readEmployeeRecord(inputFile);
outputFile << "Hello, world!" << std::endl; // Write data to the file `ofstream` classes for file input and output operations in C++.
// Create and open the file for writing
readEmployeeRecord(inputFile);
outputFile.close(); // Close the file Q) Write a program to create file, read and write record into it. Every record
std::ofstream outputFile("employees.txt");
contains employee name, id and salary. Store and retrieve atleast 3 data. // Close the file
} else {
if (!outputFile) {
Ans: #include <iostream> inputFile.close();
std::cout << "Failed to open the file for writing." << std::endl;
std::cerr << "Failed to create the file." << std::endl;
#include <fstream> return 0;}
return 1; }
return 1;
#include <string> Q) What do you mean by file handling? Explain the following functions. i)
// Reading from a file using ifstream
} open() ii) get() iii) getline()
struct Employee {
std::ifstream inputFile("example.txt"); // Create an ifstream object
// Write employee records to the file Ans: File handling refers to the process of working with files in a computer
std::string name;
if (inputFile.is_open()) { program. It involves tasks such as creating, opening, reading, writing, and
Employee employee1 = { "John Doe", 1, 5000.0 };
int id; closing files. File handling allows programs to interact with external files,
std::string line;
Employee employee2 = { "Jane Smith", 2, 6000.0 }; enabling data storage, retrieval, and manipulation.
double salary;
std::getline(inputFile, line); // Read a line from the file
Employee employee3 = { "Mike Johnson", 3, 5500.0 }; Now let's explain the following file handling functions:
};
std::cout << "Contents of the file: " << line << std::endl;
writeEmployeeRecord(outputFile, employee1); i) `open()`:The `open()` function is used to open a file in C++. It takes a
void writeEmployeeRecord(std::ofstream& outputFile, const Employee&
inputFile.close(); // Close the file filename and a mode as parameters and returns an `fstream` object that
employee) { writeEmployeeRecord(outputFile, employee2);
represents the opened file. The mode specifies the purpose for which the file
} else {
outputFile << employee.name << " " << employee.id << " " << writeEmployeeRecord(outputFile, employee3); is being opened, such as reading (`std::ifstream::in`), writing
std::cout << "Failed to open the file for reading." << std::endl; employee.salary << std::endl; (`std::ofstream::out`), or both reading and writing (`std::fstream::in |
// Close the file

std::fstream::out`). The `open()` function allows the program to establish a std::cin >> filename; determined at compile time based on the arguments provided during the Here's an example of a function template in C++:
connection to the file and perform subsequent read or write operations on it. function call.
// Create the file using the constructor #include <iostream>
ii) `get()`:The `get()` function is a member function of the `istream` class (e.g., Here's an example of overloaded functions in C++:
std::ofstream outputFile(filename); template<typename T>
`ifstream`, `cin`). It is used to extract a single character from an input stream.
#include <iostream>
When called without any parameters, `get()` reads and returns the next if (!outputFile) { void print(T num) {
character from the input stream. It can also be called with a character void print(int num) {
std::cerr << "Failed to create the file." << std::endl; std::cout << "Printing: " << num << std::endl;
variable as a parameter, in which case it reads the next character and stores
std::cout << "Printing an integer: " << num << std::endl;
it in the variable. The `get()` function is often used to read characters one by return 1; }
one from a file. }
} int main() {
iii) `getline()`:The `getline()` function is a member function of the `istream` void print(double num) {
// Write some data to the file print(10);
class (e.g., `ifstream`, `cin`). It is used to read a line of text from an input
std::cout << "Printing a double: " << num << std::endl;
stream, such as a file or standard input. It takes two parameters: a string outputFile << "This is some text written to the file." << std::endl; print(3.14);
variable to store the line of text and an optional delimiter character to }
// Close the file print("Hello");
specify where to stop reading the line (default delimiter is the newline
int main() {
character '\n'). The `getline()` function reads characters from the input outputFile.close(); return 0;
stream until it encounters the specified delimiter or reaches the end of the print(10);
std::cout << "File created successfully." << std::endl; }
line. It then stores the extracted line in the string variable, excluding the
print(3.14);
delimiter. `getline()` is commonly used to read complete lines of text from a return 0; In the above example, we define a function template named `print` that
file. return 0; takes a single parameter of type `T`. The type `T` is a placeholder for any
}
valid type. The compiler generates the appropriate version of the function for
These functions are essential for file handling in C++. The `open()` function }
Q5) a) Distinguish between overloaded function and function template with each type used during the function call. In this case, the function template is
allows you to establish a connection to a file, while `get()` and `getline()`
suitable example. In the above example, we have two overloaded functions named `print`, one instantiated for `int`, `double`, and `const char*` (for the string) types.
provide mechanisms to read data from the file. Understanding and utilizing
that takes an `int` parameter and another that takes a `double` parameter.
these functions correctly enables effective file input and output operations in An overloaded function and a function template are both mechanisms in In summary, overloaded functions differentiate between functions based on
Depending on the argument type provided during the function call, the
C++ programs. programming languages that allow multiple functions with the same name the parameter lists, while function templates allow the creation of generic
appropriate overloaded function is executed.
but different parameters to be defined. However, they differ in how they functions that can operate on multiple types by using type placeholders.
Q) Write a program to create files using constructor function.
achieve this.
Q5) b) What is an Exception specification? Explain using suitable example.
Ans: #include <iostream>
1. Overloaded Function: 2. Function Template:
In C++, an exception specification is a construct that allows a function to
#include <fstream>
An overloaded function refers to multiple functions with the same name but A function template allows the definition of a generic function that can declare the types of exceptions it may throw. It provides a way for the
int main() { different parameter lists. These functions can have different numbers or operate on multiple types without specifying the type explicitly. It provides a programmer to explicitly specify the exceptions that a function can
types of parameters, allowing the programmer to define multiple versions of way to create a family of functions where the same logic can be reused for potentially throw. Exception specifications can be used to document and
std::string filename;
the function for different scenarios. The appropriate overloaded function is different types. The compiler generates the appropriate function based on enforce error-handling requirements for functions.
std::cout << "Enter the filename: "; the argument types used during the function call.
There are two types of exception specifications in C++: dynamic exception return 0; divide(10, 2); Here's an example of a function template that performs addition:
specifications (deprecated since C++11) and noexcept specifications.
} } catch (const char* ex) { cpp
1. Dynamic Exception Specification (Deprecated):
In the above example, the `divide` function has a dynamic exception std::cout << "Exception caught: " << ex << std::endl; #include <iostream>
Dynamic exception specifications use the `throw` keyword followed by a list specification `throw(int)`, which means it can throw an exception of type
} template<typename T>
of exception types within parentheses to declare the exceptions that a `int`. Inside the function, if the divisor (`b`) is zero, it throws an exception of
function may throw. This specification is placed at the end of the function value `0`. The exception is caught in the `main` function's `catch` block, and return 0; T add(T a, T b) {
declaration. However, dynamic exception specifications are considered the appropriate error handling is performed.
} return a + b;
deprecated since C++11 and should not be used in modern C++ code.
2. Noexcept Specification:
In this example, the `divide` function is specified as `noexcept`, indicating }
Here's an example of a dynamic exception specification:
Noexcept specifications, introduced in C++11, use the `noexcept` keyword to that it does not throw any exceptions. However, inside the function, there is
int main() {
#include <iostream> indicate that a function will not throw any exceptions. This specification is an attempt to throw an exception using the `throw` keyword. This results in a
placed after the parameter list and before the function body. It allows the compile-time error since throwing an exception from a `noexcept` function std::cout << add(5, 10) << std::endl; // Output: 15
compiler to optimize the code by assuming that no exceptions will be violates its specification.
std::cout << add(3.14, 2.71) << std::endl; // Output: 5.85
void divide(int a, int b) throw(int) { thrown.
Q5) C) What is Generic programming? how it is implemented in c++?
std::cout << add("Hello, ", "World!") << std::endl; // Output: Hello, World!
if (b == 0) { Here's an example of a noexcept specification:
Generic programming is a programming paradigm that aims to create
return 0;
throw 0; // Throw an integer exception when dividing by zero #include <iostream> reusable, generic code that can operate on different data types without
sacrificing performance or type safety. It allows the development of }
} else {
algorithms and data structures that can work with a variety of types,
In the above example, the `add` function template is defined using the
std::cout << "Result: " << a / b << std::endl; void divide(int a, int b) noexcept { promoting code reusability and reducing duplication.
`template` keyword and a type parameter `T`. It takes two parameters of
} if (b == 0) { In C++, generic programming is primarily implemented using templates. type `T` and returns their sum. The function template is instantiated with
Templates provide a mechanism to define generic functions and classes that `int`, `double`, and `const char*` types in the `main` function, demonstrating
} throw "Divisor cannot be zero."; // Error: Attempt to throw an
can be instantiated with different types at compile time. This enables the its ability to work with different types.
exception from a noexcept function
int main() { creation of code that works seamlessly with various data types without the
2. Class Templates:
} else { need for explicit specialization.
try {
Class templates allow the creation of generic classes that can be instantiated
std::cout << "Result: " << a / b << std::endl; There are two main types of templates in C++: function templates and class
divide(10, 2); with different types. The class template is defined similarly to function
templates.
} templates, using the `template` keyword and the template parameter list.
divide(10, 0);
1. Function Templates:
} Here's an example of a class template representing a generic stack:
} catch (int ex) {
Function templates allow the definition of a generic function that can
int main() { #include <iostream>
std::cout << "Exception caught: " << ex << std::endl; operate on different types. The function template is defined using the
try { `template` keyword followed by the template parameter list, which includes template<typename T>
}
one or more type parameters.

class Stack { }; the programmer to explicitly indicate that a name should be treated as a Certainly! In C++, class templates can have multiple parameters, allowing for
type, even though it may not be clear to the compiler in certain contexts. the creation of generic classes that can operate on multiple types
private: int main() {
simultaneously. Each template parameter represents a different type that
Here's an example that demonstrates the usage of the `typename` keyword:
T* elements; Stack<int> intStack(5); can be specified when instantiating the class template.
template <typename T>
int top; intStack.push(10); Here's an example of a class template with multiple parameters representing
void printSize(T container) { a generic Pair class:
int capacity; intStack.push(20);
typename T::size_type size = container.size(); #include <iostream>
public: std::cout << intStack.pop() << std::endl; // Output: 20
std::cout << "Size of the container: " << size << std::endl; template<typename T1, typename T2>
Stack(int size) : capacity(size), top(-1) { Stack<double> doubleStack(3);
} class Pair {
elements = new T[capacity]; doubleStack.push(3.14);
In this example, `typename` is used to specify that `T::size_type` is a type, private:
} doubleStack.push(2.71);
not a variable. Without the `typename` keyword, the compiler may assume
T1 first;
void push(T element) { std::cout << doubleStack.pop() << std::endl; // Output: 2.71 `T::size_type` as a non-type member and raise an error.
T2 second;
if (top < capacity - 1) { return 0; 2. `export` Keyword:
public:
elements[++top] = element; } The `export` keyword was originally intended to be used in C++ as a way to
explicitly declare template definitions that would be defined separately in Pair(const T1& firstValue, const T2& secondValue) : first(firstValue),
} else { In this example, the `Stack` class template is defined using the `template`
another translation unit. The idea was to separate the template definition second(secondValue) {}
keyword and a type parameter `T`. The class template represents a stack
std::cout << "Stack is full!" << std::endl; from its declaration to improve compilation times.
data structure that can hold elements of type `T`. The `main` function
} demonstrates the instantiation and usage of `Stack` objects with `int` and However, the `export` keyword has been deprecated in the C++ standard
T1 getFirst() const {
`double` types. since C++98 and is not supported by most modern compilers. The reason for
}T pop() {
deprecation was that the export feature introduced significant complexity to return first;
By using templates, generic programming in C++
if (top >= 0) { the language and led to various implementation issues.
}
Q6) a) Write short note on type name and export key-word.
return elements[top--]; In practice, it is no longer necessary to use the `export` keyword in C++ for
1. `typename` Keyword: template definitions. Template definitions are typically included in header
} else {
files, which are directly included in the translation unit where the template is T2 getSecond() const {
In C++, the `typename` keyword is used in template code to specify that a
std::cout << "Stack is empty!" << std::endl; instantiated. This approach allows the compiler to see the template
dependent name is a type. It is typically used when dealing with dependent return second;
definition and perform the necessary compilation and linkage.
return T(); names within template definitions, especially when working with nested
}
types or dependent type names. Therefore, it is recommended to omit the `export` keyword when working
}
with C++ templates in modern code. };
The `typename` keyword helps the compiler understand that a dependent
}
name refers to a type, rather than a variable or a member function. It allows Q6 b) Explain class template using multiple parameters with help of program.
int main() { exceptional conditions, such as divide-by-zero errors, file input/output std::cout << "Result: " << result << std::endl; - Enabling traversal: Iterators provide a way to iterate over the elements of a
errors, or memory allocation failures. container sequentially or non-sequentially. They allow accessing and
Pair<int, double> pair1(10, 3.14); } catch (const std::runtime_error& ex) {
manipulating individual elements during iteration.
The exception handling mechanism in C++ involves three main components:
std::cout << "Pair 1: " << pair1.getFirst() << ", " << pair1.getSecond() << std::cout << "Exception caught: " << ex.what() << std::endl;
`try`, `catch`, and `throw`. - Abstracting container details: Iterators provide an abstraction layer that
std::endl;
} separates the algorithms from the specific container implementation. This
1. `try` block: The `try` block is used to enclose the code that might throw an
means that the same algorithm can be applied to different containers as long
exception. It is followed by one or more `catch` blocks that handle specific return 0;
as they support the required iterator operations.
Pair<std::string, bool> pair2("Hello", true); types of exceptions.
}
- Supporting generic algorithms: Iterators enable the implementation of
std::cout << "Pair 2: " << pair2.getFirst() << ", " << pair2.getSecond() << 2. `catch` block: The `catch` block is used to catch and handle exceptions. It
In this example, the `divide` function takes two parameters, `a` and `b`, and generic algorithms that work with different container types. By using
std::endl; specifies the type of exception it can handle and the code to be executed
performs division. If the divisor `b` is zero, the function throws a iterators, algorithms can operate on containers without needing to know the
when that exception is thrown. Multiple `catch` blocks can be chained to
`std::runtime_error` exception with a custom error message. underlying container type or implementation details.
handle different types of exceptions.
return 0; In the `main` function, the `divide` function is called within a `try` block. If an 2. Purpose of Algorithms:
3. `throw` statement: The `throw` statement is used to explicitly throw an
exception is thrown, it is caught by the `catch` block, which handles
} exception. It is typically used within the `try` block when an exceptional Algorithms in C++ are generic functions that operate on ranges of elements
exceptions of type `std::runtime_error`. The caught exception object is
condition is encountered. The thrown exception can be of any type, including defined by iterators. They provide a wide range of operations for
In this example, we define a class template `Pair` that takes two type accessed using a reference (`const std::runtime_error& ex`) and its `what()`
built-in types or user-defined types. manipulating and processing data stored in containers. The main purposes of
parameters, `T1` and `T2`. The `Pair` class has two private data members member function is called to retrieve the error message. The appropriate
algorithms are:
`first` and `second` of type `T1` and `T2`, respectively. The constructor Here's an example that demonstrates exception handling for divide-by-zero error handling code is then executed.
initializes these members with the provided values. errors: - Performing common operations: Algorithms offer a set of common
This example demonstrates how the exception handling mechanism allows
operations, such as searching, sorting, modifying, and transforming elements
In the `main` function, we instantiate two instances of the `Pair` class: `pair1` #include <iostream> for the detection and handling of divide-by-zero errors, preventing program
in containers. They provide a high-level interface for performing these
and `pair2`. The first instance is instantiated with `int` and `double` as the termination and providing an opportunity for error recovery or graceful
double divide(double a, double b) { operations efficiently and effectively.
template arguments, while the second instance is instantiated with termination.
`std::string` and `bool`. We then retrieve and print the values of the pairs if (b == 0) { - Encapsulating complex logic: Algorithms encapsulate complex operations
Q7) a) What is purpose of iterator and Algorithm?
using the `getFirst()` and `getSecond()` member functions. and algorithms that would otherwise require manual implementation by the
throw std::runtime_error("Divide by zero exception");
Iterators and algorithms are two fundamental components of the Standard programmer. They provide optimized and reusable solutions for various
This example demonstrates how a class template with multiple parameters
} Template Library (STL) in C++. They work together to provide a powerful and common data manipulation tasks.
allows the creation of generic classes that can hold different types
flexible mechanism for manipulating and processing data in containers.
simultaneously, providing flexibility and reusability. return a / b; - Promoting code reuse: Algorithms promote code reuse by providing a
1. Purpose of Iterators: collection of well-defined and tested functions that can be applied to
Q6) C) Explain Exception handling mechanism in c++ ? Explain by program to }
different containers. They reduce code duplication and promote modular
handle "divide by zero". Iterators are objects that allow traversal and access to elements within a
int main() { programming.
container. They provide a uniform interface for moving through the elements
In C++, exception handling is a mechanism that allows the programmer to
try { of a container, regardless of the specific container type. The main purposes - Providing a consistent interface: Algorithms follow a consistent interface
deal with exceptional situations or errors that may occur during program
of iterators are: that takes input ranges defined by iterators and produces output according
execution. It provides a structured way to handle and recover from double result = divide(10, 0);

to the specific algorithm. This uniformity makes it easier to understand, - Set: A container that stores unique elements in a sorted order. It does not #include <map> std::cout << "Updated age of " << name << " to 27." << std::endl;
learn, and use algorithms. allow duplicate elements.
int main() { }
By combining iterators and algorithms, the STL in C++ provides a powerful - Map: A container that stores key-value pairs. It provides efficient lookup
// Create a map to store name-age pairs // Erase an element from the map
and flexible framework for working with containers and performing various and retrieval based on the key.
operations on their elements in a generic and efficient manner. std::map<std::string, int> ageMap; name = "Bob";
- Unordered Set: Similar to a set, but the elements are not stored in a
Q7) b) What is STL? List and explain different types of STL Containers. particular order. It provides faster lookup and retrieval at the cost of // Insert elements into the map if (ageMap.count(name) > 0) {
unordered traversal.
STL stands for the Standard Template Library, which is a powerful library in ageMap.insert(std::make_pair("John", 25)); ageMap.erase(name);
C++ that provides a collection of templates and algorithms for efficient and - Unordered Map: Similar to a map, but the key-value pairs are not stored in
ageMap.insert(std::make_pair("Alice", 30)); std::cout << "Erased " << name << " from the map." << std::endl;
generic programming. It is part of the C++ Standard Library and offers a wide a particular order. It provides faster lookup and retrieval at the cost of
range of data structures and algorithms that can be used to solve diverse unordered traversal. ageMap.insert(std::make_pair("Bob", 35)); }
programming problems.
2. Iterators: // Access and print the elements in the map // Print the elements in the map after modifications
The STL consists of three main components:
Iterators provide a way to access and manipulate elements within a for (const auto& entry : ageMap) { std::cout << "Elements in the map after modifications:" << std::endl;
1. Containers: container. They act as generalizations of pointers and allow traversing the
std::cout << "Name: " << entry.first << ", Age: " << entry.second << for (const auto& entry : ageMap) {
elements of a container. Iterators can be used with algorithms to perform
Containers are data structures that store and organize elements in a specific std::endl;
various operations on the container's elements. They provide different levels std::cout << "Name: " << entry.first << ", Age: " << entry.second <<
way. The STL provides various types of containers, each with its own
of functionality and support, such as input iterators, output iterators, } std::endl;
characteristics and usage scenarios. The different types of STL containers
forward iterators, bidirectional iterators, and random access iterators.
include: // Check if an element exists in the map }
3. Algorithms:
- Vector: A dynamic array that can grow and shrink dynamically. It provides std::string name = "Alice"; return 0;
random access to elements and efficient insertion/deletion at the end. Algorithms are generic functions provided by the STL that operate on ranges
if (ageMap.count(name) > 0) { }
of elements defined by iterators. They perform common operations, such as
- List: A doubly-linked list that allows efficient insertion and deletion of
searching, sorting, modifying, and manipulating elements in containers. The std::cout << name << " is present in the map." << std::endl; In this program, we include the necessary header files `<iostream>` and
elements at any position. It does not support random access.
STL algorithms are designed to work with various container types, providing `<map>` to work with the `std::map` container from the STL.
} else {
- Deque: A double-ended queue that supports insertion and deletion at both efficient and reusable solutions for data processing tasks.
We create a `std::map` called `ageMap`, which stores pairs of name and age.
ends. It provides random access to elements similar to a vector. std::cout << name << " is not present in the map." << std::endl;
Overall, the STL provides a rich set of containers, iterators, and algorithms We insert three elements into the map using the `insert` function and the
- Stack: A container that follows the Last-In-First-Out (LIFO) principle. It that allow C++ programmers to write efficient and generic code, promoting } `make_pair` helper function.
provides push and pop operations on the top element. code reuse and maintainability.
// Update the age of an existing entry Next, we iterate over the elements in the map using a range-based for loop
- Queue: A container that follows the First-In-First-Out (FIFO) principle. It Q7) C) Write a program to implement map in STL. and print each name-age pair.
name = "John";
provides enqueue and dequeue operations.
Certainly! Here's an example program that demonstrates the usage of the We then check if a specific name exists in the map using the `count` function,
if (ageMap.count(name) > 0) {
- Priority Queue: A container that maintains a sorted sequence of elements. `std::map` container from the STL in C++: and based on the result, we display a corresponding message.
The highest-priority element is always at the front. ageMap[name] = 27;
#include <iostream>
After that, we update the age of an existing entry in the map by directly Function objects (also known as functors) are objects that behave like 2. `pop_back()`: Removes the last element from the vector. numbers.push_back(10);
assigning a new value to it. functions. They can be used with algorithms and containers to define custom
3. `size()`: Returns the number of elements in the vector. numbers.push_back(20);
behavior. Function objects provide a way to encapsulate operations and
Finally, we erase an element from the map using the `erase` function and
customize the behavior of algorithms based on specific criteria. 4. `empty()`: Checks whether the vector is empty or not. numbers.push_back(30);
iterate over the map again to print the elements after the modifications.
5. Allocators: 5. `at()`: Accesses the element at a specified index with bounds checking. // Access and print vector elements
This program demonstrates the basic operations of inserting, accessing,
updating, and erasing elements in a `std::map` container from the STL. Allocators are used to manage memory allocation and deallocation for 6. `operator[]`: Accesses the element at a specified index without bounds std::cout << "Vector elements: ";
container elements. They provide a way to customize the memory checking.
Q8) a) What are major components of STL. for (const auto& num : numbers) {
management behavior of containers. By default, containers use a specific
7. `front()`: Accesses the first element of the vector.
The major components of the Standard Template Library (STL) in C++ are as allocator, but custom allocators can be provided to override the default std::cout << num << " ";
follows: behavior. 8. `back()`: Accesses the last element of the vector.
}
1. Containers: 6. Adapters: 9. `begin()`: Returns an iterator pointing to the first element of the vector.
std::cout << std::endl;
The STL provides a set of container classes that store and organize data. Adapters are classes that modify or extend the behavior of existing 10. `end()`: Returns an iterator pointing to the position past the last element
// Access elements using at() and operator[]
These containers include vectors, lists, deques, stacks, queues, sets, maps, containers or iterators. They provide a different interface or functionality of the vector.
and more. Containers offer various operations for accessing, inserting, and while internally using the original containers or iterators. Some examples of std::cout << "Element at index 1: " << numbers.at(1) << std::endl;
11. `insert()`: Inserts elements at a specified position.
removing elements, and they come with different characteristics and usage adapters include stack, queue, and priority_queue, which are implemented
std::cout << "Element at index 2: " << numbers[2] << std::endl;
scenarios. using underlying containers. 12. `erase()`: Removes elements from a specified position or range.
// Check vector size and emptiness
2. Algorithms: These major components work together to provide a powerful and efficient 13. `clear()`: Removes all elements from the vector.
framework for generic programming in C++. They enable code reuse, std::cout << "Vector size: " << numbers.size() << std::endl;
Algorithms in the STL operate on sequences of elements defined by iterators. 14. `resize()`: Resizes the vector to a specified size.
abstraction, and separation of concerns, making it easier to write
They provide a wide range of operations, such as sorting, searching, std::cout << "Is vector empty? " << (numbers.empty() ? "Yes" : "No") <<
maintainable and efficient code. The STL is a fundamental part of the C++ 15. `reserve()`: Reserves memory for a specified number of elements.
transforming, and modifying elements. Algorithms are designed to work with std::endl;
Standard Library and has become a cornerstone of modern C++ development.
different container types and follow a consistent interface, promoting code 16. `swap()`: Swaps the contents of two vectors.
// Modify elements
reuse and maintainability. Q8) b) State functions of vector STL. Write a program to explain the same.
Here's an example program that demonstrates the usage of these vector
numbers[0] = 5;
3. Iterators: The vector is a dynamic array implementation in the Standard Template functions:
Library (STL) in C++. It provides a resizable container that stores elements in a numbers.at(1) = 15;
Iterators provide a way to traverse and access elements within a container. #include <iostream>
contiguous memory block. The vector class offers various functions to
They act as generalized pointers and provide a uniform interface for working // Insert elements at a specified position
manipulate and access its elements efficiently. #include <vector>
with containers. Different types of iterators, such as input iterators, output
numbers.insert(numbers.begin() + 2, 25);
iterators, forward iterators, bidirectional iterators, and random access int main() {
iterators, provide varying levels of functionality and support. numbers.insert(numbers.end(), {40, 50});
Some of the important functions provided by the vector class are as follows: // Create a vector and insert elements
4. Function Objects: // Remove an element
std::vector<int> numbers;
numbers.erase(numbers.begin() + 1);
1. `push_back()`: Inserts an element at the end of the vector.

// Print vector elements after modifications // Remove an element

std::cout << "Modified vector elements: "; 1. Array: A fixed-size array that stores a sequence of elements with a Let's take an example and explain the vector container using a program: numbers.erase(numbers.begin() + 2);
specified size.
for (const auto& num : numbers) { // Print vector elements after modifications
2. Vector: A dynamic array that can grow or shrink in size as needed.
std::cout << num << " "; ```cpp std::cout << "Modified vector elements: ";
3. List: A doubly-linked list that allows efficient insertion and deletion at any
} #include <iostream> for (const auto& num : numbers) {
position.
std::cout << std::endl; #include <vector> std::cout << num << " ";
4. Forward List: A singly-linked list that allows efficient insertion and deletion
// Clear the vector at the beginning or after a specified position. }

numbers.clear(); 5. Deque: A double-ended queue that allows efficient insertion and deletion int main() { std::cout << std::endl;
at both ends.
// Check vector size after clearing // Create a vector and insert elements // Check vector size
6. Stack: A container that follows the Last-In-First-Out (LIFO) principle.
std::cout << "Vector size after clearing: " << numbers.size() << std::endl; std::vector<int> numbers; std::cout << "Vector size: " << numbers.size() << std::endl;
7. Queue: A container that follows the First-In-First-Out (FIFO) principle.
numbers.push_back(10); // Clear the vector
8. Priority Queue: A container that maintains a sorted sequence of elements,
return 0; numbers.push_back(20); numbers.clear();
with the highest-priority element at the front.
} numbers.push_back(30); // Check vector size after clearing
9. Set: A container that stores unique elements in a sorted order.
In this program, we include the necessary header files `<iostream>` and // Access and print vector elements std::cout << "Vector size after clearing: " << numbers.size() << std::endl;
10. Map: A container that stores key-value pairs, with unique keys and a
`<vector>` to work with the vector class from the STL.
sorted order based on the keys. std::cout << "Vector elements: "; return 0;
We create a vector called `numbers` to store integer values. We use the
11. Multiset: Similar to a set, but allows duplicate elements. for (const auto& num : numbers) { }
`push_back` function to insert elements into
12. Multimap: Similar to a map, but allows duplicate keys. std::cout << num << " "; In this program, we include the necessary header files `<iostream>` and
Q8) c) What is container ? List the container classes in C++.Explain any one of
`<vector>` to work with the vector container class from the STL.
them using program. 13. Unordered Set: A container that stores unique elements in an unordered }
manner, providing faster lookup and retrieval than a set. We create a vector called `numbers` to store integer values. We use the
In C++, a container is a data structure that stores and manages a collection of std::cout << std::endl;
`push_back` function to insert elements into the vector. We then iterate over
elements. It provides methods to insert, access, and manipulate the elements 14. Unordered Map: A container that stores key-value pairs in an unordered
// Modify an element the vector and print its elements.
in a structured and efficient manner. Containers are an essential part of the manner, providing faster lookup and retrieval than a map.
Standard Template Library (STL) and provide various types and numbers[0] = 5; Next, we modify an element by assigning a new value to it using the indexing
15. Unordered Multiset: Similar to an unordered set, but allows duplicate
characteristics for different use cases. operator
elements. // Insert an element at a specified position

16. Unordered Multimap: Similar to an unordered map, but allows duplicate numbers.insert(numbers.begin() + 1, 15);
Here are the container classes in C++: keys.
Click on the below links

https://www.instagram.com/
sppu_engineering_update

For University updates on Instagram Page


Like exam form , scholarship form, timetables ,
Photocopy , revolution , gov exam

https://t.me/SPPU_SE_COMP

First Year & second year telegram channel


Notes , micro PDF, books Pdf , solved question paper

https://www.whatsapp.com/channel/0029VaAhRMdAzNbmPG0jyq2x

For University updates on WhatsApp channel


Like exam form , scholarship form, timetables ,
Photocopy , revolution , gov exam

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy