C ++ 2023 Previous Year Solved



Q1. (a) Inline function

  • An inline function is a special type of function in C++ that, when used, copies the entire function code directly into the place where it is called, instead of calling the function entirely.
  • This is often used for small, frequently used functions to reduce the function call overhead.
1#include<iostream>
2using namespace std;
3
4// Inline function declaration
5inline int add(int a, int b);
6
7int main() {
8    int result = add(5, 7);
9    cout << "Sum: " << result << endl;
10    return 0;
11}
12
13// Inline function definition
14inline int add(int a, int b) {
15    return a + b;
16}
17
  • In this example, the add function is declared and defined as inline.
  • When the add function is called in the main function, the compiler replaces the function call with the actual code of the function, resulting in more efficient code execution.

(B) Describe the various benefits of OOP.

  • Modularity: Break down a complex system into smaller, manageable modules (classes).
  • Reusability: Promotes reuse of classes and objects in different parts of a program.
  • Encapsulation: Bundles data and methods that operate on the data within a single unit, preventing external interference.

(C) New Vs Delete

  • New Operator: Allocates memory for a single object on the heap and returns a pointer to that object.
  • Delete Operator: Deallocates memory that was allocated using a new keyword.
1#include<iostream>
2using namespace std;
3
4int main() {
5    // Dynamically allocate an integer
6    int* num = new int;
7
8    // Assign a value to the allocated memory
9    *num = 42;
10
11    // Output the value
12    cout << "Value: " << *num << endl;
13
14    // Deallocate the memory
15    delete num;
16
17    return 0;
18}
  • new int: Dynamically allocates memory for a single integer.
  • *num = 42; Assigns the value 42 to the memory location pointed by num.
  • cout << "Value: " << *num << endl; Prints the value stored in the dynamically allocated memory using the (*).
  • delete num: Deallocates (frees) the memory previously allocated by new. This step is crucial to avoid memory leaks.

(d) Static Data Member

  • A static data member in a class is shared by all instances of that class.
  • It is declared with the static keyword and exists independently of any specific object of the class.
1class MyClass {
2public:
3    // Static data member
4    static int count;
5
6    // Constructor to increment count
7    MyClass() {
8        count++;
9    }
10};
11
12// Initializing static data member
13int MyClass::count = 0;
14
15int main() {
16    MyClass obj1;
17    MyClass obj2;
18
19    // Accessing static data member using class name
20    cout << "Number of objects: " << MyClass::count << endl;
21
22    return 0;
23}
24
  • In this example, the count static data member is shared among all objects of the class MyClass.
  • Each time an object is created, the count is incremented for any specific object of the class.

(e) Copy Constructor

A copy constructor is a special constructor that creates a new object as a copy of an existing object.
1#include <iostream>
2using namespace std;
3
4class Number
5{
6    int a;
7
8public:
9    Number()
10    {
11        a = 0;
12    }
13
14    Number(int num)
15    {
16        a = num;
17    }
18    // When no copy constructor is found, compiler supplies its own copy constructor
19    Number(Number &obj)
20    {
21        cout << "Copy constructor called !!!" << endl;
22        a = obj.a;
23    }
24
25    void display()
26    {
27        cout << "The number for this object is " << a << endl;
28    }
29};
30/*
31 note: copy constructor will not invoked or call when object is already created.
32*/
33int main()
34{
35
36    Number x, y, z(45);
37    x.display();
38    y.display();
39    z.display();
40
41   
42}

(F) Virtual Base Class

A virtual base class is used in multiple inheritance to avoid the "diamond problem" by ensuring that there is only one instance of the base class shared among the derived classes.
1#include<iostream>
2using namespace std;
3
4// Virtual base class
5class Shape {
6public:
7    virtual void draw() {
8        cout << "Drawing shape" << endl;
9    }
10};
11
12// Derived classes
13class Circle : virtual public Shape {
14public:
15    void draw() override {
16        cout << "Drawing circle" << endl;
17    }
18};
19
20class Square : virtual public Shape {
21public:
22    void draw() override {
23        cout << "Drawing square" << endl;
24    }
25};
26
27// Derived class inheriting from both Circle and Square
28class Sphere : public Circle, public Square {
29};
30
31int main() {
32    Sphere sphere;
33    sphere.draw();  // Ambiguous call issue without virtual inheritance
34
35    return 0;
36}
  • In this example, the Shape class is a virtual base class, and the Circle and Square classes use virtual inheritance.
  • The Sphere class inherits from both Circle and Square, preventing the diamond problem.

