{"id":12430,"date":"2024-08-23T10:15:43","date_gmt":"2024-08-23T04:45:43","guid":{"rendered":"https:\/\/www.placementpreparation.io\/blog\/?p=12430"},"modified":"2024-12-26T17:13:06","modified_gmt":"2024-12-26T11:43:06","slug":"cpp-interview-questions-for-freshers","status":"publish","type":"post","link":"https:\/\/www.placementpreparation.io\/blog\/cpp-interview-questions-for-freshers\/","title":{"rendered":"Top C++ Interview Questions for Freshers"},"content":{"rendered":"<?xml encoding=\"utf-8\" ?><p>Are you preparing for your first C++ interview and wondering what questions you might face? Understanding the key C++ interview questions for freshers can give you more clarity.<\/p><p>This blog is here to help you get ready with practical questions that test your real-world problem-solving skills. We&rsquo;ve gathered some of the most common basic C++ interview questions that freshers often encounter.<\/p><p>With this guide, you&rsquo;ll be well-prepared to tackle these C++ interview questions and answers for freshers and make a strong impression in your interview.<\/p><p><a href=\"https:\/\/www.guvi.in\/courses\/programming\/c-plus-plus-beginners\/?utm_source=placement_preparation&amp;utm_medium=blog_banner&amp;utm_campaign=cpp_interview_questions_for_freshers_horizontal\" target=\"_blank\" rel=\"noopener\"><img decoding=\"async\" class=\"alignnone wp-image-10345 size-full\" src=\"https:\/\/www.placementpreparation.io\/blog\/wp-content\/uploads\/2024\/05\/cpp-beginners-course-desktop-banner-horizontal.webp\" alt=\"cpp beginners course desktop banner horizontal\" width=\"2270\" height=\"600\" srcset=\"https:\/\/www.placementpreparation.io\/blog\/wp-content\/uploads\/2024\/05\/cpp-beginners-course-desktop-banner-horizontal.webp 2270w, https:\/\/www.placementpreparation.io\/blog\/wp-content\/uploads\/2024\/05\/cpp-beginners-course-desktop-banner-horizontal-300x79.webp 300w, https:\/\/www.placementpreparation.io\/blog\/wp-content\/uploads\/2024\/05\/cpp-beginners-course-desktop-banner-horizontal-1024x271.webp 1024w, https:\/\/www.placementpreparation.io\/blog\/wp-content\/uploads\/2024\/05\/cpp-beginners-course-desktop-banner-horizontal-768x203.webp 768w, https:\/\/www.placementpreparation.io\/blog\/wp-content\/uploads\/2024\/05\/cpp-beginners-course-desktop-banner-horizontal-1536x406.webp 1536w, https:\/\/www.placementpreparation.io\/blog\/wp-content\/uploads\/2024\/05\/cpp-beginners-course-desktop-banner-horizontal-2048x541.webp 2048w, https:\/\/www.placementpreparation.io\/blog\/wp-content\/uploads\/2024\/05\/cpp-beginners-course-desktop-banner-horizontal-150x40.webp 150w\" sizes=\"(max-width: 2270px) 100vw, 2270px\"><\/a><\/p><h2 id=\"practice-c++-interview-questions\">Practice C++ Interview Questions and Answers<\/h2><p>Below are the top 50 C++ interview questions for freshers with answers:<\/p><h3 id=\"swap-two-numbers\">1. Write a C++ program to swap two numbers without using a third variable.<\/h3><p><strong>Answer:<\/strong><\/p><p>Use arithmetic operations to swap values directly without needing extra space.<\/p><div class=\"su-note\" style=\"border-color:#e5dbc7;border-radius:3px;-moz-border-radius:3px;-webkit-border-radius:3px;\"><div class=\"su-note-inner su-u-clearfix su-u-trim\" style=\"background-color:#FFF5E1;border-color:#ffffff;color:#333333;border-radius:3px;-moz-border-radius:3px;-webkit-border-radius:3px;\">\n<p>int a = 5, b = 10;<br>\na = a + b;<br>\nb = a &ndash; b;<br>\na = a &ndash; b;<\/p>\n<\/div><\/div><h3 id=\"reverse-a-string\">2. How would you reverse a given string in C++ without using the reverse() function?<\/h3><p><strong>Answer:<\/strong><\/p><p>Use a loop to swap characters from the beginning and end of the string until you reach the middle.<\/p><div class=\"su-note\" style=\"border-color:#e5dbc7;border-radius:3px;-moz-border-radius:3px;-webkit-border-radius:3px;\"><div class=\"su-note-inner su-u-clearfix su-u-trim\" style=\"background-color:#FFF5E1;border-color:#ffffff;color:#333333;border-radius:3px;-moz-border-radius:3px;-webkit-border-radius:3px;\">\n<p>std::string str = &ldquo;Hello&rdquo;;<br>\nint n = str.length();<br>\nfor (int i = 0; i &lt; n \/ 2; i++) {<br>\nstd::swap(str[i], str[n &ndash; i &ndash; 1]);<br>\n}<\/p>\n<\/div><\/div><h3 id=\"check-palindrome-number\">3. Write a C++ function to check if a given number is a palindrome.<\/h3><p><strong>Answer:<\/strong><\/p><p>Reverse the number and compare it with the original to check for palindrome property.<\/p><div class=\"su-note\" style=\"border-color:#e5dbc7;border-radius:3px;-moz-border-radius:3px;-webkit-border-radius:3px;\"><div class=\"su-note-inner su-u-clearfix su-u-trim\" style=\"background-color:#FFF5E1;border-color:#ffffff;color:#333333;border-radius:3px;-moz-border-radius:3px;-webkit-border-radius:3px;\">\n<p>bool isPalindrome(int num) {<br>\nint original = num, reversed = 0;<br>\nwhile (num &gt; 0) {<br>\nint digit = num % 10;<br>\nreversed = reversed * 10 + digit;<br>\nnum \/= 10;<br>\n}<br>\nreturn original == reversed;<br>\n}<\/p>\n<\/div><\/div><h3 id=\"factorial-using-recursion\">4. How do you calculate the factorial of a number using recursion in C++?<\/h3><p><strong>Answer:<\/strong><\/p><p>Define a recursive function that multiplies the current number by the factorial of the previous number until it reaches 1.<\/p><div class=\"su-note\" style=\"border-color:#e5dbc7;border-radius:3px;-moz-border-radius:3px;-webkit-border-radius:3px;\"><div class=\"su-note-inner su-u-clearfix su-u-trim\" style=\"background-color:#FFF5E1;border-color:#ffffff;color:#333333;border-radius:3px;-moz-border-radius:3px;-webkit-border-radius:3px;\">\n<p>int factorial(int n) {<br>\nif (n &lt;= 1) return 1;<br>\nreturn n * factorial(n &ndash; 1);<br>\n}<\/p>\n<\/div><\/div><h3 id=\"largest-of-three-numbers\">5. Write a C++ program to find the largest of three numbers using a simple if-else construct.<\/h3><p><strong>Answer:<\/strong><\/p><p>Compare the numbers pairwise and store the largest one at each step.<\/p><div class=\"su-note\" style=\"border-color:#e5dbc7;border-radius:3px;-moz-border-radius:3px;-webkit-border-radius:3px;\"><div class=\"su-note-inner su-u-clearfix su-u-trim\" style=\"background-color:#FFF5E1;border-color:#ffffff;color:#333333;border-radius:3px;-moz-border-radius:3px;-webkit-border-radius:3px;\">\n<p>int largest(int a, int b, int c) {<br>\nif (a &gt; b &amp;&amp; a &gt; c) return a;<br>\nelse if (b &gt; c) return b;<br>\nelse return c;<br>\n}<\/p>\n<\/div><\/div><h3 id=\"basic-student-class\">6. How do you implement a basic class in C++ to represent a Student with attributes like name and roll number?<\/h3><p><strong>Answer:<\/strong><\/p><p>Define a class with private attributes and public methods to set and get the attribute values.<\/p><div class=\"su-note\" style=\"border-color:#e5dbc7;border-radius:3px;-moz-border-radius:3px;-webkit-border-radius:3px;\"><div class=\"su-note-inner su-u-clearfix su-u-trim\" style=\"background-color:#FFF5E1;border-color:#ffffff;color:#333333;border-radius:3px;-moz-border-radius:3px;-webkit-border-radius:3px;\">\n<p>class Student {<br>\nprivate:<br>\nstd::string name;<br>\nint rollNumber;<\/p>\n<p>public:<br>\nvoid setName(std::string n) { name = n; }<br>\nvoid setRollNumber(int r) { rollNumber = r; }<br>\nstd::string getName() { return name; }<br>\nint getRollNumber() { return rollNumber; }<br>\n};<\/p>\n<\/div><\/div><h3 id=\"constructor-overloading-example\">7. Write a C++ program to demonstrate constructor overloading with an example.<\/h3><p><strong>Answer:<\/strong><\/p><p>Create multiple constructors within a class to initialize objects in different ways.<\/p><div class=\"su-note\" style=\"border-color:#e5dbc7;border-radius:3px;-moz-border-radius:3px;-webkit-border-radius:3px;\"><div class=\"su-note-inner su-u-clearfix su-u-trim\" style=\"background-color:#FFF5E1;border-color:#ffffff;color:#333333;border-radius:3px;-moz-border-radius:3px;-webkit-border-radius:3px;\">\n<p>class Rectangle {<br>\nprivate:<br>\nint width, height;<\/p>\n<p>public:<br>\nRectangle() : width(0), height(0) {}<br>\nRectangle(int w, int h) : width(w), height(h) {}<br>\nint area() { return width * height; }<br>\n};<\/p>\n<\/div><\/div><h3 id=\"implement-single-inheritance\">8. How would you implement single inheritance in C++? Demonstrate with a Base and Derived class.<\/h3><p><strong>Answer:<\/strong><\/p><p>Derive a new class from an existing class using the <strong>public<\/strong> inheritance specifier.<\/p><div class=\"su-note\" style=\"border-color:#e5dbc7;border-radius:3px;-moz-border-radius:3px;-webkit-border-radius:3px;\"><div class=\"su-note-inner su-u-clearfix su-u-trim\" style=\"background-color:#FFF5E1;border-color:#ffffff;color:#333333;border-radius:3px;-moz-border-radius:3px;-webkit-border-radius:3px;\">\n<p>class Base {<br>\npublic:<br>\nvoid show() { std::cout &lt;&lt; &ldquo;Base class\\n&rdquo;; }<br>\n};<\/p>\n<p>class Derived : public Base {<br>\npublic:<br>\nvoid display() { std::cout &lt;&lt; &ldquo;Derived class\\n&rdquo;; }<br>\n};<\/p>\n<\/div><\/div><h3 id=\"demonstrate-function-overloading\">9. Write a C++ program that demonstrates the concept of function overloading.<\/h3><p><strong>Answer:<\/strong><\/p><p>Define multiple functions with the same name but different parameters.<\/p><div class=\"su-note\" style=\"border-color:#e5dbc7;border-radius:3px;-moz-border-radius:3px;-webkit-border-radius:3px;\"><div class=\"su-note-inner su-u-clearfix su-u-trim\" style=\"background-color:#FFF5E1;border-color:#ffffff;color:#333333;border-radius:3px;-moz-border-radius:3px;-webkit-border-radius:3px;\">\n<p>class Math {<br>\npublic:<br>\nint add(int a, int b) { return a + b; }<br>\ndouble add(double a, double b) { return a + b; }<br>\n};<\/p>\n<\/div><\/div><h3 id=\"polymorphism-with-virtual-functions\">10. How would you implement polymorphism in C++ using a base class pointer and virtual functions?<\/h3><p><strong>Answer:<\/strong><\/p><p>Create a base class with a virtual function and derive classes that override this function.<\/p><div class=\"su-note\" style=\"border-color:#e5dbc7;border-radius:3px;-moz-border-radius:3px;-webkit-border-radius:3px;\"><div class=\"su-note-inner su-u-clearfix su-u-trim\" style=\"background-color:#FFF5E1;border-color:#ffffff;color:#333333;border-radius:3px;-moz-border-radius:3px;-webkit-border-radius:3px;\">\n<p>class Base {<br>\npublic:<br>\nvirtual void show() { std::cout &lt;&lt; &ldquo;Base class\\n&rdquo;; }<br>\n};<\/p>\n<p>class Derived : public Base {<br>\npublic:<br>\nvoid show() override { std::cout &lt;&lt; &ldquo;Derived class\\n&rdquo;; }<br>\n};<\/p>\n<p>Base* basePtr = new Derived();<br>\nbasePtr-&gt;show(); \/\/ Outputs &ldquo;Derived class&rdquo;<\/p>\n<\/div><\/div><h3 id=\"dynamic-array-allocation\">11. Write a C++ program to dynamically allocate memory for an array and deallocate it.<\/h3><p><strong>Answer:<\/strong><\/p><p>Use <strong>new<\/strong> to allocate memory and <strong>delete[]<\/strong> to deallocate it.<\/p><div class=\"su-note\" style=\"border-color:#e5dbc7;border-radius:3px;-moz-border-radius:3px;-webkit-border-radius:3px;\"><div class=\"su-note-inner su-u-clearfix su-u-trim\" style=\"background-color:#FFF5E1;border-color:#ffffff;color:#333333;border-radius:3px;-moz-border-radius:3px;-webkit-border-radius:3px;\">\n<p>int* arr = new int[10];<br>\n\/\/ Use the array<br>\ndelete[] arr;<\/p>\n<\/div><\/div><h3 id=\"simple-linked-list\">12. How do you implement a simple linked list in C++ using pointers? Write the code to insert a node at the beginning.<\/h3><p><strong>Answer:<\/strong><\/p><p>Define a <strong>Node<\/strong> structure and use pointers to link the nodes together.<\/p><div class=\"su-note\" style=\"border-color:#e5dbc7;border-radius:3px;-moz-border-radius:3px;-webkit-border-radius:3px;\"><div class=\"su-note-inner su-u-clearfix su-u-trim\" style=\"background-color:#FFF5E1;border-color:#ffffff;color:#333333;border-radius:3px;-moz-border-radius:3px;-webkit-border-radius:3px;\">\n<p>struct Node {<br>\nint data;<br>\nNode* next;<br>\n};<\/p>\n<p>void insertAtBeginning(Node*&amp; head, int newData) {<br>\nNode* newNode = new Node();<br>\nnewNode-&gt;data = newData;<br>\nnewNode-&gt;next = head;<br>\nhead = newNode;<br>\n}<\/p>\n<\/div><\/div><h3 id=\"pointer-arithmetic-iteration\">13. Write a C++ program to demonstrate the concept of pointer arithmetic by iterating over an array.<\/h3><p><strong>Answer:<\/strong><\/p><p>Use pointer increment to traverse the array.<\/p><div class=\"su-note\" style=\"border-color:#e5dbc7;border-radius:3px;-moz-border-radius:3px;-webkit-border-radius:3px;\"><div class=\"su-note-inner su-u-clearfix su-u-trim\" style=\"background-color:#FFF5E1;border-color:#ffffff;color:#333333;border-radius:3px;-moz-border-radius:3px;-webkit-border-radius:3px;\">\n<p>int arr[] = {1, 2, 3, 4, 5};<br>\nint* ptr = arr;<br>\nfor (int i = 0; i &lt; 5; ++i) {<br>\nstd::cout &lt;&lt; *(ptr + i) &lt;&lt; &rdquo; &ldquo;;<br>\n}<\/p>\n<\/div><\/div><h3 id=\"basic-smart-pointer\">14. How do you implement a smart pointer in C++? Write a basic unique_ptr implementation.<\/h3><p><strong>Answer:<\/strong><\/p><p>Use the <strong>std::unique_ptr<\/strong> from the C++ Standard Library to manage dynamic memory automatically.<\/p><div class=\"su-note\" style=\"border-color:#e5dbc7;border-radius:3px;-moz-border-radius:3px;-webkit-border-radius:3px;\"><div class=\"su-note-inner su-u-clearfix su-u-trim\" style=\"background-color:#FFF5E1;border-color:#ffffff;color:#333333;border-radius:3px;-moz-border-radius:3px;-webkit-border-radius:3px;\">\n<p>#include &lt;memory&gt;<br>\nstd::unique_ptr&lt;int&gt; ptr(new int(5));<br>\n\/\/ No need to manually delete the memory<\/p>\n<\/div><\/div><h3 id=\"avoid-memory-leaks\">15. What is a memory leak, and how can it be avoided in C++? Demonstrate a situation that could lead to a memory leak and how to prevent it.<\/h3><p><strong>Answer:<\/strong><\/p><p>A memory leak occurs when allocated memory is not properly deallocated. It can be avoided by ensuring that all allocated memory is deleted.<\/p><div class=\"su-note\" style=\"border-color:#e5dbc7;border-radius:3px;-moz-border-radius:3px;-webkit-border-radius:3px;\"><div class=\"su-note-inner su-u-clearfix su-u-trim\" style=\"background-color:#FFF5E1;border-color:#ffffff;color:#333333;border-radius:3px;-moz-border-radius:3px;-webkit-border-radius:3px;\">\n<p>int* ptr = new int(10);<br>\n\/\/ Forgot to delete the memory<br>\n\/\/ delete ptr; \/\/ Prevent memory leak<\/p>\n<\/div><\/div><h3 id=\"basic-stack-operations\">16. How do you implement a stack using STL in C++? Provide an example of basic stack operations like push and pop.<\/h3><p><strong>Answer:<\/strong><\/p><p>Use the <strong>std::stack<\/strong> container adapter to implement a stack.<\/p><div class=\"su-note\" style=\"border-color:#e5dbc7;border-radius:3px;-moz-border-radius:3px;-webkit-border-radius:3px;\"><div class=\"su-note-inner su-u-clearfix su-u-trim\" style=\"background-color:#FFF5E1;border-color:#ffffff;color:#333333;border-radius:3px;-moz-border-radius:3px;-webkit-border-radius:3px;\">\n<p>#include &lt;stack&gt;<br>\nstd::stack&lt;int&gt; s;<br>\ns.push(10);<br>\ns.push(20);<br>\nint top = s.top(); \/\/ 20<br>\ns.pop(); \/\/ Removes 20<\/p>\n<\/div><\/div><h3 id=\"maximum-element-in-vector\">17. Write a C++ program to find the maximum element in a vector using STL.<\/h3><p><strong>Answer:<\/strong><\/p><p>Use the <strong>std::max_element<\/strong> algorithm to find the maximum element.<\/p><div class=\"su-note\" style=\"border-color:#e5dbc7;border-radius:3px;-moz-border-radius:3px;-webkit-border-radius:3px;\"><div class=\"su-note-inner su-u-clearfix su-u-trim\" style=\"background-color:#FFF5E1;border-color:#ffffff;color:#333333;border-radius:3px;-moz-border-radius:3px;-webkit-border-radius:3px;\">\n<p>#include &lt;vector&gt;<br>\n#include &lt;algorithm&gt;<br>\nstd::vector&lt;int&gt; v = {10, 20, 30, 40};<br>\nint maxElem = *std::max_element(v.begin(), v.end());<\/p>\n<\/div><\/div><h3 id=\"sort-strings-descending\">18. How do you sort a list of strings in descending order using STL in C++?<\/h3><p><strong>Answer:<\/strong><\/p><p>Use <strong>std::sort<\/strong> with a custom comparator.<\/p><div class=\"su-note\" style=\"border-color:#e5dbc7;border-radius:3px;-moz-border-radius:3px;-webkit-border-radius:3px;\"><div class=\"su-note-inner su-u-clearfix su-u-trim\" style=\"background-color:#FFF5E1;border-color:#ffffff;color:#333333;border-radius:3px;-moz-border-radius:3px;-webkit-border-radius:3px;\">\n<p>#include &lt;vector&gt;<br>\n#include &lt;algorithm&gt;<br>\nstd::vector&lt;std::string&gt; vec = {&ldquo;apple&rdquo;, &ldquo;banana&rdquo;, &ldquo;cherry&rdquo;};<br>\nstd::sort(vec.begin(), vec.end(), std::greater&lt;std::string&gt;());<\/p>\n<\/div><\/div><h3 id=\"count-element-occurrences\">19. Write a C++ program to count the occurrences of a specific element in a list using STL.<\/h3><p><strong>Answer:<\/strong><\/p><p>Use the <strong>std::count<\/strong> algorithm to count occurrences.<\/p><div class=\"su-note\" style=\"border-color:#e5dbc7;border-radius:3px;-moz-border-radius:3px;-webkit-border-radius:3px;\"><div class=\"su-note-inner su-u-clearfix su-u-trim\" style=\"background-color:#FFF5E1;border-color:#ffffff;color:#333333;border-radius:3px;-moz-border-radius:3px;-webkit-border-radius:3px;\">\n<p>#include &lt;list&gt;<br>\n#include &lt;algorithm&gt;<br>\nstd::list&lt;int&gt; lst = {1, 2, 3, 2, 4, 2};<br>\nint count = std::count(lst.begin(), lst.end(), 2); \/\/ 3 occurrences of 2<\/p>\n<\/div><\/div><h3 id=\"merge-two-sets\">20. How would you merge two sets in C++ using STL? Provide a code example that merges two std::set containers.<\/h3><p><strong>Answer:<\/strong><\/p><p>Use <strong>std::set_union<\/strong> to merge two sets.<\/p><div class=\"su-note\" style=\"border-color:#e5dbc7;border-radius:3px;-moz-border-radius:3px;-webkit-border-radius:3px;\"><div class=\"su-note-inner su-u-clearfix su-u-trim\" style=\"background-color:#FFF5E1;border-color:#ffffff;color:#333333;border-radius:3px;-moz-border-radius:3px;-webkit-border-radius:3px;\">\n<p>#include &lt;set&gt;<br>\n#include &lt;algorithm&gt;<br>\nstd::set&lt;int&gt; set1 = {1, 2, 3};<br>\nstd::set&lt;int&gt; set2 = {3, 4, 5};<br>\nstd::set&lt;int&gt; result;<br>\nstd::set_union(set1.begin(), set1.end(), set2.begin(), set2.end(),<br>\nstd::inserter(result, result.begin()));<\/p>\n<\/div><\/div><h3 id=\"binary-search-implementation\">21. Write a C++ program to implement binary search on a sorted array.<\/h3><p><strong>Answer:<\/strong><\/p><p>Use a loop to repeatedly divide the array and narrow down the search range.<\/p><div class=\"su-note\" style=\"border-color:#e5dbc7;border-radius:3px;-moz-border-radius:3px;-webkit-border-radius:3px;\"><div class=\"su-note-inner su-u-clearfix su-u-trim\" style=\"background-color:#FFF5E1;border-color:#ffffff;color:#333333;border-radius:3px;-moz-border-radius:3px;-webkit-border-radius:3px;\">\n<p>int binarySearch(int arr[], int size, int key) {<br>\nint left = 0, right = size &ndash; 1;<br>\nwhile (left &lt;= right) {<br>\nint mid = left + (right &ndash; left) \/ 2;<br>\nif (arr[mid] == key) return mid;<br>\nif (arr[mid] &lt; key) left = mid + 1;<br>\nelse right = mid &ndash; 1;<br>\n}<br>\nreturn -1;<br>\n}<\/p>\n<\/div><\/div><h3 id=\"basic-queue-operations\">22. How do you implement a basic queue using an array in C++? Provide the code for enqueue and dequeue operations.<\/h3><p><strong>Answer:<\/strong><\/p><p>Use an array to store elements and manage front and rear indices for queue operations.<\/p><div class=\"su-note\" style=\"border-color:#e5dbc7;border-radius:3px;-moz-border-radius:3px;-webkit-border-radius:3px;\"><div class=\"su-note-inner su-u-clearfix su-u-trim\" style=\"background-color:#FFF5E1;border-color:#ffffff;color:#333333;border-radius:3px;-moz-border-radius:3px;-webkit-border-radius:3px;\">\n<p>class Queue {<br>\nprivate:<br>\nint arr[100];<br>\nint front, rear;<br>\npublic:<br>\nQueue() : front(0), rear(0) {}<br>\nvoid enqueue(int data) { arr[rear++] = data; }<br>\nint dequeue() { return arr[front++]; }<br>\n};<\/p>\n<\/div><\/div><h3 id=\"quicksort-array-sorting\">23. Write a C++ program to sort an array using the quicksort algorithm.<\/h3><p><strong>Answer:<\/strong><\/p><p>Use a divide-and-conquer approach to partition the array and recursively sort the subarrays.<\/p><div class=\"su-note\" style=\"border-color:#e5dbc7;border-radius:3px;-moz-border-radius:3px;-webkit-border-radius:3px;\"><div class=\"su-note-inner su-u-clearfix su-u-trim\" style=\"background-color:#FFF5E1;border-color:#ffffff;color:#333333;border-radius:3px;-moz-border-radius:3px;-webkit-border-radius:3px;\">\n<p>void quickSort(int arr[], int low, int high) {<br>\nif (low &lt; high) {<br>\nint pi = partition(arr, low, high);<br>\nquickSort(arr, low, pi &ndash; 1);<br>\nquickSort(arr, pi + 1, high);<br>\n}<br>\n}<\/p>\n<p>int partition(int arr[], int low, int high) {<br>\nint pivot = arr[high];<br>\nint i = (low &ndash; 1);<br>\nfor (int j = low; j &lt;= high &ndash; 1; j++) {<br>\nif (arr[j] &lt; pivot) {<br>\ni++;<br>\nstd::swap(arr[i], arr[j]);<br>\n}<br>\n}<br>\nstd::swap(arr[i + 1], arr[high]);<br>\nreturn (i + 1);<br>\n}<\/p>\n<\/div><\/div><h3 id=\"binary-tree-insertion\">24. How would you implement a binary tree in C++? Write the code for inserting a node into a binary tree.<\/h3><p><strong>Answer:<\/strong><\/p><p>Define a <strong>Node<\/strong> structure and write a function to insert nodes based on value comparison.<\/p><div class=\"su-note\" style=\"border-color:#e5dbc7;border-radius:3px;-moz-border-radius:3px;-webkit-border-radius:3px;\"><div class=\"su-note-inner su-u-clearfix su-u-trim\" style=\"background-color:#FFF5E1;border-color:#ffffff;color:#333333;border-radius:3px;-moz-border-radius:3px;-webkit-border-radius:3px;\">\n<p>struct Node {<br>\nint data;<br>\nNode* left, *right;<br>\nNode(int val) : data(val), left(nullptr), right(nullptr) {}<br>\n};<\/p>\n<p>Node* insert(Node* root, int data) {<br>\nif (root == nullptr) return new Node(data);<br>\nif (data &lt; root-&gt;data) root-&gt;left = insert(root-&gt;left, data);<br>\nelse root-&gt;right = insert(root-&gt;right, data);<br>\nreturn root;<br>\n}<\/p>\n<\/div><\/div><h3 id=\"dijkstra's-shortest-path\">25. Write a C++ program to find the shortest path in a graph using Dijkstra&rsquo;s algorithm.<\/h3><p><strong>Answer:<\/strong><\/p><p>Use a priority queue to explore the graph and update the shortest paths to each node.<\/p><div class=\"su-note\" style=\"border-color:#e5dbc7;border-radius:3px;-moz-border-radius:3px;-webkit-border-radius:3px;\"><div class=\"su-note-inner su-u-clearfix su-u-trim\" style=\"background-color:#FFF5E1;border-color:#ffffff;color:#333333;border-radius:3px;-moz-border-radius:3px;-webkit-border-radius:3px;\">\n<p>#include &lt;vector&gt;<br>\n#include &lt;queue&gt;<br>\n#include &lt;climits&gt;<\/p>\n<p>void dijkstra(std::vector&lt;std::vector&lt;std::pair&lt;int, int&gt;&gt;&gt; &amp;graph, int src, int V) {<br>\nstd::vector&lt;int&gt; dist(V, INT_MAX);<br>\ndist[src] = 0;<br>\nstd::priority_queue&lt;std::pair&lt;int, int&gt;, std::vector&lt;std::pair&lt;int, int&gt;&gt;, std::greater&lt;&gt;&gt; pq;<br>\npq.push({0, src});<\/p>\n<p>while (!pq.empty()) {<br>\nint u = pq.top().second;<br>\npq.pop();<\/p>\n<p>for (auto &amp;neighbor : graph[u]) {<br>\nint v = neighbor.first, weight = neighbor.second;<br>\nif (dist[u] + weight &lt; dist[v]) {<br>\ndist[v] = dist[u] + weight;<br>\npq.push({dist[v], v});<br>\n}<br>\n}<br>\n}<br>\n}<\/p>\n<\/div><\/div><h3 id=\"read-and-write-files\">26. How do you read and write to a text file in C++? Provide an example that reads a file line by line and writes the content to another file.<\/h3><p><strong>Answer:<\/strong><\/p><p>Use <strong>ifstream<\/strong> for reading and <strong>ofstream<\/strong> for writing.<\/p><div class=\"su-note\" style=\"border-color:#e5dbc7;border-radius:3px;-moz-border-radius:3px;-webkit-border-radius:3px;\"><div class=\"su-note-inner su-u-clearfix su-u-trim\" style=\"background-color:#FFF5E1;border-color:#ffffff;color:#333333;border-radius:3px;-moz-border-radius:3px;-webkit-border-radius:3px;\">\n<p>#include &lt;fstream&gt;<br>\n#include &lt;string&gt;<\/p>\n<p>void copyFile(const std::string &amp;inputFile, const std::string &amp;outputFile) {<br>\nstd::ifstream inFile(inputFile);<br>\nstd::ofstream outFile(outputFile);<br>\nstd::string line;<\/p>\n<p>while (std::getline(inFile, line)) {<br>\noutFile &lt;&lt; line &lt;&lt; &ldquo;\\n&rdquo;;<br>\n}<br>\n}<\/p>\n<\/div><\/div><h3 id=\"count-words-in-file\">27. Write a C++ program to count the number of words in a text file.<\/h3><p><strong>Answer:<\/strong><\/p><p>Use file streams to read the file word by word and count the occurrences.<\/p><div class=\"su-note\" style=\"border-color:#e5dbc7;border-radius:3px;-moz-border-radius:3px;-webkit-border-radius:3px;\"><div class=\"su-note-inner su-u-clearfix su-u-trim\" style=\"background-color:#FFF5E1;border-color:#ffffff;color:#333333;border-radius:3px;-moz-border-radius:3px;-webkit-border-radius:3px;\">\n<p>#include &lt;fstream&gt;<br>\n#include &lt;string&gt;<\/p>\n<p>int countWords(const std::string &amp;filename) {<br>\nstd::ifstream inFile(filename);<br>\nstd::string word;<br>\nint count = 0;<\/p>\n<p>while (inFile &gt;&gt; word) {<br>\ncount++;<br>\n}<br>\nreturn count;<br>\n}<\/p>\n<\/div><\/div><h3 id=\"handle-binary-files\">28. How do you handle binary files in C++? Write a program to read and write binary data.<\/h3><p><strong>Answer:<\/strong><\/p><p>Use <strong>ifstream<\/strong> and <strong>ofstream<\/strong> with the <strong>ios::binary<\/strong> flag to handle binary files.<\/p><div class=\"su-note\" style=\"border-color:#e5dbc7;border-radius:3px;-moz-border-radius:3px;-webkit-border-radius:3px;\"><div class=\"su-note-inner su-u-clearfix su-u-trim\" style=\"background-color:#FFF5E1;border-color:#ffffff;color:#333333;border-radius:3px;-moz-border-radius:3px;-webkit-border-radius:3px;\">\n<p>#include &lt;fstream&gt;<\/p>\n<p>struct Data {<br>\nint id;<br>\nchar name[20];<br>\n};<\/p>\n<p>void writeBinary(const std::string &amp;filename) {<br>\nstd::ofstream outFile(filename, std::ios::binary);<br>\nData d = {1, &ldquo;Example&rdquo;};<br>\noutFile.write(reinterpret_cast&lt;char*&gt;(&amp;d), sizeof(Data));<br>\n}<\/p>\n<p>void readBinary(const std::string &amp;filename) {<br>\nstd::ifstream inFile(filename, std::ios::binary);<br>\nData d;<br>\ninFile.read(reinterpret_cast&lt;char*&gt;(&amp;d), sizeof(Data));<br>\n}<\/p>\n<\/div><\/div><h3 id=\"append-text-to-file\">29. Write a C++ program to append text to an existing file without overwriting its content.<\/h3><p><strong>Answer:<\/strong><\/p><p>Use <strong>ofstream<\/strong> with the <strong>ios::app<\/strong> flag to append data to a file.<\/p><div class=\"su-note\" style=\"border-color:#e5dbc7;border-radius:3px;-moz-border-radius:3px;-webkit-border-radius:3px;\"><div class=\"su-note-inner su-u-clearfix su-u-trim\" style=\"background-color:#FFF5E1;border-color:#ffffff;color:#333333;border-radius:3px;-moz-border-radius:3px;-webkit-border-radius:3px;\">\n<p>#include &lt;fstream&gt;<br>\n#include &lt;string&gt;<\/p>\n<p>void appendToFile(const std::string &amp;filename, const std::string &amp;text) {<br>\nstd::ofstream outFile(filename, std::ios::app);<br>\noutFile &lt;&lt; text &lt;&lt; &ldquo;\\n&rdquo;;<br>\n}<\/p>\n<\/div><\/div><h3 id=\"serialize-class-object\">30. How do you serialize and deserialize an object in C++ using file handling? Provide an example of saving and loading a class object to\/from a file.<\/h3><p><strong>Answer:<\/strong><\/p><p>Use file streams to serialize (write) and deserialize (read) an object&rsquo;s data.<\/p><div class=\"su-note\" style=\"border-color:#e5dbc7;border-radius:3px;-moz-border-radius:3px;-webkit-border-radius:3px;\"><div class=\"su-note-inner su-u-clearfix su-u-trim\" style=\"background-color:#FFF5E1;border-color:#ffffff;color:#333333;border-radius:3px;-moz-border-radius:3px;-webkit-border-radius:3px;\">\n<p>#include &lt;fstream&gt;<\/p>\n<p>class MyClass {<br>\npublic:<br>\nint id;<br>\nchar name[20];<\/p>\n<p>void serialize(const std::string &amp;filename) {<br>\nstd::ofstream outFile(filename, std::ios::binary);<br>\noutFile.write(reinterpret_cast&lt;char*&gt;(this), sizeof(MyClass));<br>\n}<\/p>\n<p>void deserialize(const std::string &amp;filename) {<br>\nstd::ifstream inFile(filename, std::ios::binary);<br>\ninFile.read(reinterpret_cast&lt;char*&gt;(this), sizeof(MyClass));<br>\n}<br>\n};<\/p>\n<\/div><\/div><h3 id=\"create-and-manage-threads\">31. How do you create and manage threads in C++ using the Standard Library? Write a program to run two threads concurrently.<\/h3><p><strong>Answer:<\/strong><\/p><p>Use <strong>std::thread<\/strong> to create and manage threads.<\/p><div class=\"su-note\" style=\"border-color:#e5dbc7;border-radius:3px;-moz-border-radius:3px;-webkit-border-radius:3px;\"><div class=\"su-note-inner su-u-clearfix su-u-trim\" style=\"background-color:#FFF5E1;border-color:#ffffff;color:#333333;border-radius:3px;-moz-border-radius:3px;-webkit-border-radius:3px;\">\n<p>#include &lt;thread&gt;<br>\n#include &lt;iostream&gt;<\/p>\n<p>void printNumbers() {<br>\nfor (int i = 1; i &lt;= 5; i++) {<br>\nstd::cout &lt;&lt; i &lt;&lt; &rdquo; &ldquo;;<br>\n}<br>\n}<\/p>\n<p>void printLetters() {<br>\nfor (char c = &lsquo;A&rsquo;; c &lt;= &lsquo;E&rsquo;; c++) {<br>\nstd::cout &lt;&lt; c &lt;&lt; &rdquo; &ldquo;;<br>\n}<br>\n}<\/p>\n<p>int main() {<br>\nstd::thread t1(printNumbers);<br>\nstd::thread t2(printLetters);<br>\nt1.join();<br>\nt2.join();<br>\nreturn 0;<br>\n}<\/p>\n<\/div><\/div><h3 id=\"thread-safe-shared-variable\">32. Write a C++ program that uses a mutex to ensure thread-safe access to a shared variable.<\/h3><p><strong>Answer:<\/strong><\/p><p>Use <strong>std::mutex<\/strong> to protect access to the shared resource.<\/p><div class=\"su-note\" style=\"border-color:#e5dbc7;border-radius:3px;-moz-border-radius:3px;-webkit-border-radius:3px;\"><div class=\"su-note-inner su-u-clearfix su-u-trim\" style=\"background-color:#FFF5E1;border-color:#ffffff;color:#333333;border-radius:3px;-moz-border-radius:3px;-webkit-border-radius:3px;\">\n<p>#include &lt;thread&gt;<br>\n#include &lt;mutex&gt;<br>\n#include &lt;iostream&gt;<\/p>\n<p>int counter = 0;<br>\nstd::mutex mtx;<\/p>\n<p>void incrementCounter() {<br>\nstd::lock_guard&lt;std::mutex&gt; lock(mtx);<br>\n++counter;<br>\n}<\/p>\n<p>int main() {<br>\nstd::thread t1(incrementCounter);<br>\nstd::thread t2(incrementCounter);<br>\nt1.join();<br>\nt2.join();<br>\nstd::cout &lt;&lt; &ldquo;Counter: &rdquo; &lt;&lt; counter &lt;&lt; std::endl;<br>\nreturn 0;<br>\n}<\/p>\n<\/div><\/div><h3 id=\"producer-consumer-problem\">33. How do you implement a producer-consumer problem in C++ using threads? Provide a simple implementation using condition variables.<\/h3><p><strong>Answer:<\/strong><\/p><p>Use <strong>std::condition_variable<\/strong> to synchronize the producer and consumer threads.<\/p><div class=\"su-note\" style=\"border-color:#e5dbc7;border-radius:3px;-moz-border-radius:3px;-webkit-border-radius:3px;\"><div class=\"su-note-inner su-u-clearfix su-u-trim\" style=\"background-color:#FFF5E1;border-color:#ffffff;color:#333333;border-radius:3px;-moz-border-radius:3px;-webkit-border-radius:3px;\">\n<p>#include &lt;queue&gt;<br>\n#include &lt;thread&gt;<br>\n#include &lt;mutex&gt;<br>\n#include &lt;condition_variable&gt;<br>\n#include &lt;iostream&gt;<\/p>\n<p>std::queue&lt;int&gt; q;<br>\nstd::mutex mtx;<br>\nstd::condition_variable cv;<\/p>\n<p>void producer() {<br>\nfor (int i = 1; i &lt;= 5; i++) {<br>\nstd::unique_lock&lt;std::mutex&gt; lock(mtx);<br>\nq.push(i);<br>\ncv.notify_one();<br>\n}<br>\n}<\/p>\n<p>void consumer() {<br>\nfor (int i = 1; i &lt;= 5; i++) {<br>\nstd::unique_lock&lt;std::mutex&gt; lock(mtx);<br>\ncv.wait(lock, [] { return !q.empty(); });<br>\nint val = q.front();<br>\nq.pop();<br>\nstd::cout &lt;&lt; &ldquo;Consumed: &rdquo; &lt;&lt; val &lt;&lt; std::endl;<br>\n}<br>\n}<\/p>\n<p>int main() {<br>\nstd::thread t1(producer);<br>\nstd::thread t2(consumer);<br>\nt1.join();<br>\nt2.join();<br>\nreturn 0;<br>\n}<\/p>\n<\/div><\/div><h3 id=\"simple-thread-pool\">34. Write a C++ program that demonstrates the use of a thread pool for parallel processing.<\/h3><p><strong>Answer:<\/strong><\/p><p>Create a pool of worker threads that can execute tasks from a task queue.<\/p><div class=\"su-note\" style=\"border-color:#e5dbc7;border-radius:3px;-moz-border-radius:3px;-webkit-border-radius:3px;\"><div class=\"su-note-inner su-u-clearfix su-u-trim\" style=\"background-color:#FFF5E1;border-color:#ffffff;color:#333333;border-radius:3px;-moz-border-radius:3px;-webkit-border-radius:3px;\">\n<p>#include &lt;iostream&gt;<br>\n#include &lt;vector&gt;<br>\n#include &lt;thread&gt;<br>\n#include &lt;queue&gt;<br>\n#include &lt;functional&gt;<br>\n#include &lt;condition_variable&gt;<\/p>\n<p>class ThreadPool {<br>\npublic:<br>\nThreadPool(size_t numThreads);<br>\n~ThreadPool();<br>\nvoid enqueueTask(std::function&lt;void()&gt; task);<\/p>\n<p>private:<br>\nstd::vector&lt;std::thread&gt; workers;<br>\nstd::queue&lt;std::function&lt;void()&gt;&gt; tasks;<br>\nstd::mutex mtx;<br>\nstd::condition_variable cv;<br>\nbool stop;<\/p>\n<p>void workerThread();<br>\n};<\/p>\n<p>ThreadPool::ThreadPool(size_t numThreads) : stop(false) {<br>\nfor (size_t i = 0; i &lt; numThreads; ++i) {<br>\nworkers.emplace_back([this] { workerThread(); });<br>\n}<br>\n}<\/p>\n<p>ThreadPool::~ThreadPool() {<br>\n{<br>\nstd::unique_lock&lt;std::mutex&gt; lock(mtx);<br>\nstop = true;<br>\n}<br>\ncv.notify_all();<br>\nfor (std::thread &amp;worker : workers) {<br>\nworker.join();<br>\n}<br>\n}<\/p>\n<p>void ThreadPool::enqueueTask(std::function&lt;void()&gt; task) {<br>\n{<br>\nstd::unique_lock&lt;std::mutex&gt; lock(mtx);<br>\ntasks.push(task);<br>\n}<br>\ncv.notify_one();<br>\n}<\/p>\n<p>void ThreadPool::workerThread() {<br>\nwhile (true) {<br>\nstd::function&lt;void()&gt; task;<br>\n{<br>\nstd::unique_lock&lt;std::mutex&gt; lock(mtx);<br>\ncv.wait(lock, [this] { return stop || !tasks.empty(); });<br>\nif (stop &amp;&amp; tasks.empty()) return;<br>\ntask = std::move(tasks.front());<br>\ntasks.pop();<br>\n}<br>\ntask();<br>\n}<br>\n}<\/p>\n<p>int main() {<br>\nThreadPool pool(4);<br>\npool.enqueueTask([] { std::cout &lt;&lt; &ldquo;Task 1\\n&rdquo;; });<br>\npool.enqueueTask([] { std::cout &lt;&lt; &ldquo;Task 2\\n&rdquo;; });<br>\npool.enqueueTask([] { std::cout &lt;&lt; &ldquo;Task 3\\n&rdquo;; });<br>\npool.enqueueTask([] { std::cout &lt;&lt; &ldquo;Task 4\\n&rdquo;; });<br>\nreturn 0;<br>\n}<\/p>\n<\/div><\/div><h3 id=\"futures-and-promises\">35. How do you use futures and promises in C++ to manage asynchronous operations? Write a program that demonstrates their use.<\/h3><p><strong>Answer:<\/strong><\/p><p>Use <strong>std::future<\/strong> and <strong>std::promise<\/strong> to handle asynchronous operations and retrieve their results.<\/p><div class=\"su-note\" style=\"border-color:#e5dbc7;border-radius:3px;-moz-border-radius:3px;-webkit-border-radius:3px;\"><div class=\"su-note-inner su-u-clearfix su-u-trim\" style=\"background-color:#FFF5E1;border-color:#ffffff;color:#333333;border-radius:3px;-moz-border-radius:3px;-webkit-border-radius:3px;\">\n<p>#include &lt;iostream&gt;<br>\n#include &lt;future&gt;<\/p>\n<p>int asyncTask(std::promise&lt;int&gt; &amp;promiseObj) {<br>\nint result = 10 * 2;<br>\npromiseObj.set_value(result);<br>\nreturn result;<br>\n}<\/p>\n<p>int main() {<br>\nstd::promise&lt;int&gt; promiseObj;<br>\nstd::future&lt;int&gt; futureObj = promiseObj.get_future();<br>\nstd::thread t(asyncTask, std::ref(promiseObj));<br>\nstd::cout &lt;&lt; &ldquo;Result: &rdquo; &lt;&lt; futureObj.get() &lt;&lt; std::endl;<br>\nt.join();<br>\nreturn 0;<br>\n}<\/p>\n<\/div><\/div><h3 id=\"template-function-swap\">36. How do you implement a template function in C++? Write a template function that swaps two values of any data type.<\/h3><p><strong>Answer:<\/strong><\/p><p>Define a function template using the <strong>template<\/strong> keyword.<\/p><div class=\"su-note\" style=\"border-color:#e5dbc7;border-radius:3px;-moz-border-radius:3px;-webkit-border-radius:3px;\"><div class=\"su-note-inner su-u-clearfix su-u-trim\" style=\"background-color:#FFF5E1;border-color:#ffffff;color:#333333;border-radius:3px;-moz-border-radius:3px;-webkit-border-radius:3px;\">\n<p>template &lt;typename T&gt;<br>\nvoid swapValues(T &amp;a, T &amp;b) {<br>\nT temp = a;<br>\na = b;<br>\nb = temp;<br>\n}<\/p>\n<\/div><\/div><h3 id=\"template-class-stack\">37. Write a C++ program that demonstrates the use of template classes by creating a generic stack class.<\/h3><p><strong>Answer:<\/strong><\/p><p>Use a class template to define a stack that works with any data type.<\/p><div class=\"su-note\" style=\"border-color:#e5dbc7;border-radius:3px;-moz-border-radius:3px;-webkit-border-radius:3px;\"><div class=\"su-note-inner su-u-clearfix su-u-trim\" style=\"background-color:#FFF5E1;border-color:#ffffff;color:#333333;border-radius:3px;-moz-border-radius:3px;-webkit-border-radius:3px;\">\n<p>template &lt;typename T&gt;<br>\nclass Stack {<br>\nprivate:<br>\nstd::vector&lt;T&gt; elements;<\/p>\n<p>public:<br>\nvoid push(const T &amp;element) { elements.push_back(element); }<br>\nvoid pop() { elements.pop_back(); }<br>\nT top() const { return elements.back(); }<br>\nbool isEmpty() const { return elements.empty(); }<br>\n};<\/p>\n<\/div><\/div><h3 id=\"implement-multiple-inheritance\">38. How do you implement multiple inheritance in C++? Write a program that demonstrates multiple inheritance with two base classes and one derived class.<\/h3><p><strong>Answer:<\/strong><\/p><p>Define a derived class that inherits from multiple base classes.<\/p><div class=\"su-note\" style=\"border-color:#e5dbc7;border-radius:3px;-moz-border-radius:3px;-webkit-border-radius:3px;\"><div class=\"su-note-inner su-u-clearfix su-u-trim\" style=\"background-color:#FFF5E1;border-color:#ffffff;color:#333333;border-radius:3px;-moz-border-radius:3px;-webkit-border-radius:3px;\">\n<p>class Base1 {<br>\npublic:<br>\nvoid show() { std::cout &lt;&lt; &ldquo;Base1\\n&rdquo;; }<br>\n};<\/p>\n<p>class Base2 {<br>\npublic:<br>\nvoid display() { std::cout &lt;&lt; &ldquo;Base2\\n&rdquo;; }<br>\n};<\/p>\n<p>class Derived : public Base1, public Base2 {<br>\n};<\/p>\n<p>int main() {<br>\nDerived d;<br>\nd.show();<br>\nd.display();<br>\nreturn 0;<br>\n}<\/p>\n<\/div><\/div><h3 id=\"std::function-callback\">39. Write a C++ program that demonstrates the use of the std::function to store and invoke a callback function.<\/h3><p><strong>Answer:<\/strong><\/p><p>Use <strong>std::function<\/strong> to store a callable entity and invoke it later.<\/p><div class=\"su-note\" style=\"border-color:#e5dbc7;border-radius:3px;-moz-border-radius:3px;-webkit-border-radius:3px;\"><div class=\"su-note-inner su-u-clearfix su-u-trim\" style=\"background-color:#FFF5E1;border-color:#ffffff;color:#333333;border-radius:3px;-moz-border-radius:3px;-webkit-border-radius:3px;\">\n<p>#include &lt;iostream&gt;<br>\n#include &lt;functional&gt;<\/p>\n<p>void myCallback(int x) {<br>\nstd::cout &lt;&lt; &ldquo;Callback called with value: &rdquo; &lt;&lt; x &lt;&lt; std::endl;<br>\n}<\/p>\n<p>int main() {<br>\nstd::function&lt;void(int)&gt; callback = myCallback;<br>\ncallback(10);<br>\nreturn 0;<br>\n}<\/p>\n<\/div><\/div><h3 id=\"use-lambda-expressions\">40. How do you use lambda expressions in C++? Write a program that captures variables by value and by reference in a lambda.<\/h3><p><strong>Answer:<\/strong><\/p><p>Use lambda expressions to define inline functions that can capture variables.<\/p><div class=\"su-note\" style=\"border-color:#e5dbc7;border-radius:3px;-moz-border-radius:3px;-webkit-border-radius:3px;\"><div class=\"su-note-inner su-u-clearfix su-u-trim\" style=\"background-color:#FFF5E1;border-color:#ffffff;color:#333333;border-radius:3px;-moz-border-radius:3px;-webkit-border-radius:3px;\">\n<p>#include &lt;iostream&gt;<\/p>\n<p>int main() {<br>\nint a = 10, b = 20;<br>\nauto add = [a, &amp;b]() {<br>\nb = b + a;<br>\nreturn b;<br>\n};<br>\nstd::cout &lt;&lt; &ldquo;Sum: &rdquo; &lt;&lt; add() &lt;&lt; std::endl;<br>\nreturn 0;<br>\n}<\/p>\n<\/div><\/div><h3 id=\"custom-exception-handling\">41. Write a C++ program that demonstrates exception handling by throwing and catching a custom exception.<\/h3><p><strong>Answer:<\/strong><\/p><p>Define a custom exception class and use <strong>try<\/strong>, <strong>catch<\/strong>, and <strong>throw<\/strong> to handle exceptions.<\/p><div class=\"su-note\" style=\"border-color:#e5dbc7;border-radius:3px;-moz-border-radius:3px;-webkit-border-radius:3px;\"><div class=\"su-note-inner su-u-clearfix su-u-trim\" style=\"background-color:#FFF5E1;border-color:#ffffff;color:#333333;border-radius:3px;-moz-border-radius:3px;-webkit-border-radius:3px;\">\n<p>class MyException : public std::exception {<br>\npublic:<br>\nconst char *what() const noexcept override {<br>\nreturn &ldquo;My custom exception&rdquo;;<br>\n}<br>\n};<\/p>\n<p>int main() {<br>\ntry {<br>\nthrow MyException();<br>\n} catch (const MyException &amp;e) {<br>\nstd::cout &lt;&lt; e.what() &lt;&lt; std::endl;<br>\n}<br>\nreturn 0;<br>\n}<\/p>\n<\/div><\/div><h3 id=\"handle-multiple-exceptions\">42. How do you handle multiple exceptions in C++? Provide an example where you catch different types of exceptions.<\/h3><p><strong>Answer:<\/strong><\/p><p>Use multiple <strong>catch<\/strong> blocks to handle different types of exceptions.<\/p><div class=\"su-note\" style=\"border-color:#e5dbc7;border-radius:3px;-moz-border-radius:3px;-webkit-border-radius:3px;\"><div class=\"su-note-inner su-u-clearfix su-u-trim\" style=\"background-color:#FFF5E1;border-color:#ffffff;color:#333333;border-radius:3px;-moz-border-radius:3px;-webkit-border-radius:3px;\">\n<p>int main() {<br>\ntry {<br>\nthrow 10;<br>\n} catch (int e) {<br>\nstd::cout &lt;&lt; &ldquo;Caught integer exception: &rdquo; &lt;&lt; e &lt;&lt; std::endl;<br>\n} catch (double e) {<br>\nstd::cout &lt;&lt; &ldquo;Caught double exception: &rdquo; &lt;&lt; e &lt;&lt; std::endl;<br>\n}<br>\nreturn 0;<br>\n}<\/p>\n<\/div><\/div><h3 id=\"try-catch-finally-mechanism\">43. Write a C++ program that uses a try-catch-finally like mechanism to ensure that resources are released even if an exception is thrown.<\/h3><p><strong>Answer:<\/strong><\/p><p>Use RAII (Resource Acquisition Is Initialization) to manage resources safely.<\/p><div class=\"su-note\" style=\"border-color:#e5dbc7;border-radius:3px;-moz-border-radius:3px;-webkit-border-radius:3px;\"><div class=\"su-note-inner su-u-clearfix su-u-trim\" style=\"background-color:#FFF5E1;border-color:#ffffff;color:#333333;border-radius:3px;-moz-border-radius:3px;-webkit-border-radius:3px;\">\n<p>class ResourceGuard {<br>\npublic:<br>\nResourceGuard() { std::cout &lt;&lt; &ldquo;Acquiring resource\\n&rdquo;; }<br>\n~ResourceGuard() { std::cout &lt;&lt; &ldquo;Releasing resource\\n&rdquo;; }<br>\n};<\/p>\n<p>int main() {<br>\ntry {<br>\nResourceGuard rg;<br>\nthrow std::runtime_error(&ldquo;An error occurred&rdquo;);<br>\n} catch (const std::exception &amp;e) {<br>\nstd::cout &lt;&lt; e.what() &lt;&lt; std::endl;<br>\n}<br>\nreturn 0;<br>\n}<\/p>\n<\/div><\/div><h3 id=\"error-code-handling\">44. How do you implement a custom error code handling mechanism in C++? Write a program that uses a custom error code enum to represent different error states.<\/h3><p><strong>Answer:<\/strong><\/p><p>Define an enum for error codes and return these from functions to indicate success or failure.<\/p><div class=\"su-note\" style=\"border-color:#e5dbc7;border-radius:3px;-moz-border-radius:3px;-webkit-border-radius:3px;\"><div class=\"su-note-inner su-u-clearfix su-u-trim\" style=\"background-color:#FFF5E1;border-color:#ffffff;color:#333333;border-radius:3px;-moz-border-radius:3px;-webkit-border-radius:3px;\">\n<p>enum class ErrorCode {<br>\nSuccess,<br>\nNotFound,<br>\nPermissionDenied<br>\n};<\/p>\n<p>ErrorCode performOperation(int data) {<br>\nif (data &lt; 0) return ErrorCode::NotFound;<br>\nif (data == 0) return ErrorCode::PermissionDenied;<br>\nreturn ErrorCode::Success;<br>\n}<\/p>\n<\/div><\/div><h3 id=\"exception-across-threads\">45. Write a C++ program that demonstrates the use of std::exception_ptr to rethrow an exception in a different thread.<\/h3><p><strong>Answer:<\/strong><\/p><p>Use <strong>std::exception_ptr<\/strong> to capture and propagate exceptions across threads.<\/p><div class=\"su-note\" style=\"border-color:#e5dbc7;border-radius:3px;-moz-border-radius:3px;-webkit-border-radius:3px;\"><div class=\"su-note-inner su-u-clearfix su-u-trim\" style=\"background-color:#FFF5E1;border-color:#ffffff;color:#333333;border-radius:3px;-moz-border-radius:3px;-webkit-border-radius:3px;\">\n<p>#include &lt;iostream&gt;<br>\n#include &lt;thread&gt;<br>\n#include &lt;exception&gt;<\/p>\n<p>std::exception_ptr eptr;<\/p>\n<p>void threadFunc() {<br>\ntry {<br>\nthrow std::runtime_error(&ldquo;Error in thread&rdquo;);<br>\n} catch (&hellip;) {<br>\neptr = std::current_exception();<br>\n}<br>\n}<\/p>\n<p>int main() {<br>\nstd::thread t(threadFunc);<br>\nt.join();<br>\nif (eptr) {<br>\ntry {<br>\nstd::rethrow_exception(eptr);<br>\n} catch (const std::exception &amp;e) {<br>\nstd::cout &lt;&lt; e.what() &lt;&lt; std::endl;<br>\n}<br>\n}<br>\nreturn 0;<br>\n}<\/p>\n<\/div><\/div><h3 id=\"singleton-pattern-implementation\">46. How do you implement the Singleton pattern in C++? Provide a thread-safe implementation using std::mutex.<\/h3><p><strong>Answer:<\/strong><\/p><p>Use a <strong>static<\/strong> function to return the single instance of the class and protect it with a <strong>std::mutex<\/strong>.<\/p><div class=\"su-note\" style=\"border-color:#e5dbc7;border-radius:3px;-moz-border-radius:3px;-webkit-border-radius:3px;\"><div class=\"su-note-inner su-u-clearfix su-u-trim\" style=\"background-color:#FFF5E1;border-color:#ffffff;color:#333333;border-radius:3px;-moz-border-radius:3px;-webkit-border-radius:3px;\">\n<p>class Singleton {<br>\nprivate:<br>\nstatic Singleton *instance;<br>\nstatic std::mutex mtx;<br>\nSingleton() {}<\/p>\n<p>public:<br>\nSingleton(const Singleton &amp;) = delete;<br>\nSingleton &amp;operator=(const Singleton &amp;) = delete;<\/p>\n<p>static Singleton *getInstance() {<br>\nstd::lock_guard&lt;std::mutex&gt; lock(mtx);<br>\nif (!instance) {<br>\ninstance = new Singleton();<br>\n}<br>\nreturn instance;<br>\n}<br>\n};<\/p>\n<p>Singleton *Singleton::instance = nullptr;<br>\nstd::mutex Singleton::mtx;<\/p>\n<\/div><\/div><h3 id=\"factory-design-pattern\">47. Write a C++ program that demonstrates the Factory design pattern by creating different types of objects based on input parameters.<\/h3><p><strong>Answer:<\/strong><\/p><p>Use a factory method to create and return different types of objects.<\/p><div class=\"su-note\" style=\"border-color:#e5dbc7;border-radius:3px;-moz-border-radius:3px;-webkit-border-radius:3px;\"><div class=\"su-note-inner su-u-clearfix su-u-trim\" style=\"background-color:#FFF5E1;border-color:#ffffff;color:#333333;border-radius:3px;-moz-border-radius:3px;-webkit-border-radius:3px;\">\n<p>class Shape {<br>\npublic:<br>\nvirtual void draw() = 0;<br>\n};<\/p>\n<p>class Circle : public Shape {<br>\npublic:<br>\nvoid draw() override { std::cout &lt;&lt; &ldquo;Drawing Circle\\n&rdquo;; }<br>\n};<\/p>\n<p>class Square : public Shape {<br>\npublic:<br>\nvoid draw() override { std::cout &lt;&lt; &ldquo;Drawing Square\\n&rdquo;; }<br>\n};<\/p>\n<p>class ShapeFactory {<br>\npublic:<br>\nstatic Shape *createShape(const std::string &amp;type) {<br>\nif (type == &ldquo;Circle&rdquo;) return new Circle();<br>\nif (type == &ldquo;Square&rdquo;) return new Square();<br>\nreturn nullptr;<br>\n}<br>\n};<\/p>\n<p>int main() {<br>\nShape *shape = ShapeFactory::createShape(&ldquo;Circle&rdquo;);<br>\nshape-&gt;draw();<br>\ndelete shape;<br>\nreturn 0;<br>\n}<\/p>\n<\/div><\/div><h3 id=\"observer-pattern-implementation\">48. How do you implement the Observer pattern in C++? Write a program where observers are notified of state changes in the subject.<\/h3><p><strong>Answer:<\/strong><\/p><p>Use a subject class to maintain a list of observers and notify them of state changes.<\/p><div class=\"su-note\" style=\"border-color:#e5dbc7;border-radius:3px;-moz-border-radius:3px;-webkit-border-radius:3px;\"><div class=\"su-note-inner su-u-clearfix su-u-trim\" style=\"background-color:#FFF5E1;border-color:#ffffff;color:#333333;border-radius:3px;-moz-border-radius:3px;-webkit-border-radius:3px;\">\n<p>#include &lt;iostream&gt;<br>\n#include &lt;vector&gt;<\/p>\n<p>class Observer {<br>\npublic:<br>\nvirtual void update(int state) = 0;<br>\n};<\/p>\n<p>class Subject {<br>\nprivate:<br>\nstd::vector&lt;Observer *&gt; observers;<br>\nint state;<\/p>\n<p>public:<br>\nvoid attach(Observer *observer) { observers.push_back(observer); }<br>\nvoid setState(int newState) {<br>\nstate = newState;<br>\nnotifyAll();<br>\n}<br>\nvoid notifyAll() {<br>\nfor (Observer *observer : observers) {<br>\nobserver-&gt;update(state);<br>\n}<br>\n}<br>\n};<\/p>\n<p>class ConcreteObserver : public Observer {<br>\npublic:<br>\nvoid update(int state) override { std::cout &lt;&lt; &ldquo;State changed to: &rdquo; &lt;&lt; state &lt;&lt; std::endl; }<br>\n};<\/p>\n<p>int main() {<br>\nSubject subject;<br>\nConcreteObserver observer1, observer2;<br>\nsubject.attach(&amp;observer1);<br>\nsubject.attach(&amp;observer2);<br>\nsubject.setState(10);<br>\nreturn 0;<br>\n}<\/p>\n<\/div><\/div><h3 id=\"strategy-pattern-sorting\">49. Write a C++ program that demonstrates the Strategy design pattern by implementing different sorting algorithms that can be selected at runtime.<\/h3><p><strong>Answer:<\/strong><\/p><p>Define a strategy interface and implement different strategies that can be selected dynamically.<\/p><div class=\"su-note\" style=\"border-color:#e5dbc7;border-radius:3px;-moz-border-radius:3px;-webkit-border-radius:3px;\"><div class=\"su-note-inner su-u-clearfix su-u-trim\" style=\"background-color:#FFF5E1;border-color:#ffffff;color:#333333;border-radius:3px;-moz-border-radius:3px;-webkit-border-radius:3px;\">\n<p>class SortStrategy {<br>\npublic:<br>\nvirtual void sort(std::vector&lt;int&gt; &amp;data) = 0;<br>\n};<\/p>\n<p>class BubbleSort : public SortStrategy {<br>\npublic:<br>\nvoid sort(std::vector&lt;int&gt; &amp;data) override {<br>\nfor (size_t i = 0; i &lt; data.size(); ++i) {<br>\nfor (size_t j = 0; j &lt; data.size() &ndash; i &ndash; 1; ++j) {<br>\nif (data[j] &gt; data[j + 1]) std::swap(data[j], data[j + 1]);<br>\n}<br>\n}<br>\n}<br>\n};<\/p>\n<p>class QuickSort : public SortStrategy {<br>\npublic:<br>\nvoid sort(std::vector&lt;int&gt; &amp;data) override {<br>\nstd::sort(data.begin(), data.end());<br>\n}<br>\n};<\/p>\n<p>class SortContext {<br>\nprivate:<br>\nSortStrategy *strategy;<\/p>\n<p>public:<br>\nvoid setStrategy(SortStrategy *s) { strategy = s; }<br>\nvoid executeStrategy(std::vector&lt;int&gt; &amp;data) { strategy-&gt;sort(data); }<br>\n};<\/p>\n<p>int main() {<br>\nstd::vector&lt;int&gt; data = {5, 2, 9, 1, 5, 6};<br>\nSortContext context;<br>\ncontext.setStrategy(new BubbleSort());<br>\ncontext.executeStrategy(data);<\/p>\n<p>for (int val : data) std::cout &lt;&lt; val &lt;&lt; &rdquo; &ldquo;;<br>\nreturn 0;<br>\n}<\/p>\n<\/div><\/div><h3 id=\"decorator-pattern-example\">50. How do you implement the Decorator pattern in C++? Write a program that extends the functionality of an object dynamically.<\/h3><p><strong>Answer:<\/strong><\/p><p>Use a base class and concrete decorators to add functionality to objects at runtime.<\/p><div class=\"su-note\" style=\"border-color:#e5dbc7;border-radius:3px;-moz-border-radius:3px;-webkit-border-radius:3px;\"><div class=\"su-note-inner su-u-clearfix su-u-trim\" style=\"background-color:#FFF5E1;border-color:#ffffff;color:#333333;border-radius:3px;-moz-border-radius:3px;-webkit-border-radius:3px;\">\n<p>class Coffee {<br>\npublic:<br>\nvirtual std::string getDescription() = 0;<br>\nvirtual double cost() = 0;<br>\n};<\/p>\n<p>class SimpleCoffee : public Coffee {<br>\npublic:<br>\nstd::string getDescription() override { return &ldquo;Simple Coffee&rdquo;; }<br>\ndouble cost() override { return 2.0; }<br>\n};<\/p>\n<p>class MilkDecorator : public Coffee {<br>\nprivate:<br>\nCoffee *coffee;<\/p>\n<p>public:<br>\nMilkDecorator(Coffee *c) : coffee(c) {}<br>\nstd::string getDescription() override { return coffee-&gt;getDescription() + &ldquo;, Milk&rdquo;; }<br>\ndouble cost() override { return coffee-&gt;cost() + 0.5; }<br>\n};<\/p>\n<p>class SugarDecorator : public Coffee {<br>\nprivate:<br>\nCoffee *coffee;<\/p>\n<p>public:<br>\nSugarDecorator(Coffee *c) : coffee(c) {}<br>\nstd::string getDescription() override { return coffee-&gt;getDescription() + &ldquo;, Sugar&rdquo;; }<br>\ndouble cost() override { return coffee-&gt;cost() + 0.2; }<br>\n};<\/p>\n<p>int main() {<br>\nCoffee *coffee = new SimpleCoffee();<br>\ncoffee = new MilkDecorator(coffee);<br>\ncoffee = new SugarDecorator(coffee);<br>\nstd::cout &lt;&lt; coffee-&gt;getDescription() &lt;&lt; &rdquo; costs $&rdquo; &lt;&lt; coffee-&gt;cost() &lt;&lt; std::endl;<br>\ndelete coffee;<br>\nreturn 0;<br>\n}<\/p>\n<\/div><\/div><h2>Final Words<\/h2><p>Getting ready for an interview can feel overwhelming, but going through these C++ fresher interview questions can help you feel more confident. This guide focuses on the kinds of C++ developer interview questions for fresher roles that you&rsquo;re likely to face.<\/p><p>Don&rsquo;t forget to practice the C++ basic coding interview questions too! With the right preparation, you&rsquo;ll ace your C++ interview and take that important step in your career.<\/p><hr><h2>Frequently Asked Questions<\/h2><h3>1. What are the most common interview questions for C++?<\/h3><p>Common interview questions for C++ often focus on object-oriented programming concepts, memory management, pointers, data structures, and algorithms.<\/p><h3>2. What are the important C++ topics freshers should focus on for interviews?<\/h3><p>Freshers should focus on understanding classes and objects, inheritance, polymorphism, pointers, references, STL, and basic algorithms.<\/p><h3>3. How should freshers prepare for C++ technical interviews?<\/h3><p>Freshers should practice coding problems, review key concepts, and understand the application of C++ in solving real-world problems.<\/p><h3>4. What strategies can freshers use to solve C++ coding questions during interviews?<\/h3><p>Freshers should break down problems, write clean code, test with different inputs, and focus on time and space complexity.<\/p><h3>5. Should freshers prepare for advanced C++ topics in interviews?<\/h3><p>Yes, depending on the job role, it&rsquo;s beneficial to know advanced topics like smart pointers, multithreading, templates, and memory management techniques.<\/p><hr><h2>Explore More C++ Resources<\/h2><ul class=\"explore-more\">\n<li><a href=\"https:\/\/www.placementpreparation.io\/blog\/best-websites-to-learn-cpp\/\">C++ Websites<\/a><\/li>\n<li><a href=\"https:\/\/www.placementpreparation.io\/blog\/best-youtube-channels-to-learn-c-plus-plus\/\">C++ YouTube Channels<\/a><\/li>\n<li><a href=\"https:\/\/www.placementpreparation.io\/blog\/cpp-project-ideas-for-beginners\/\">C++ Project Ideas<\/a><\/li>\n<li><a href=\"https:\/\/www.placementpreparation.io\/blog\/best-apps-to-learn-cpp\/\">C++ Apps<\/a><\/li>\n<li><a href=\"https:\/\/www.placementpreparation.io\/blog\/cpp-ides-and-code-editors\/\">C++ IDEs<\/a><\/li>\n<li><a href=\"https:\/\/www.placementpreparation.io\/mcq\/cpp-programming\/\">C++ MCQ<\/a><\/li>\n<li><a href=\"https:\/\/www.placementpreparation.io\/blog\/c-vs-cpp-programming\/\">C vs C++<\/a><\/li>\n<\/ul><h2>Explore More Interview Questions<\/h2><ul class=\"explore-more\">\n<li><a href=\"https:\/\/www.placementpreparation.io\/blog\/python-interview-questions-for-freshers\/\">Python<\/a><\/li>\n<li><a href=\"https:\/\/www.placementpreparation.io\/blog\/java-interview-questions-for-freshers\/\">Java<\/a><\/li>\n<li><a href=\"https:\/\/www.placementpreparation.io\/blog\/sql-interview-questions-for-freshers\/\">SQL<\/a><\/li>\n<li><a href=\"https:\/\/www.placementpreparation.io\/blog\/react-interview-questions-for-freshers\/\">React<\/a><\/li>\n<li><a href=\"https:\/\/www.placementpreparation.io\/blog\/javascript-interview-questions-for-freshers\/\">JavaScript<\/a><\/li>\n<li><a href=\"https:\/\/www.placementpreparation.io\/blog\/c-programming-interview-questions-for-freshers\/\">C Programming<\/a><\/li>\n<li><a href=\"https:\/\/www.placementpreparation.io\/blog\/html-interview-questions-for-freshers\/\">HTML<\/a><\/li>\n<li><a href=\"https:\/\/www.placementpreparation.io\/blog\/css-interview-questions-for-freshers\/\">CSS<\/a><\/li>\n<li><a href=\"https:\/\/www.placementpreparation.io\/blog\/angular-interview-questions-for-freshers\/\">Angular<\/a><\/li>\n<li><a href=\"https:\/\/www.placementpreparation.io\/blog\/spring-boot-interview-questions-for-freshers\/\">Spring Boot<\/a><\/li>\n<\/ul>\n","protected":false},"excerpt":{"rendered":"<p>Are you preparing for your first C++ interview and wondering what questions you might face? Understanding the key C++ interview questions for freshers can give you more clarity.This blog is here to help you get ready with practical questions that test your real-world problem-solving skills. We&rsquo;ve gathered some of the most common basic C++ interview [&hellip;]<\/p>\n","protected":false},"author":4,"featured_media":12457,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[45],"tags":[],"class_list":["post-12430","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-programming-interview-questions"],"_links":{"self":[{"href":"https:\/\/www.placementpreparation.io\/blog\/wp-json\/wp\/v2\/posts\/12430","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.placementpreparation.io\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.placementpreparation.io\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.placementpreparation.io\/blog\/wp-json\/wp\/v2\/users\/4"}],"replies":[{"embeddable":true,"href":"https:\/\/www.placementpreparation.io\/blog\/wp-json\/wp\/v2\/comments?post=12430"}],"version-history":[{"count":3,"href":"https:\/\/www.placementpreparation.io\/blog\/wp-json\/wp\/v2\/posts\/12430\/revisions"}],"predecessor-version":[{"id":12458,"href":"https:\/\/www.placementpreparation.io\/blog\/wp-json\/wp\/v2\/posts\/12430\/revisions\/12458"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.placementpreparation.io\/blog\/wp-json\/wp\/v2\/media\/12457"}],"wp:attachment":[{"href":"https:\/\/www.placementpreparation.io\/blog\/wp-json\/wp\/v2\/media?parent=12430"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.placementpreparation.io\/blog\/wp-json\/wp\/v2\/categories?post=12430"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.placementpreparation.io\/blog\/wp-json\/wp\/v2\/tags?post=12430"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}