OOP Imp
OOP Imp
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>
if (argc < 2) {
cout << "Usage: " << argv[0] << " <name>" << endl;
return 1;
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!
template <typename T> // Function template to add two values of any type
T add(T a, T b) {
return a + b;
}
int main() {
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>
template <typename T1, typename T2> // Class template for a simple Pair
class Pair {
public:
T1 first;
T2 second;
};
int main() {
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.
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;
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;
}
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
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;
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.
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
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
}
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
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;
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
class Complex {
private:
public:
Complex result;
return result;
void input() {
cout << "Complex Number: " << real << " + " << imag << "i" << endl;
};
int main() {
cout << "Enter values for the first complex number:" << endl;
complex1.input();
cout << "\nEnter values for the second complex number:" << endl;
complex2.input();
complex1.display();
complex2.display();
sum.display();
return 0;
public:
};
class Circle : public Shape { // Derived class with overridden virtual function
public:
};
int main() {
shapePtr = &circle;
return 0;
#include <vector>
int main() {
myVector.push_back(2);
myVector.push_back(3);
cout << "Elements in the vector:"; // Display the elements using iterators
cout << "Element at index 1: " << myVector.at(1) << endl; // Access elements using at.
cout << "First element: " << myVector.front() << endl;
cout << "Is the vector empty? " << (myVector.empty() ? "Yes" : "No") << endl;
cout << "Vector after pop_back:"; // Display the vector after pop_back
return 0;
DEQUE :
#include <iostream>
#include <deque>
int main() {
myDeque.push_back(2);
myDeque.push_front(0);
myDeque.push_back(3);
cout << "Elements in the deque:"; // Display the elements using iterators
cout << "Is the deque empty? " << (myDeque.empty() ? "Yes" : "No") << endl;
// Remove the first and last elements using pop_front and pop_back
myDeque.pop_front();
myDeque.pop_back();
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>
int main() {
int number;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
} else {
cout << "You entered: " << number << endl; // Display the entered integer
return 0;
int main() {
try {
ifstream inputFile(filePath); // Attempt to open the file
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>
return a + b;
return a + b;
}
template <typename T> // Function template to add two values of any type
T add(T a, T b) {
return a + b;
int main() {
// Overloaded functions
// Function template
cout << add(3.5, 4.2) << endl; // Calls add<T>(T, T) with T=double
return 0;
#include <fstream>
#include <string>
class FileCreator {
public:
if (outputFile.is_open()) {
cout << "File '" << filename << "' created successfully with content:\n" << content << endl;
} else {
cerr << "Error creating file '" << filename << "'." << endl;
};
int main() {
return 0;