(G) Friend Function

  • A friend function is a function that is not a member of a class but is granted access to the class's private and protected members.
  • It is declared with the friend keyword in the class definition.
1#include <iostream>
2using namespace std;
3
4// Declaration of a class named Complex
5class Complex {
6    int a, b;
7
8    // Declaration of a friend function named Sum
9    friend Complex Sum(Complex c1, Complex c2);
10
11public:
12    // Member function to input values for 'a' and 'b'
13    void getdata() {
14        cout << "\n Enter the value of a - ";
15        cin >> a;
16        cout << " Enter the value of b - ";
17        cin >> b;
18    }
19
20    // Member function to print the values of 'a' and 'b'
21    void printNo() {
22        cout << "\n The value of a is : " << a << endl;
23        cout << " The value of b is : " << b << endl;
24    }
25};
26
27// Definition of the friend function Sum
28Complex Sum(Complex c1, Complex c2) {
29    Complex c3;
30    c3.a = c1.a + c2.a;
31    c3.b = c1.b + c2.b;
32
33    return c3;
34}
35
36// The starting point of the program
37int main() {
38    // Create objects of Complex class
39    Complex c1, c2, sum;
40
41    // Input values for c1 and c2
42    c1.getdata();
43    c2.getdata();
44
45    // Call the friend function Sum to add c1 and c2, store result in sum
46    sum = Sum(c1, c2);
47
48    // Print the result
49    sum.printNo();
50
51    // Indicate successful program execution
52    return 0;
53}

(H) Class Template

  • A class template in C++ allows you to define a generic class that can work with different data types.
  • It provides a way to create classes with members that can vary in type.

(I) This Pointer

  • The this pointer is a pointer available in C++ that points to the object for which the member function is called.
  • It is used to differentiate between the calling object's data members and local variables with the same names.
1#include<iostream>
2using namespace std;
3
4class MyClass {
5private:
6    int value;
7
8public:
9    void setValue(int value) {
10        // Using the this pointer to differentiate between
11        // the class member and the local variable
12        this->value = value;
13    }
14
15    void displayValue() {
16        cout << "Value: " << value << endl;
17    }
18};
19
20int main() {
21    MyClass obj;
22    obj.setValue(42);
23    obj.displayValue();
24
25    return 0;
26}
27
28
In this example, the this pointer is used within the setValue function to assign the value passed as a parameter to the class member variable.
It helps distinguish between the local variable and the class member with the same name.

(j) Early Vs Late Binding

  • Early Binding (Static Binding): The association between a function call and the function definition is determined at compile time.
  • This is also known as compile-time polymorphism.
  • In the early binding example, the function calls are resolved at compile time based on the declared type.
  • Late Binding (Dynamic Binding): The association between a function call and the function definition is determined at runtime.
  • This is also known as runtime polymorphism and is achieved through virtual functions.
  • In the late binding example, virtual functions are used, and the function calls are resolved at runtime.
Q2. (a) Explain the following terms:
(i) Literals
Literals are constant values that represent fixed values and data types in a program. In C++, there are several types of literals, including:
  • Integer Literals: Represent whole numbers without any decimal point (e.g., 42).
  • Floating-point Literals: Represent numbers with a decimal point or in scientific notation (e.g., 3.14 or 2.5e3).
  • Character Literals: Represent individual characters enclosed in single quotes (e.g., 'A').
  • String Literals: Represent sequences of characters enclosed in double quotes (e.g., "Hello").
  • Boolean Literals: Represent either true or false.
  • Nullptr Literal: Represents a null pointer and is denoted by the keyword nullptr.
