Top 45+ C++ Interview Questions and Answers [2025]
C++ was introduced by Bjarne Stroustrup at Bell Labs is a language that has stood the test of time since the 80s, It has evolved into the fourth most popular programming language all over the world, consisting of approximately 7.5 percent of the index. Understanding C++ opens doors to opportunities and empowers developers to address complicated software development obstacles successfully. In this blog, we will discuss C++ interview questions for freshers, intermediate, and experienced with their coding examples.
C++ Basic Interview Questions For Freshers
Here is a list of C++ basic interview questions and answers for freshers which will help you understand the basics of C++, and enhance your skills to excel in your interview. To learn more about C++, you can opt for C and C++ courses and gather your expertise in this field.
1. What do you understand by C++?
C++ is a versatile, all-purpose, object-oriented programming language that offers supportive procedural, practical, and generic programming styles. It provides programmers with wide-ranging command over system tools and memory. It is also an object-oriented programming language, which offers applications a distinct format and permits code to be re-factored, minimizing expenses.
2. What are the different data types present in C++?
There are three different data types in C++:
- Primitive data types – Primitive data structure is the data structure that enables you to retain distinctly single data type values.
- Abstract data types – The abstract datatype is a unique type of datatype, whose performance is determined using a set of values and a collection of operations.
- Derived data types – The data types that are extracted from the primitive or built-in datatypes are known as derived data types.
3. How will you define class and object in C++?
A class functions as a blueprint for constructing objects in C++. It defines the data and methods that an object will exhibit. Alternatively, an object is a set of instances derived from a class. It acquires the data and methods determined by its connected class.
4. What do you understand by reference in C++?
A reference in C++ denotes the address of the unique variable and is built through the ampersand (&) operator. It is used when you want to have two distinct names indicating the same variable.
In the given case code, a reference named “a” is created, which signifies the variable “b.” This enables you to access and modify the same data using either “a” or “b.”
int a = 10; int& b = a; |
5. What is the token in C++?
Tokens are the smallest component in a C++ program. It’s a collection of characters that logically or rationally, are connected. It signifies a substantial unit of code and operates as a foundation inside the syntax rules and program structure.
6. What is the difference between C and C++?
C | C++ |
---|---|
It is a procedural programming language. | It is a procedural and Object-oriented programming language. |
It supports integers, floating-point numbers, characters, strings, and pointers. | It supports integers, floating-point numbers, characters, strings, pointers, classes, and objects |
It has user-controlled memory management. | It has Dynamic memory management. |
7. What is the difference between C++ and OOPS?
C++ | OOPs |
---|---|
It is a procedural and Object-oriented programming language. | It is an Object-oriented programming language. |
C++ is specifically employed for game development, programming, etc. | OOPs are not limited to one language, they can be executed in multiple languages |
It focuses on only some basic characteristics. | It focuses on encapsulation, inheritance, and polymorphism. |
8. What is the “std” namespace in C++?
In C++, std stands for “standard”. The “std” namespace is part of the C++ standard library present in C++ which is a collection of related names or identifiers such as functions, classes, and variables. With the help of the “std” namespace, you can retrieve and apply standard library parts easily without naming incompatibilities with different segments of your program or third-party libraries.
Also Read: C++ STL Tutorial
C++ Coding Interview Questions For Freshers
Here is a list of basic C++ coding interview questions for freshers which will help you understand foundational concepts and principles of C++.
9. Write a program to print “My name is John.”
#include <iostream>
int main() {
std::cout << "My name is John." << std::endl;
return 0;
}
10. Write a program to find the multiplication of two numbers.
#include <iostream>
#include <iostream>
int main() {
int num1 = 2;
int num2 = 4;
int sum = num1 * num2;
std::cout << "The product is: " << product << std::endl;
return 0;
}
11. Write a program to find the smallest among three numbers.
#include <iostream>
int main() {
int num1 = 1, num2 = 7, num3 = 11;
int smallest = (num1 < num2) ? ((num1 < num3) ? num1 : num3) : ((num2 < num3) ? num2 : num3);
std::cout << "The smallest number is: " << smallest << std::endl;
return 0;
}
12. Write a program to calculate and find the factorial of a given number.
#include <iostream>
int main() {
int number = 10;
int factorial = 1;
for (int i = 1; i <= number; i++) {
factorial *= i;
}
std::cout << "The factorial of " << number << " is: " << factorial << std::endl;
return 0;
}
13. Write a program to sort an array in ascending order.
#include <algorithm>
#include <iostream>
int main() {
int arr[] = {50, 40, 30, 20, 10};
int n = sizeof(arr) / sizeof(arr[0]);
std::sort(arr, arr + n);
for (int i = 0; i < n; i++) {
std::cout << arr[i] << " ";
}
std::cout << std::endl;
return 0;
}
14. Write a program to print the Fibonacci sequence up to 20 terms.
#include <iostream>
int main() {
int n = 20;
int a = 0, b = 1;
std::cout << a << " " << b << " ";
for (int i = 2; i < n; i++) {
int c = a + b;
std::cout << c << " ";
a = b;
b = c;
}
std::cout << std::endl;
return 0;
}
15. Write a program to find out if the given number is odd or even.
#include <iostream>
int main() {
int number = 24;
if (number % 2 == 0) {
std::cout << number << " is even." << std::endl;
} else {
std::cout << number << " is odd." << std::endl;
}
return 0;
}
C++ Interview Questions for Intermediate Candidates
Here is a list of C++ intermediate interview questions which will help you understand the advanced concepts and nourish your skill set to handle more complicated problems.
Functions Interview Questions in C++
Here is the list of intermediate function interview questions:
16. What is operator overloading?
Operator overloading is a type of polymorphism within which a function is employed to overload or modifies the majority of the operators accessible in C++. It is a precompiled polymorphism, having unique names: the keyword “operator” followed by the character of the operator being defined.
Also Read: Inline Function in C++ With Examples
17. Define polymorphism, encapsulation, and inheritance?
- Polymorphism – It is the combination of “poly” + “morphs” which means many forms. Typically, polymorphism occurs when there is a hierarchy of classes and they are related by inheritance.
- Encapsulation – It is referred to as the Wrapping up of data in a single unit in C++.
- Inheritance – In C++, inheritance is a method by which a single class inherits the attributes from its parent class.
18. What is a virtual function?
A virtual function (commonly called a virtual method). It is a member function in the base class the ones we assume to be changed in subclasses. It is possible to define the function in the base class using the virtual keyword. Once you declare the function in the base class, you have the option to use a pointer or reference to call the virtual class and run its virtual version in the subclass.
19. Explain multithreading in C++.
Multithreading is defined as the property that permits parallel processing of multiple components in a program to optimize CPU utilization. Every component of such a program is known as a thread. So, threads can be described as small programs in larger programs.
20. What is the friend function in ?++.
In C++, the Friend function is defined as the creative function capable of retrieving the private and protected data of a class. We define a friend function employing the friend keyword within the structure of the class.
21. Define smart pointers in C++.
In C++, Smart pointers are instances that contain wrappers encompassing raw pointers and offer automatic memory management. They are members of the C++ runtime library and are executed as template classes. Smart pointers assist in stopping common memory-related errors such as memory leaks, double deletion, and dangling pointers.
22. What is a template in C++
A template is a strong and easy-to-use tool in C++. It is used to transmit the data type as a parameter. This eliminates the requirement to write repetitive programs for various data structures, resulting in, an effortless and more effective way to handle different data.
- The syntax for Function Template
template < class Ttype> ret_type func_name(parameter_list) { // body of function. } |
Programming Interview Question For Intermediate
Here is a list of C++ intermediate programming interview questions which will help you understand the concepts and evaluate your knowledge and skills:
23. Write a program to execute a function to test if a string is a palindrome.
#include <iostream>
#include <algorithm>
using namespace std;
bool isPalindrome(string str) {
string reversed = str;
reverse(reversed.begin(), reversed.end());
return str == reversed;
}
int main() {
string input;
cout << "Enter a string: ";
cin >> input;
if (isPalindrome(input))
cout << "It is a palindrome." << endl;
else
cout << "It is not a palindrome." << endl;
return 0;
}
24. Write a program to check the sum of all odd numbers in an array.
#include <iostream>
using namespace std;
int sumOfOddNumbers(int arr[], int size) {
int sum = 0;
for (int i = 0; i < size; i++) {
if (arr[i] % 2 != 0) // Check if the number is odd
sum += arr[i];
}
return sum;
}
int main() {
int size;
cout << "Enter the size of the array: ";
cin >> size;
int arr[size];
cout << "Enter the elements of the array: ";
for (int i = 0; i < size; i++)
cin >> arr[i];
cout << "Sum of odd numbers: " << sumOfOddNumbers(arr, size) << endl;
return 0;
}
25. Write a program to find the third smallest element in an array
#include <iostream>
#include <climits>
using namespace std;
int findThirdSmallest(int arr[], int size) {
if (size < 3)
return -1; // Invalid input, as array size is less than 3
int smallest = INT_MAX;
int secondSmallest = INT_MAX;
int thirdSmallest = INT_MAX;
for (int i = 0; i < size; i++) {
if (arr[i] < smallest) {
thirdSmallest = secondSmallest;
secondSmallest = smallest;
smallest = arr[i];
} else if (arr[i] < secondSmallest && arr[i] != smallest) {
thirdSmallest = secondSmallest;
secondSmallest = arr[i];
} else if (arr[i] < thirdSmallest && arr[i] != secondSmallest && arr[i] != smallest) {
thirdSmallest = arr[i];
}
}
return thirdSmallest;
}
int main() {
int size;
cout << "Enter the size of the array: ";
cin >> size;
int arr[size];
cout << "Enter the elements of the array: ";
for (int i = 0; i < size; i++)
cin >> arr[i];
int thirdSmallest = findThirdSmallest(arr, size);
if (thirdSmallest != -1)
cout << "The third smallest element is: " << thirdSmallest << endl;
else
cout << "No third smallest element found." << endl;
return 0;
}
26. Write a program to check the greatest common divisor (GCD) of three numbers.
#include <iostream> using namespace std; int findGCD(int a, int b) { if (b == 0) return a; return findGCD(b, a % b); } int findGCD(int a, int b, int c) { return findGCD(findGCD(a, b), c); } int main() { int a, b, c; cout << “Enter three numbers: “; cin >> a >> b >> c; cout << “GCD: ” << findGCD(a, b, c) << endl; return 0; } |
27. Write a program to check the third repeating character in a string.
#include <iostream>
#include <unordered_map>
using namespace std;
char findThirdRepeatingChar(string str) {
unordered_map<char, int> charCount;
for (char ch : str) {
charCount[ch]++;
if (charCount[ch] == 3)
return ch;
}
return '\0'; // If no third repeating character is found
}
int main() {
string str;
cout << "Enter a string: ";
cin >> str;
char thirdRepeatingChar = findThirdRepeatingChar(str);
if (thirdRepeatingChar != '\0')
cout << "The third repeating character is: " << thirdRepeatingChar << endl;
else
cout << "No third repeating character found." << endl;
return 0;
}
28. Write a program to check if a number is prime or not
#include <iostream>
using namespace std;
bool isPrime(int n) {
if (n <= 1)
return false;
for (int i = 2; i * i <= n; i++) {
if (n % i == 0)
return false;
}
return true;
}
int main() {
int number;
cout << "Enter a number: ";
cin >> number;
if (isPrime(number))
cout << number << " is a prime number." << endl;
else
cout << number << " is not a prime number." << endl;
return 0;
}
29. Write a program to check if a number is even or odd
#include <iostream>
using namespace std;
bool isEven(int number) {
return number % 2 == 0;
}
int main() {
int number;
cout << "Enter a number: ";
cin >> number;
if (isEven(number))
cout << number << " is even." << endl;
else
cout << number << " is odd." << endl;
return 0;
}
Advanced C++ Interview Questions for Professionals
Here is a list of C++ language interview questions for professionals which will help you understand the advanced concepts and evaluate your expertise:
Function Interview Questions in C++ for Experienced
Here is the list of advanced function interview questions for experienced candidates.
30. Explain, When is the void() return type executed in C++?
In C++, void() return type is used if a function fails to return a value. This is usually meant for functions that carry out actions, like printing to the console or displaying a message.
For instance, the given function prints the message “Hello, John!” to the terminal:
void printHelloJohn() { System.out.println(“Hello, john!”); } |
Also Read: Virtual Functions in C++
31. Differentiate between shallow copy and deep copy?
Shallow copy | Deep copy |
---|---|
Shallow Copy represents alters, produced into the new/replicated object within the original object. | Deep copy doesn’t represent alters, produced into the new/replicated object within the original object. |
A shallow Copy saves the copy of the original object and directs the pointers to the objects. | A Deep copy saves the copy of the original object and repeatedly replicates the objects as well. |
A shallow copy is faster. | A Deep copy is relatively slower. |
32. Explain ‘call by value’ and ‘call by reference’.
- Call by value – In the call by value procedure of parameter transferring, the inputs of concrete parameters are replicated to the function’s declared parameters.
- Call by reference – In the call by reference technique of parameter transferring, the memory location of the provided parameters is passed to the function as the formal parameters.
33. Explain, Can we call a virtual function from a constructor?
Yes, it is feasible to invoke a virtual function coming from a constructor. On the other hand, it is typically not suggested to carry out this task. When a virtual function is invoked from a constructor, the response can be uncertain or result in unwanted results. This happens because, throughout the construction of an object, the virtual function resolution system may not function as predicted, as the object’s inherited class parts have not yet been entirely constructed.
34. What do you mean by destructors in C++?
Destructor is an object member method that is executed implicitly each time an instance is about to be destroyed. Meaning, a destructor is the last function that is set to be executed prior to an object being destroyed.
35. What is exception handling in C++?
An exception represents an event or entity that is thrown during runtime. Exception Handling in C++ is a procedure to manage execution errors. It is used to carry out error management so the regular flow of the program can be preserved despite runtime errors. Every exception is originated from std::exception class. It is a runtime error that can be handled. If we don’t manage the error, it prints an exception message and terminates the code.
36. What are void pointers in C++?
In C++, A void pointer is a pointer that does not have any associated data type with it. A void pointer can store memory addresses of any kind and can be converted to any class.
Here’s an example of void pointers in C++
#include <iostream>
using namespace std;
int main()
{
int num = 25;
float pi = 3.14;
void* p = # // void pointer holds address of int 'num'
p = π // void pointer holds address of float 'pi'
}
C++ Programming Interview Questions for Experienced
Here is a list of C++ programming interview questions for experienced which will help you understand the application of advanced concepts and evaluate your coding skills:
37. Write a program to check the intersection of single-sorted arrays.
#include <iostream>
#include <vector>
using namespace std;
vector<int> findArrayIntersection(vector<int>& arr) {
vector<int> intersection;
for (int i = 1; i < arr.size(); i++) {
if (arr[i] == arr[i - 1]) {
intersection.push_back(arr[i]);
}
}
return intersection;
}
int main() {
vector<int> arr = {1, 2, 3, 3, 4, 5, 5, 6, 7, 7, 8, 9, 9};
vector<int> intersection = findArrayIntersection(arr);
cout << "Intersection: ";
for (int num : intersection) {
cout << num << " ";
}
cout << endl;
return 0;
}
#include <iostream>
#include <vector>
using namespace std;
vector<int> findArrayIntersection(vector<int>& arr) {
vector<int> intersection;
for (int i = 1; i < arr.size(); i++) {
if (arr[i] == arr[i - 1]) {
intersection.push_back(arr[i]);
}
}
return intersection;
}
int main() {
vector<int> arr = {1, 2, 3, 3, 4, 5, 5, 6, 7, 7, 8, 9, 9};
vector<int> intersection = findArrayIntersection(arr);
cout << "Intersection: ";
for (int num : intersection) {
cout << num << " ";
}
cout << endl;
return 0;
}
38. Write a program to check the factorial of a negative number using recursion.
#include <iostream>
using namespace std;
int factorial(int n) {
if (n < 0) {
cout << "Factorial is not defined for negative numbers." << endl;
return -1; // Return an error value
}
if (n == 0 || n == 1)
return 1;
return n * factorial(n - 1);
}
int main() {
int number;
cout << "Enter a number: ";
cin >> number;
int result = factorial(number);
if (result != -1)
cout << "Factorial of " << number << " is: " << result << endl;
return 0;
}
39. Write a program to reverse a linked list.
struct Node {
int data;
Node* next;
};
Node* reverseLinkedList(Node* head) {
Node* prev = nullptr;
Node* curr = head;
while (curr != nullptr) {
Node* next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
return prev;
}
40. Write a program to reverse a string without utilizing any additional storage.
#include <iostream>
#include <algorithm>
using namespace std;
void reverseString(string& str) {
reverse(str.begin(), str.end());
}
int main() {
string str = "Hello, World!";
reverseString(str);
cout << str << endl;
return 0;
}
41. Write a function to check if a linked list contains a cycle.
struct ListNode {
int val;
ListNode* next;
ListNode(int x) : val(x), next(nullptr) {}
};
bool hasCycle(ListNode* head) {
if (head == nullptr || head->next == nullptr)
return false;
ListNode* slow = head;
ListNode* fast = head;
while (fast != nullptr && fast->next != nullptr) {
slow = slow->next;
fast = fast->next->next;
if (slow == fast)
return true;
}
return false;
}
42. Write a program to verify if a number is an Armstrong number.
#include <iostream>
#include <cmath>
using namespace std;
bool isArmstrongNumber(int number) {
int originalNumber = number;
int sum = 0;
int numDigits = to_string(number).length();
while (number > 0) {
int digit = number % 10;
sum += pow(digit, numDigits);
number /= 10;
}
return sum == originalNumber;
}
int main() {
int number;
cout << "Enter a number: ";
cin >> number;
if (isArmstrongNumber(number))
cout << "It is an Armstrong number." << endl;
else
cout << "It is not an Armstrong number." << endl;
return 0;
}
43. Write a function to find the LCM of four numbers.
#include <bits/stdc++.h>
using namespace std;
int lcm(int a, int b) {
return (a * b) / gcd(a, b);
}
int lcmOfFourNumbers(int a, int b, int c, int d) {
return lcm(lcm(a, b), lcm(c, d));
}
44. Write a function to find the minimum value in an array.
#include <bits/stdc++.h>
using namespace std;
int maxValue(int arr[], int n) {
int max_val = arr[0];
for (int i = 1; i < n; i++) {
if (arr[i] > max_val) {
max_val = arr[i];
}
}
return max_val;
}
45. Write a C++ function to find the longest palindromic substring of a string.
def longest_palindromic_substring(str):
n = len(str)
dp = [[0 for j in range(n + 1)] for i in range(n + 1)]
45. Write a C++ function to find the smallest palindromic substring of a string.
#include <iostream>
#include <string>
using namespace std;
bool isPalindrome(const string& str, int start, int end) {
while (start < end) {
if (str[start] != str[end])
return false;
start++;
end--;
}
return true;
}
string smallestPalindromicSubstring(const string& str) {
int n = str.length();
int minLength = n;
int start = 0;
for (int i = 0; i < n; i++) {
for (int j = i; j < n; j++) {
if (isPalindrome(str, i, j)) {
int length = j - i + 1;
if (length < minLength) {
minLength = length;
start = i;
}
}
}
}
return str.substr(start, minLength);
}
int main() {
string str = "abcaaaedcbf";
string smallestPalindrome = smallestPalindromicSubstring(str);
cout << "Smallest Palindromic Substring: " << smallestPalindrome << endl;
return 0;
}
Conclusion
C++ interview questions will help you understand the foundation for your basics to advance your level, of C++, and enhance your skills to excel in your interview. It is essential to note that the actual questions may vary depending on the specific organization and position that you are applying for. Therefore, make sure you carefully review the job description to ensure proper preparation for the interview.