
Preparing for a C++ interview? This guide offers 50 thoughtfully selected C++ interview questions, complete with concise explanations—ideal for those at the beginning of their careers. Topics span foundational concepts, object-oriented programming, the Standard Template Library, and practical coding challenges. With this resource, you’ll strengthen your understanding and approach technical interviews with greater assurance.
Basic C++ Questions
1. What is C++?
C++ is an extension of the C programming language, developed by Bjarne Stroustrup in 1985. It incorporates object-oriented features, such as classes and objects, into the procedural foundation of C. The language supports multiple programming paradigms—procedural, object-oriented, and generic—making it suitable for a wide range of applications, including systems programming, game development, and other performance-critical domains.
2. What are the main features of C++?
C++ is characterized by its support for object-oriented programming principles, including encapsulation, inheritance, and polymorphism. Additional features include templates, robust exception handling, and the Standard Template Library (STL), which provides reusable data structures and algorithms. The language also allows for fine-grained memory management, contributing to its reputation for high performance and suitability for system-level programming.
3. What is the difference between C and C++?
C is a procedural programming language known for its efficiency and simplicity. In contrast, C++ builds upon C by introducing object-oriented constructs such as classes, objects, inheritance, and polymorphism, as well as templates. C++ also offers the STL and improved mechanisms for memory management. While C focuses on procedural programming, C++ accommodates both procedural and object-oriented approaches.
4. What is a class in C++?
A class in C++ serves as a user-defined data type, providing a blueprint for creating objects. It encapsulates data (attributes) and functions (methods) within a single unit, supporting the principles of encapsulation and data hiding. For example:
class Car {
public:
string model;
void drive() {
cout << "Driving " << model;
}
};
5. What is an object in C++?
An object is an instance of a class, created in memory to represent a specific entity based on the class blueprint. Example:
Car myCar;
creates an object myCar
of class Car
.
6. What are access specifiers in C++?
Access specifiers define the accessibility of class members: public
(accessible everywhere), private
(accessible only within the class), and protected
(accessible in the class and its derived classes).
7. What is the difference between a class and a structure?
In C++, a class has private members by default, while a structure has public members by default. Both can contain data and functions, but classes are typically used for OOP, while structures are used for simple data grouping.
8. What is a constructor in C++?
A constructor is a special member function with the same name as the class, used to initialize objects. It is called automatically when an object is created. Example:
class MyClass {
public:
MyClass() {
cout << "Default constructor";
}
};
9. What is a destructor in C++?
A destructor is a special member function called when an object is destroyed to free resources. It has the same name as the class, preceded by a tilde (~). Example:
class MyClass {
public:
~MyClass() {
cout << "Destructor called";
}
};
10. What is the difference between call by value and call by reference?
In call by value, a copy of the parameter is passed, and changes don’t affect the original. In call by reference, the address is passed, and changes affect the original variable. Example:
void swapByValue(int a, int b) { int temp = a; a = b; b = temp; }
void swapByReference(int& a, int& b) { int temp = a; a = b; b = temp; }
11. What is a namespace in C++?
A namespace is a declarative region that organizes code to avoid naming conflicts. The std
namespace contains standard library components like cout
. Example: using namespace std;
12. What is the purpose of the ‘this’ pointer?
The this
pointer holds the address of the current object, used to resolve conflicts between class attributes and method parameters.
13. What is the difference between declaration and definition?
Declaration specifies a variable’s type and name without allocating memory (e.g., extern int x;
). Definition allocates memory and assigns a value (e.g., int x = 5;
).
14. What is the scope resolution operator (::)?
The scope resolution operator ::
accesses entities in a specific scope, like std::cout
or class members.
15. What is a pointer in C++?
A pointer is a variable that stores a memory address. Example:
int* ptr = &x;
points to the address of variable x
.
Object-Oriented Programming (OOP) Questions
16. What is encapsulation?
Encapsulation hides a class’s internal data by making it private and providing public methods to access or modify it, ensuring data protection.
17. What is inheritance?
Inheritance allows a derived class to inherit properties and methods from a base class, promoting code reuse. Example:
class Car : public Vehicle
.
18. What is polymorphism?
Polymorphism allows objects of different classes to be treated as objects of a common base class, with behavior varying based on the object type. It includes compile-time (overloading) and runtime (overriding) polymorphism.
19. What is the difference between compile-time and runtime polymorphism?
Compile-time polymorphism is achieved through function or operator overloading, resolved at compile time. Runtime polymorphism uses virtual functions and is resolved at runtime. Example:
class Base {
public:
virtual void display() { cout << "Base"; }
};
class Derived : public Base {
void display() override { cout << "Derived"; }
};
20. What is a virtual function?
A virtual function is a member function in a base class that can be overridden in a derived class, enabling runtime polymorphism. It is declared with the virtual
keyword.
21. What is an abstract class?
An abstract class contains at least one pure virtual function (virtual void func() = 0;
) and cannot be instantiated. It serves as a base for derived classes.
22. What is a copy constructor?
A copy constructor initializes an object using another object of the same class. Example:
class MyClass {
public:
MyClass(const MyClass& obj) { cout << "Copy constructor"; }
};
23. What is operator overloading?
Operator overloading allows defining custom behavior for operators (e.g., +, -) for user-defined types. Example:
class Complex {
private: float r, i;
public:
Complex(float r, float i) : r(r), i(i) {}
Complex operator+(Complex c) {
return Complex(r + c.r, i + c.i);
}
};
24. What is the Rule of Three?
The Rule of Three states that if a class defines a destructor, copy constructor, or copy assignment operator, it should define all three to manage resources properly.
25. What is the difference between method overloading and overriding?
Method overloading involves multiple functions with the same name but different parameters in the same class (compile-time). Method overriding involves redefining a virtual function in a derived class (runtime).
Memory Management Questions
26. What is a pointer vs. a reference?
The distinction between a pointer and a reference is crucial in programming. A pointer serves as a variable that holds the address of another variable in memory. It can be reassigned to point elsewhere or set to null if needed. In contrast, a reference acts as an alias for an existing variable. Once initialized, it cannot be reseated to refer to another object, nor can it be null.
27. What is dynamic memory allocation?
Dynamic memory allocation refers to allocating memory during a program’s execution rather than at compile time. In C++, the new operator allocates memory on the heap, and the delete operator is used to release that memory when it is no longer needed. For example:int* ptr = new int(5); delete ptr;
28. What is a segmentation fault?
A segmentation fault occurs when a program attempts to access memory that it is not permitted to reach—such as dereferencing a null pointer or accessing memory outside the bounds of an array. This results in an abrupt termination of the program.
29. What are smart pointers?
Smart pointers—including unique_ptr, shared_ptr, and weak_ptr—are objects that manage memory automatically. They ensure that dynamically allocated memory is properly released when it is no longer needed, thereby preventing memory leaks and dangling pointers.
30. What is the purpose of the ‘mutable’ keyword?
The mutable keyword in C++ allows a member variable of a class to be modified even if it is part of an object declared as const. This is particularly useful for cases like internal caches, where logical constness needs to be maintained while still allowing some internal state to change.
Standard Template Library (STL) Questions
31. What is the Standard Template Library (STL)?
The STL is a library of template classes providing containers (e.g., vector, list), algorithms (e.g., sort, search), and iterators for generic programming.
32. What is an iterator in C++?
An iterator is a pointer-like object used to traverse elements in an STL container.
Example:
vector
33. What is a vector in C++?
A vector is a dynamic array in the STL that can resize itself. Example:
#include
vector<int> v = {1, 2, 3};
v.push_back(4);
34. What is the difference between a vector and an array?
A vector is dynamic and can resize, while an array has a fixed size. Vectors provide STL functions like push_back
, unlike arrays.
35. What is a stack in C++?
A stack is an STL container adapter following LIFO (Last In, First Out). Example:
#include
stack<int> s;
s.push(10);
Coding Questions
36. Write a program to reverse a string.
This program reverses a string using two pointers:
#include
using namespace std;
void reverse(string& s) {
int i = 0, j = s.length() - 1;
while (i < j) {
swap(s[i++], s[j--]);
}
}
int main() {
string s = "hello";
reverse(s);
cout << s; // Output: olleh
return 0;
}
37. Write a program to find the sum of an array.
This program calculates the sum of array elements:
#include
using namespace std;
int sum(int arr[], int n) {
int total = 0;
for (int i = 0; i < n; i++) total += arr[i];
return total;
}
int main() {
int arr[] = {1, 2, 3, 4, 5};
int n = sizeof(arr) / sizeof(arr[0]);
cout << sum(arr, n); // Output: 15
return 0;
}
38. Write a program to find the second smallest element in an array.
This program finds the second smallest element:
#include
#include
using namespace std;
void print2Smallest(int arr[], int n) {
int first = INT_MAX, second = INT_MAX;
if (n < 2) { cout << "Invalid Input"; return; }
for (int i = 0; i < n; i++) {
if (arr[i] < first) { second = first; first = arr[i]; }
else if (arr[i] < second && arr[i] != first) second = arr[i];
}
cout << second; // Example: {21, 3, 15} -> 15
}
39. Write a program to print a star pattern (triangle).
This program prints a star triangle:
#include
using namespace std;
void pattern(int n) {
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++) cout << "* ";
cout << endl;
}
}
int main() {
pattern(4); // Output: * \n * * \n * * * \n * * * *
return 0;
}
40. Write a program to find the GCD of two numbers.
This program finds the GCD using the Euclidean algorithm:
#include
using namespace std;
int gcd(int p, int q) {
if (q == 0) return p;
return gcd(q, p % q);
}
int main() {
cout << gcd(36, 60); // Output: 12
return 0;
}
Miscellaneous Questions
41. What is the ‘const’ keyword used for?
The const
keyword ensures a variable’s value cannot be modified after initialization. It’s also used in functions to prevent modification of parameters or objects.
42. What is an inline function?
An inline function is expanded at the call site to avoid function call overhead, improving performance for small functions. Example:
inline int square(int x) { return x * x; }
43. What is exception handling?
Exception handling manages runtime errors using try
, catch
, and throw
. Example:
try { throw "Error"; }
catch (const char* msg) { cout << msg; }
44. What is a static member?
A static member belongs to the class, not an object, and is shared by all instances. It’s initialized before main()
and accessed using the class name.
45. What is the ‘explicit’ keyword?
The explicit
keyword prevents implicit conversions in constructors. Example:
explicit MyClass(int x);
46. What is a friend function?
A friend function is a non-member function granted access to a class’s private members. Example:
friend void access(ClassName obj);
47. What is a template in C++?
A template allows generic programming by defining functions or classes that work with any data type. Example:
template <typename T>
T max(T x, T y) { return (x > y) ? x : y; }
48. What is the ‘auto’ keyword?
The ‘auto’ keyword allows the C++ compiler to deduce the type of a variable automatically at compile time. For instance:
auto x = 5; // Here, x is deduced to be of type int.
49. What is a virtual destructor?
A virtual destructor ensures that when an object of a derived class is deleted through a pointer to the base class, the destructor of the derived class is invoked. This mechanism prevents resource leaks and guarantees correct object cleanup in polymorphic class hierarchies.
50. What is the ‘constexpr’ keyword?
The ‘constexpr’ keyword specifies that the value of a function or variable can be evaluated at compile time. Using constexpr can improve program performance by enabling computations to occur before runtime. For example:
constexpr int square(int x) { return x * x; }
This function can be evaluated during compilation for constant expressions.
Conclusion
Gaining proficiency with these 50 C++ interview questions equips newcomers with a solid technical base for interviews. The topics span from fundamental syntax and object-oriented programming to Standard Template Library concepts and classic coding challenges. Diligent practice on coding platforms such as LeetCode can further consolidate your understanding and enhance your confidence in a real interview setting.