(ii) Implicit Conversion
  • Implicit conversion, also known as type conversion, refers to the automatic conversion of one data type to another by the compiler without the need for explicit instructions from the programmer.
  • This conversion occurs when an expression involving different data types is encountered.
  • Implicit conversion is convenient but should be used with caution, as it may lead to unexpected behavior if not handled carefully.

b) Write a program that will find out whether the given number is even or odd. If it is an odd number then find out whether it is prime or not?

1#include<iostream>
2#include<cmath> // Required for sqrt function
3
4using namespace std;
5
6// Function to check if a number is prime
7bool isPrime(int num) {
8    if (num <= 1) {
9        return false;
10    }
11    for (int i = 2; i <= sqrt(num); ++i) {
12        if (num % i == 0) {
13            return false;
14        }
15    }
16    return true;
17}
18
19int main() {
20    // Input
21    int number;
22    cout << "Enter a number: ";
23    cin >> number;
24
25    // Check if the number is even or odd
26    if (number % 2 == 0) {
27        cout << number << " is an even number." << endl;
28    } else {
29        cout << number << " is an odd number." << endl;
30
31        // Check if the odd number is prime
32        if (isPrime(number)) {
33            cout << number << " is a prime number." << endl;
34        } else {
35            cout << number << " is not a prime number." << endl;
36        }
37    }
38
39    return 0;
40}
41

Q3 . (a) Illustrate the comparison between C and C++.

Object-Oriented Programming (OOP):
  • C: Procedural programming language without native support for OOP concepts.
  • C++: Extends C with features like classes, objects, inheritance, and polymorphism, providing a comprehensive OOP framework.
Standard Template Library (STL):
  • C: Lacks a standardized template library.
  • C++: Includes the STL, offering a collection of template classes and functions for common data structures and algorithms.
Memory Management:
  • C: Relies on manual memory management using functions like malloc and free.
  • C++: Supports both manual memory management and automatic memory management through features like constructors, destructors, and the new and delete operators.
Function Overloading:
  • C: Does not support function overloading.
  • C++: Allows multiple functions with the same name but different parameter lists, enhancing code readability and flexibility.

(b) Describe the concepts of parameter passing by value, reference and pointer with the help of an example.

1. Parameter Passing by Value:
  • In parameter passing by value, the actual value of the argument is passed to the function.
  • Changes made to the parameter within the function do not affect the original value outside the function.
1#include <iostream>
2using namespace std;
3
4class Swap
5{
6
7public:
8    int a, b, swap;
9
10    void getData()
11    {
12        cout << "enter the value of a \n";
13        cin >> a;
14        cout << " \nenter the value of b \n";
15        cin >> b;
16    }
17
18    void SwapByValue()
19    {
20        swap = a;
21        a = b;
22        b = swap;
23    }
24
25    void DisplayData()
26    {
27        cout << "swaped value of a is "
28             << a;
29        cout << " swaped value of b is "
30             << b;
31    }
32};
33
34int main()
35{
36    Swap s;
37    s.getData();
38    s.SwapByValue();
39    s.DisplayData();
40}
2. Parameter Passing by Reference:
  • In parameter passing by reference, the memory address of the actual argument is passed to the function.
  • Changes made to the parameter within the function directly affect the original value outside the function.
1// call by reference using class
2#include <iostream>
3using namespace std;
4class Swap
5{
6
7    // int a, b;
8
9    // priavte , protected
10public:
11    void swapReference(int &a, int &b)
12    {
13        int temp = a;
14        a = b;
15        b = temp;
16    }
17};
18int main()
19{
20
21    Swap s;
22    int x, y;
23
24    cout << " Please enter the value of x  - ";
25    cin >> x;
26
27    cout << "\n Please enter the value of y  - ";
28    cin >> y;
29
30    s.swapReference(x, y);
31    cout << " \n swapped value of x is "
32         << x;
33    cout << "\n swapped value of y is "
34         << y;
35
36    return 0;
37}
38
3. Parameter Passing by Pointer:
  • In parameter passing by pointer, the memory address (pointer) of the actual argument is passed to the function.
  • Like passing by reference, changes made to the parameter through the pointer affect the original value outside the function.
