Search Jobs

Ticker

6/recent/ticker-posts

C++ Interview Questions

Top 50 questions from the list. For more detailed answers.


 * Top 15 Most Asking Program AT THE BOTTOM *


1. What is C++?

 

   - C++ is a general-purpose programming language that extends the C programming language with features like classes, objects, and object-oriented programming.


2. What is the difference between C and C++?

   - C++ is an extension of C with added support for object-oriented programming. C is a procedural programming language, while C++ is a multi-paradigm language.


3. Explain the OOP concepts in C++.

   - Object-oriented programming in C++ includes concepts like encapsulation, inheritance, and polymorphism, which help in modeling real-world problems using classes and objects.


4. What is a class in C++?

   - A class in C++ is a blueprint for creating objects. It defines the data and behavior of the objects.


5. What is an object in C++?

   - An object is an instance of a class. It contains data members and member functions defined in the class.


6. Explain the constructor and destructor in C++.

   - A constructor is a special member function used to initialize objects of a class, while a destructor is used to clean up resources when an object goes out of scope.


7. What is inheritance in C++?

   - Inheritance allows a class to inherit properties and methods from another class, promoting code reuse and creating a hierarchy of classes.


8. What is a derived class and a base class in C++?

   - A derived class is a class that inherits from another class, known as the base class or parent class.


9. Differentiate between private, protected, and public access specifiers.

   - Private members are accessible only within the class, protected members are accessible within the class and derived classes, and public members are accessible from anywhere.


10. What is function overloading?

- Function overloading allows you to have multiple functions with the same name but different parameters in a class. The correct function is chosen based on the arguments used when calling it.



11. What is operator overloading?

- Operator overloading allows you to define custom behaviors for C++ operators (e.g., +, -, *, /) when applied to user-defined types.


12. What is the difference between new and malloc() in C++?

- new is an operator that allocates memory and calls constructors, while malloc() is a library function that allocates memory but doesn't call constructors.


13. Explain dynamic memory allocation in C++.

- Dynamic memory allocation allows you to allocate memory at runtime using operators like new and delete.


14. What are the static and dynamic binding in C++?

- Static binding (early binding) occurs at compile-time, while dynamic binding (late binding) occurs at runtime with polymorphic functions.


15. What is a virtual function?

- A virtual function is a function declared in a base class and redefined in derived classes to achieve runtime polymorphism.


16. What is a pure virtual function?

- A pure virtual function is a virtual function without an implementation in the base class, which makes it mandatory for derived classes to provide an implementation.


17. Explain the concept of multiple inheritance in C++.

- Multiple inheritance allows a class to inherit from more than one base class, but it can lead to ambiguity and the "diamond problem."


18. What is a friend function in C++?

- A friend function is a function that is not a member of a class but is granted access to its private and protected members.


19. What is a template class in C++?

- A template class allows you to define a class with generic types so that it can be reused with different data types.


20. What is the Standard Template Library (STL)?

- The STL is a C++ library that provides templates for various data structures and algorithms, such as vectors, lists, and sorting algorithms.


21. What are the containers in the STL?

- Containers in the STL include vector, list, stack, queue, and map, among others, to store and manipulate data efficiently.


22. Explain the difference between a vector and an array.

- Vectors are dynamic arrays that can grow or shrink, while arrays have a fixed size and are more static.


23. What is a linked list in C++?

- A linked list is a data structure where each element (node) contains data and a reference to the next node, forming a chain.


24. What is a stack and a queue in the STL?

- A stack is a data structure that follows the Last-In-First-Out (LIFO) principle, while a queue follows the First-In-First-Out (FIFO) principle.


25. What is an iterator in the STL?

- An iterator is an object that allows you to traverse and manipulate elements in a container, providing a common interface for different data structures.


26. How does exception handling work in C++?

- C++ uses try-catch blocks to handle exceptions, allowing you to separate error-handling code from the normal flow of the program.


27. What is RAII (Resource Acquisition Is Initialization)?

- RAII is a programming concept where resource management (e.g., memory or file handles) is tied to the lifetime of an object, ensuring automatic cleanup.