1#include <iostream>
2using namespace std;
3
4class Swap
5{
6public:
7    void swapPointer(int *a, int *b)
8    {
9        int temp = *a;
10        *a = *b;
11        *b = temp;
12    }
13};
14
15int main()
16{
17    Swap s;
18    int x, y;
19
20    cout << "Please enter the value of x: ";
21    cin >> x;
22
23    cout << "Please enter the value of y: ";
24    cin >> y;
25
26    s.swapPointer(&x, &y);
27
28    cout << "\nSwapped value of x is " << x;
29    cout << "\nSwapped value of y is " << y;
30
31    return 0;
32}

Q4. (a) Explain the concept of constructor overloading and function overloading.

Constructor Overloading:
  • Constructor overloading in C++ involves defining multiple constructors within a class, each with a different set of parameters.
  • Purpose: Allows an object to be initialized in different ways based on the number or types of parameters provided during object creation.
Example:
1#include<iostream>
2using namespace std;
3
4class MyClass {
5public:
6    // Default constructor
7    MyClass() {
8        cout << "Default constructor called" << endl;
9    }
10
11    // Parameterized constructor
12    MyClass(int value) {
13        cout << "Parameterized constructor called with value: " << value << endl;
14    }
15};
16
17int main() {
18    // Creating objects using different constructors
19    MyClass obj1;        // Default constructor
20    MyClass obj2(42);    // Parameterized constructor
21
22    return 0;
23}
24
Function Overloading
  • Function overloading allows multiple functions with the same name but different parameter lists within the same scope.
  • Purpose: Provides flexibility in using functions with various argument types or numbers of arguments.
Example:
1#include<iostream>
2using namespace std;
3
4// Function overloading
5int add(int a, int b) {
6    return a + b;
7}
8
9double add(double a, double b) {
10    return a + b;
11}
12
13int main() {
14    // Using overloaded functions
15    cout << "Sum (int): " << add(5, 7) << endl;
16    cout << "Sum (double): " << add(3.5, 4.2) << endl;
17
18    return 0;
19}
20

(b) What do you understand by access specifiers? What are these access specifiers?

  • In C++, access specifiers are keywords used in class definitions to control the visibility and accessibility of class members (attributes and methods) from outside the class.
  • They determine how the class's members can be accessed and modified by other parts of the program.
Types of Access Specifiers:
Public:
  • Members declared as public are accessible from any part of the program,including outside the class.
1class MyClass {
2public:
3    int publicVar;
4    void publicMethod() {
5        // Code here
6    }
7};
8
Private
  • Members declared as private are only accessible within the class. They cannot be accessed directly from outside the class.
1class MyClass {
2private:
3    int privateVar;
4    void privateMethod() {
5        // Code here
6    }
7};
8
9
Protected:
Similar to private, members declared as protected are accessible within the class and its derived classes (in the context of inheritance).
1class BaseClass {
2protected:
3    int protectedVar;
4};
5
6class DerivedClass : public BaseClass {
7    // Can access protectedVar here
8};
9
Inheritance:
  • Access specifiers play a role in determining the visibility of members in derived classes when using inheritance.
  • They define the level of access to base class members in the derived class.