28. Explain smart pointers in C++.

- Smart pointers are objects that manage the memory of dynamically allocated objects, automatically releasing memory when it's no longer needed.


29. What is a lambda function in C++?

- A lambda function is an anonymous, inline function that can be defined and used within the scope where it's declared.


30. What is the auto keyword in C++?

- The auto keyword allows the compiler to deduce the type of a variable based on its initializer, reducing the need for explicit type declarations.



31. What is a reference in C++?

- A reference is an alias for an existing variable, allowing you to access or modify the variable without copying its value.


32. What is the size of the C++ data types int, char, and float?

- The size of int is typically 4 bytes, char is 1 byte, and float is 4 bytes, although it may vary on different systems.


33. Explain the scope resolution operator (::) in C++.

- The :: operator is used to access global variables or static members of a class, distinguishing them from local variables.


34. What is a const member function in C++?

- A const member function is a member function that promises not to modify the state of the object it's called on.


35. What is a copy constructor?

- A copy constructor is a special constructor used to create a new object as a copy of an existing object.


36. Describe the Rule of Three and Rule of Five.

- The Rule of Three involves defining a custom destructor, copy constructor, and copy assignment operator if one of them is needed. The Rule of Five adds move constructor and move assignment operator for better performance.


37. What is the C++ Standard Library?

- The C++ Standard Library provides a set of standard classes, functions, and templates to perform common tasks, including I/O operations, containers, and algorithms.


38. What is the difference between a structure and a class?

- In C++, the primary difference is that members of a class have private access by default, while members of a struct have public access by default.


39. How does the C++ preprocessor work?

- The preprocessor processes directives (e.g., #include and #define ) before the actual compilation and is used for macro substitution and including header files.


40. What is the difference between an array and a pointer?

- An array is a fixed-size collection of elements, while a pointer is a variable that stores the memory address of another variable or object.


41. Explain the use of the typeid operator.

- The typeid operator is used to obtain the type information of an object, which is helpful for type identification in runtime.


42. What is the role of the new and delete operators in C++?

    - new allocates memory for objects on the heap and calls constructors, while delete deallocates memory and calls destructors.


43. What is the C++ auto_ptr?

- auto_ptr was a C++98 smart pointer that has been deprecated in favor of safer smart pointers like unique_ptr and shared_ptr .


44. Describe the function object (functor) in C++.

- A function object is an object that can be called like a function, often used in algorithms that require function pointers.


45. How do you handle multiple catch blocks in exception handling?

- Multiple catch blocks allow you to catch different types of exceptions, with the most specific exception type being caught first.


46. What are the storage classes in C++?

- C++ provides storage classes like auto register , static , and extern to control the storage duration and scope of variables.


47. Explain the concept of namespaces in C++.

- Namespaces provide a way to organize code by preventing naming conflicts and ensuring that names are unique within the namespace.


48. What is the C++ volatile keyword used for?

- The volatile keyword is used to indicate that a variable may change its value unexpectedly and should not be optimized by the compiler.


49. What is a const_cast in C++?

-const_cast is a C++ operator used to remove the const qualifier from a variable, allowing you to modify it.


50. What is the C++ const qualifier?

- The const qualifier is used to indicate that a variable's value should not be modified after initialization.



Here are 15 commonly asked program code examples in C++:



1. Hello World Program:

  

#include <iostream>


int main() {

std::cout << "Hello, World!" << std::endl;

return 0;

}

2. Factorial Calculation:


#include <iostream>


int factorial(int n) {

if (n == 0) return 1;

return n * factorial(n - 1);

}


int main() {

int n = 5;

std::cout << "Factorial of " << n << " is " << factorial(n) << std::endl;

return 0;

}

3. Fibonacci Series:


#include <iostream>


int fibonacci(int n) {

if (n <= 1) return n;

return fibonacci(n - 1) + fibonacci(n - 2);

}


int main() {

int n = 10;

std::cout << "Fibonacci Series up to " << n << " terms: ";

for (int i = 0; i < n; i++) {

     std::cout << fibonacci(i) << " ";

}

std::cout << std::endl;

return 0;

}

4. Prime Number Check:


#include <iostream>


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 num = 17;

if (isPrime(num)) {

     std::cout << num << " is a prime number." << std::endl;

} else {

     std::cout << num << " is not a prime number." << std::endl;

}

return 0;

}

5. Palindrome Check:


#include <iostream>

#include <string>


bool isPalindrome(std::string str) {

int left = 0;

int right = str.length() - 1;

while (left < right) {

     if (str[left] != str[right]) return false;

     left++;

     right--;

}

return true;

}


int main() {

std::string word = "racecar";

if (isPalindrome(word)) {

     std::cout << word << " is a palindrome." << std::endl;

} else {

     std::cout << word << " is not a palindrome." << std::endl;

}

return 0;

}

6. Swapping Two Numbers:


#include <iostream>


void swap(int &a, int &b) {

int temp = a;

a = b;

b = temp;

}


int main() {

int x = 5, y = 10;

swap(x, y);

std::cout << "After swapping: x = " << x << ", y = " << y << std::endl;

return 0;

}

7. Find Maximum in an Array:


#include <iostream>


int findMax(int arr[], int size) {

int max = arr[0];

for (int i = 1; i < size; i++) {

     if (arr[i] > max) {

         max = arr[i];

     }

}

return max;

}


int main() {

int arr[] = {3, 8, 1, 12, 5};

int size = sizeof(arr) / sizeof(arr[0]);

int max = findMax(arr, size);

std::cout << "Maximum element in the array is: " << max << std::endl;

return 0;

}

8. Linear Search in an Array:


#include <iostream>


int linearSearch(int arr[], int size, int key) {

for (int i = 0; i < size; i++) {

     if (arr[i] == key) {

         return i;

     }

}

return -1;

}


int main() {

int arr[] = {10, 20, 30, 40, 50};

int key = 30;

int size = sizeof(arr) / sizeof(arr[0]);

int result = linearSearch(arr, size, key);

if (result != -1) {

     std::cout << "Element found at index " << result << std::endl;

} else {

     std::cout << "Element not found." << std::endl;

}

return 0;

}

9. Binary Search in an Array (requires a sorted array):


#include <iostream>


int binarySearch(int arr[], int left, int right, int key) {

while (left <= right) {

     int mid = left + (right - left) / 2;

     if (arr[mid] == key) return mid;

     if (arr[mid] < key) left = mid + 1;

     else right = mid - 1;

}

return -1;

}


int main() {

int arr[] = {10, 20, 30, 40, 50};

int key = 30;

int size = sizeof(arr) / sizeof(arr[0]);

int result = binarySearch(arr, 0, size - 1, key);

if (result != -1) {

     std::cout << "Element found at index " << result << std::endl;

} else {

     std::cout << "Element not found." << std::endl;

}

return 0;

}

10. Bubble Sort:


#include <iostream>

void bubbleSort(int arr[], int size) {

    for (int i = 0; i < size - 1; i++) {

        for (int j = 0; j < size - i - 1; j++) {

            if (arr[j] > arr[j + 1]) {

                int temp = arr[j];

                arr[j] = arr[j + 1];

                arr[j + 1] = temp;

            }

        }

    }

}


int main() {

    int arr[] = {64, 25, 12, 22, 11};

    int size = sizeof(arr) / sizeof(arr[0]);

    bubbleSort(arr, size);

    std::cout << "Sorted array: ";

    for (int i = 0; i < size; i++) {

        std::cout << arr[i] << " ";

    }

    std::cout << std::endl;

    return 0;

}



11. **Selection Sort:**


#include <iostream>


void selectionSort(int arr[], int size) {

    for (int i = 0; i < size - 1; i++) {

        int min_index = i;

        for (int j = i + 1; j < size; j++) {

            if (arr[j] < arr[min_index]) {

                min_index = j;

            }

        }

        int temp = arr[i];

        arr[i] =





Post a Comment

0 Comments