Q5. Private members: Name 20 characters Subject 10 characters Basic, DA, HRA float and Salary float. Calculate() function computes the salary and returns it. Salary is sum of Basic, DA , HRA and Public members.
Readdata() function accepts the data values and invokes the calculate function. Displaydata () function prints the data on the screen.
1 Class Definition for Teacher:
2#include<iostream>
3#include<iomanip>
4#include<string>
5using namespace std;
6
7class Teacher {
8private:
9    char Name[21];
10    char Subject[11];
11    float Basic;
12    float DA;
13    float HRA;
14    float Salary;
15
16    // Private member function to calculate salary
17    void Calculate() {
18        Salary = Basic + DA + HRA;
19    }
20
21public:
22    // Public member function to read data and invoke Calculate
23    void ReadData() {
24        cout << "Enter Teacher's Name (up to 20 characters): ";
25        cin.ignore();  // Clear the input buffer
26        cin.getline(Name, 21);
27
28        cout << "Enter Subject (up to 10 characters): ";
29        cin.getline(Subject, 11);
30
31        cout << "Enter Basic Salary: ";
32        cin >> Basic;
33
34        cout << "Enter DA: ";
35        cin >> DA;
36
37        cout << "Enter HRA: ";
38        cin >> HRA;
39
40        Calculate();  // Invoke the Calculate function
41    }
42
43    // Public member function to display data
44    void DisplayData() {
45        cout << "\nTeacher's Information:\n";
46        cout << "Name: " << Name << endl;
47        cout << "Subject: " << Subject << endl;
48        cout << fixed << setprecision(2);
49        cout << "Basic Salary: $" << Basic << endl;
50        cout << "DA: $" << DA << endl;
51        cout << "HRA: $" << HRA << endl;
52        cout << "Total Salary: $" << Salary << endl;
53    }
54};
55
56int main() {
57    Teacher teacher;
58
59    // Read data and display information
60    teacher.ReadData();
61    teacher.DisplayData();
62
63    return 0;
64}
65
66

(b) What are the special properties of a constructor

Automatic Invocation:
  • Constructors are automatically invoked when an object of the class is created.
  • They ensure that necessary setup operations are performed before the object is used.
Same Name as Class:
  • Constructors have the same name as the class and do not have a return type.
  • They are used to initialize the object's state during creation.
Multiple Constructors (Overloading):
  • A class can have multiple constructors, allowing different ways to initialize objects based on the provided arguments.
  • Constructor overloading provides flexibility in object creation.
Initialization of Member Variables:
  • Constructors initialize the member variables of the class, ensuring that the object starts with a consistent and valid state.

Q6. (a) How data member and member function present in public mode in class be accessed through pointer object? Explain it by taking an example

  • Accessing Public Data Members and Member Functions through a Pointer
  • In C++, data members and member functions of a class can be accessed through a pointer to an object.
  • This involves using the arrow operator (->) with the pointer to access the members. Here's an example to illustrate the concept:
1#include<iostream>
2#include<string>
3using namespace std;
4
5class Student {
6public:
7    // Public data members
8    string name;
9    int age;
10
11    // Public member function
12    void displayInfo() {
13        cout << "Name: " << name << endl;
14        cout << "Age: " << age << endl;
15    }
16};
17
18int main() {
19    // Creating an object of the class
20    Student studentObj;
21    studentObj.name = "John Doe";
22    studentObj.age = 20;
23
24    // Creating a pointer to the object
25    Student *ptrStudent = &studentObj;
26
27    // Accessing public data members through the pointer
28    cout << "Name through pointer: " << ptrStudent->name << endl;
29    cout << "Age through pointer: " << ptrStudent->age << endl;
30
31    // Accessing public member function through the pointer
32    ptrStudent->displayInfo();
33
34    return 0;
35}
36
Explanation:
Object Creation:
  • An object of the class Student named studentObj is created.
Pointer Creation:
  • A pointer ptrStudent is created, pointing to the address of the studentObj.
Accessing Public Data Members:
  • Public data members (name and age) are accessed through the pointer using the arrow operator (->).
Accessing Public Member Function:
  • The public member function displayInfo() is accessed through the pointer using the arrow operator.

(b) Create class COMPLEX and overload binary operator to add objects. Using friend functions.

Overloading Binary Operator for Addition in Class COMPLEX using Friend Function
1#include<iostream>
2using namespace std;
3
4class COMPLEX {
5private:
6    float real;
7    float imag;
8
9public:
10    // Constructor to initialize complex numbers
11    COMPLEX(float r = 0, float i = 0) : real(r), imag(i) {}
12
13    // Friend function to overload binary operator '+'
14    friend COMPLEX operator+(const COMPLEX& c1, const COMPLEX& c2);
15
16    // Member function to display complex number
17    void display() {
18        cout << "Complex Number: " << real << " + " << imag << "i" << endl;
19    }
20};
21
22// Definition of the friend function to overload '+'
23COMPLEX operator+(const COMPLEX& c1, const COMPLEX& c2) {
24    COMPLEX temp;
25    temp.real = c1.real + c2.real;
26    temp.imag = c1.imag + c2.imag;
27    return temp;
28}
29
30int main() {
31    // Creating two complex numbers
32    COMPLEX complex1(3.0, 4.0);
33    COMPLEX complex2(1.5, 2.5);
34
35    // Using the overloaded '+' operator to add complex numbers
36    COMPLEX sum = complex1 + complex2;
37
38    // Displaying the result
39    cout << "Sum of Complex Numbers:" << endl;
40    sum.display();
41
42    return 0;
43}
44
45
Explanation:
  • COMPLEX: This is the name of the class. It looks like this class represents complex numbers.
  • (float r = 0, float i = 0): This part defines the constructor for the class.
  • : real(r), imag(i): This is the member initializer list. It is used to initialize the member variables of the class (real and imag) with the values passed to the constructor.
  • Friend Function: The operator+ function is declared as a friend function inside the class to allow it to access private members.
  • Operator Overloading: The operator+ function is defined outside the class to perform addition of complex numbers.
  • Main Function: Two complex numbers (complex1 and complex2) are created.
  • The overloaded + operator is used to add these complex numbers, and the result is stored in the sum object.
  • Displaying Result:The result of the addition is displayed using the display member function.

Q7. Define an inheritance and its advantage? Explain the types of inheritance and Its Advantages

  • Inheritance is a fundamental concept in object-oriented programming (OOP) that allows a class(subclass or derived class) to inherit properties and behaviors from another class (base class or parent class).
  • The subclass can reuse and extend the functionality of the base class, promoting code reusability and modularity.
Advantages of Inheritance:
  • Code Reusability: Inheritance enables the reuse of code from existing classes, reducing redundancy.
  • Extensibility: Subclasses can extend the functionality of the base class by adding new attributes and methods.
  • Inheritance facilitates polymorphism, allowing objects of the derived class to be treated as objects of the base class.
Types of Inheritance:
Single Inheritance:
A class inherits from only one base class.
1class Base {
2    // Base class definition
3};
4
5class Derived : public Base {
6    // Derived class inherits from Base
7};
8
9Multiple Inheritance:
10A class inherits from more than one base class.
11Example:
12class Base1 {
13    // Base class definition
14};
15
16class Base2 {
17    // Another base class definition
18};
19
20class Derived : public Base1, public Base2 {
21    // Derived class inherits from multiple base classes
22};
23
Multiple Inheritance:
A class inherits from more than one base class.
1class Base1 {
2    // Base class definition
3};
4
5class Base2 {
6    // Another base class definition
7};
8
9class Derived : public Base1, public Base2 {
10    // Derived class inherits from multiple base classes
11};
12
13
Multilevel Inheritance:
A class is derived from another derived class, forming a chain of inheritance.
1class Base {
2    // Base class definition
3};
4
5class Derived1 : public Base {
6    // First derived class
7};
8
9class Derived2 : public Derived1 {
10    // Second derived class
11};
12
Hierarchical Inheritance:
Multiple classes are derived from a single base class.
1class Base {
2    // Base class definition
3};
4
5class Derived1 : public Base {
6    // First derived class
7};
8
9class Derived2 : public Base {
10    // Second derived class
11};
12
Hybrid (Virtual) Inheritance:
A combination of multiple and hierarchical inheritance, involving the use of virtual base classes.
1class Base {
2    // Base class definition
3};
4
5class Derived1 : virtual public Base {
6    // First derived class with virtual inheritance
7};
8
9class Derived2 : virtual public Base {
10    // Second derived class with virtual inheritance
11};
12
13class FinalDerived : public Derived1, public Derived2 {
14    // Final derived class
15};
16

Q8. (a) What do you mean by generic programming? Write a program to swap the any two different types of variables using function template.

  • Generic programming is a programming paradigm that emphasizes writing code in a way that is independent of data types.
  • It allows algorithms and data structures to be written in a generic way, making them applicable to various types without the need for duplication.
1#include<iostream>
2using namespace std;
3
4// Function template for swapping any two variables of different types
5template <typename T>
6void swapVariables(T &a, T &b) {
7    T temp = a;
8    a = b;
9    b = temp;
10}
11
12int main() {
13    // Example with integer variables
14    int num1 = 5, num2 = 10;
15    cout << "Before swapping (int): " << num1 << ", " << num2 << endl;
16    swapVariables(num1, num2);
17    cout << "After swapping (int): " << num1 << ", " << num2 << endl;
18
19    // Example with double variables
20    double double1 = 3.14, double2 = 2.718;
21    cout << "Before swapping (double): " << double1 << ", " << double2 << endl;
22    swapVariables(double1, double2);
23    cout << "After swapping (double): " << double1 << ", " << double2 << endl;
24
25    return 0;
26}
27
Explanation:
Function Template (swapVariables):
  • The swapVariables function template is defined to swap two variables of any data type.
  • The template parameter typename T allows the function to work with variables of different types.
Main Function:
  • The program demonstrates the use of the swapVariables function template with integer and double variables.
  • Variables are passed to the function, and their values are swapped.
Output: The program outputs the values of variables before and after swapping for both integer and double examples.

(b) Create a class Stack that throws Overflow and Underflow exceptions

1#include<iostream>
2#include<stdexcept>
3using namespace std;
4
5class Stack {
6private:
7    static const int MAX_SIZE = 5;  // Maximum size of the stack
8    int data[MAX_SIZE];             // Array to store stack elements
9    int top;                        // Index of the top element
10
11public:
12    // Constructor to initialize the stack
13    Stack() : top(-1) {}
14
15    // Function to push an element onto the stack
16    void push(int value) {
17        if (top == MAX_SIZE - 1) {
18            // Throw Overflow exception if the stack is full
19            throw overflow_error("Stack Overflow");
20        }
21        data[++top] = value;
22    }
23
24    // Function to pop an element from the stack
25    int pop() {
26        if (top == -1) {
27            // Throw Underflow exception if the stack is empty
28            throw underflow_error("Stack Underflow");
29        }
30        return data[top--];
31    }
32
33    // Function to display the elements of the stack
34    void display() {
35        if (top == -1) {
36            cout << "Stack is empty." << endl;
37            return;
38        }
39        cout << "Stack elements: ";
40        for (int i = 0; i <= top; ++i) {
41            cout << data[i] << " ";
42        }
43        cout << endl;
44    }
45};
46
47int main() {
48    try {
49        // Creating an instance of the Stack class
50        Stack myStack;
51
52        // Pushing elements onto the stack
53        myStack.push(10);
54        myStack.push(20);
55        myStack.push(30);
56        myStack.display();
57
58        // Popping elements from the stack
59        cout << "Popped: " << myStack.pop() << endl;
60        cout << "Popped: " << myStack.pop() << endl;
61        myStack.display();
62
63        // Trying to pop from an empty stack (Underflow)
64        // Uncommenting the next line will result in an underflow exception
65        // cout << "Popped: " << myStack.pop() << endl;
66
67        // Pushing more elements to fill the stack (Overflow)
68        myStack.push(40);
69        myStack.push(50);
70        myStack.push(60);
71        myStack.push(70);  // Uncommenting this line will result in an overflow exception
72
73        myStack.display();
74    } catch (const exception &e) {
75        // Catching and handling exceptions
76        cerr << "Exception: " << e.what() << endl;
77    }
78
79    return 0;
80}
81
Explanation:
Stack Class:
  • The Stack class is implemented with an array to store elements and a variable to track the top of the stack.
  • The push function adds an element to the stack, and the pop function removes an element.
  • The display function prints the elements of the stack.
Exception Handling:
  • The program uses the std::overflow_error and std::underflow_error exceptions to handle stack overflow and underflow situations.
  • When an overflow or underflow condition is detected, an exception is thrown with an appropriate error message.
Main Function:
  • The main function demonstrates the use of the Stack class by pushing and popping elements from the stack.
  • It also includes examples of stack underflow and overflow scenarios, with appropriate exception handling.
Explanation and Modification:
  • The provided code demonstrates inheritance in C++, where the Programmer class is derived from the Employee base class.
  • Here are some explanations and a slight modification for clarity:
Visibility Modes:
  • The Employee class has two data members: id and salary, with a parameterized constructor to initialize them.
  • The Programmer class is derived publicly from the Employee class, which means that both id and salary of the base class are publicly inherited.
Object Creation:
  • Objects of the Employee class (harry and rohan) are created and their salary values are accessed.
  • An object of the Programmer class (p) is created, and its languageCode, id, and the getData method are accessed.
Modification for Clarity: The getData method in the Programmer class attempts to access the id member directly, but it is already accessible due to public inheritance. The method can be simplified.
1#include <iostream>
2using namespace std;
3
4// Base Class
5class Employee
6{
7public:
8    int id;
9    float salary;
10
11    // Parameterized constructor
12    Employee(int inpId)
13    {
14        id = inpId;
15        salary = 34.0;
16    }
17
18    // Default constructor
19    Employee() {}
20};
21
22// Derived Class (Programmer) from Employee Base class
23class Programmer : public Employee
24{
25public:
26    int languageCode;
27
28    // Parameterized constructor
29    Programmer(int inpId) : Employee(inpId)
30    {
31        languageCode = 9;
32    }
33
34    // Simplified method for clarity
35    void getData()
36    {
37        cout << id << endl;
38    }
39};
40
41int main()
42{
43    // Creating objects of Employee class
44    Employee harry(1), rohan(2);
45    cout << "Harry's Salary: " << harry.salary << endl;
46    cout << "Rohan's Salary: " << rohan.salary << endl;
47
48    // Creating object of Programmer class
49    Programmer p(10);
50    cout << "Language Code: " << p.languageCode << endl;
51    cout << "ID: " << p.id << endl;
52    p.getData();
53
54    return 0;
55}
56

Q9. (a) Explain the following terms: seekg , getline and write

(i) seekg:
  • seekg is a function in C++ used for setting the position of the get pointer (istream pointer) within a file.
  • Usage: streampos seekg(streampos pos);
  • It is commonly used with the ifstream (input file stream) to move the read pointer to a specified position within the file.
  • pos is the absolute position within the file where the get pointer will be moved.
(ii) getline:
  • getline is a function in C++ used for reading a line from an input stream (such as a file or cin) into a string.
  • istream& getline(istream& is, string& str, char delim = '\n');
  • It reads characters from the input stream until the specified delimiter ('\n' by default) or the end of the file is encountered.
  • The read characters are stored in the string str.
(iii) write:
  • write is a function in C++ used for writing a block of data directly to an output stream (such as a file).
  • Usage:ostream& write(const char* s, streamsize n);
  • It writes n characters from the character array s to the output stream.
  • It is commonly used with the ofstream (output file stream) to write binary data.

(b) File Access Modes:

  • File access modes in C++ determine how a file can be opened and manipulated.
  • They are specified when opening a file using classes such as ifstream or ofstream. Here are the various file access modes:
  • 1.ios::in (Input):
  • Opens a file for reading.
  • Used with classes like ifstream.
  • ifstream inputFile("example.txt", ios::in);
  • 2. ios::out (Output):
  • Opens a file for writing.
  • If the file already exists, its contents are truncated.
  • Used with classes like ofstream.
  • ofstream outputFile("output.txt", ios::out);
  • 3. ios::app (Append):
  • Opens a file for writing, but appends new data at the end of the file.
  • Existing data is not truncated
  • ofstream appendFile("log.txt", ios::app);
  • 4 . ios::ate (At End):
  • Sets the initial position at the end of the file.
  • Useful for both reading and writing.
  • fstream file("data.txt", ios::ate);
  • 5. ios::binary (Binary):
  • Treats the file as a binary file instead of a text file.
  • Useful when reading or writing non-text data.
  • ofstream binary file("data.bin", ios::binary);
  • 6. ios::trunc (Truncate):
  • Used with the ios::out mode to truncate the file if it already exists.
  • If the file does not exist, it is created.
  • ofstream truncFile("output.txt", ios::out | ios::trunc);