Top C++ Interview Questions | With Answers and Explanations
Are you preparing for a technical interview that involves C++ programming? Look no further. This comprehensive guide covers the most commonly asked C++ interview questions and provides detailed answers to help you ace your next programming interview.
Table of Contents
- Basic C++ Interview Questions
- Intermediate C++ Programming Questions
- Advanced C++ Coding Interview Questions
- Object-Oriented Programming Questions in C++
- C++ STL Interview Questions
- Memory Management Interview Questions on C++
- Multithreading and Concurrency Questions
- Common C++ Coding Challenges
Basic C++ Interview Questions
What is C++?
Answer: C++ is a general-purpose programming language created as an extension of the C programming language. It supports object-oriented, procedural, and generic programming paradigms. C++ was developed by Bjarne Stroustrup at Bell Labs in 1979 and is widely used for system/application software, game development, drivers, client-server applications, and embedded firmware.
What are the key features of C++?
Answer: Key features of C++ include:
- Object-oriented programming
- Platform independence
- Mid-level programming language capabilities
- Rich library support (STL)
- Memory management
- Pointer support
- Compile-time polymorphism through function overloading and templates
- Multi-paradigm support (procedural, object-oriented, functional, etc.)
What's the difference between C and C++?
Answer: The main differences between C and C++ are:
- C++ supports object-oriented programming, while C is procedural
- C++ supports function overloading, C doesn't
- C++ has a Boolean data type, C doesn't (pre-C99)
- C++ supports exception handling directly, C doesn't
- C++ includes reference variables, C doesn't
- C++ has the concept of namespaces, C doesn't
What is a class in C++?
Answer: A class in C++ is a user-defined data type that encapsulates data members and functions operating on the data into a single unit. It is the fundamental building block of object-oriented programming in C++, providing the concept of data hiding, inheritance, and polymorphism.
class Rectangle {
private:
int length;
int width;
public:
// Constructor
Rectangle(int l, int w) : length(l), width(w) {}
// Member function
int area() {
return length * width;
}
};
|
What are access specifiers in C++?
Answer: C++ provides three access specifiers to control the visibility of class members:
- public: Members are accessible from outside the class
- private: Members are only accessible within the class
- protected: Members are accessible within the class and its derived classes
Intermediate C++ Programming Questions
Explain the concept of function overloading in C++.
Answer: Function overloading is a feature of C++ that allows multiple functions with the same name but different parameters (either different types or different number of parameters). This is a form of compile-time polymorphism. The compiler determines which function to call based on the arguments passed.
void print(int i) {
cout << "Integer: " << i << endl;
}
void print(double d) {
cout << "Double: " << d << endl;
}
void print(string s) {
cout << "String: " << s << endl;
}
|
What is operator overloading in C++?
Answer: Operator overloading allows C++ operators to have user-defined meanings when applied to user-defined types (classes). This feature makes code more intuitive and readable by extending the functionality of standard operators.
class Complex {
private:
double real, imag;
public:
Complex(double r, double i) : real(r), imag(i) {}
// Overloading + operator
Complex operator+(const Complex& obj) {
return Complex(real + obj.real, imag + obj.imag);
}
};
|
What are virtual functions in C++?
Answer: Virtual functions are member functions declared in a base class and redefined in derived classes. They enable runtime polymorphism through function overriding. When a virtual function is called using a base class pointer or reference that actually points to a derived class object, the derived class's implementation is executed.
class Base {
public:
virtual void display() {
cout << "Display from Base" << endl;
}
};
class Derived : public Base {
public:
void display() override {
cout << "Display from Derived" << endl;
}
};
|
What is a pure virtual function and an abstract class?
Answer: A pure virtual function is a virtual function with no implementation in the base class, indicated by "= 0" at the end of its declaration. A class containing at least one pure virtual function becomes an abstract class. Abstract classes cannot be instantiated directly and require derived classes to implement all pure virtual functions.
class AbstractShape {
public:
// Pure virtual function
virtual double area() = 0;
};
class Circle : public AbstractShape {
private:
double radius;
public:
Circle(double r) : radius(r) {}
double area() override {
return 3.14159 * radius * radius;
}
};
|
Advanced C++ Coding Interview Questions
Explain RAII (Resource Acquisition Is Initialization) in C++.
Answer: RAII is a C++ programming technique where resource management is tied to object lifetime. Resources (like memory, file handles, etc.) are acquired during object initialization and released during object destruction. This ensures proper cleanup even when exceptions occur.
class ResourceManager {
private:
Resource* resource;
public:
// Constructor acquires resource
ResourceManager() {
resource = new Resource();
}
// Destructor releases resource
~ResourceManager() {
delete resource;
}
};
|
What are smart pointers in C++?
Answer: Smart pointers are objects that act like pointers but provide automatic memory management. They help prevent memory leaks by automatically deallocating memory when no longer needed. C++11 introduced three types of smart pointers:
std::unique_ptr
: Exclusive ownership model
std::shared_ptr
: Shared ownership model with reference counting
std::weak_ptr
: Non-owning reference to a shared_ptr
#include <memory>
void smartPointerExample() {
// Unique pointer
std::unique_ptr<int> uniquePtr = std::make_unique<int>(10);
// Shared pointer
std::shared_ptr<int> sharedPtr1 = std::make_shared<int>(20);
std::shared_ptr<int> sharedPtr2 = sharedPtr1; // Reference count becomes 2
}
|
What is move semantics in C++?
Answer: Move semantics is a C++11 feature that allows resources owned by an rvalue (temporary object) to be moved into an lvalue without creating a copy. This is particularly useful when dealing with large objects or managing resources like dynamic memory, file handles, etc.
class MovableClass {
private:
int* data;
public:
// Constructor
MovableClass(int size) {
data = new int[size];
}
// Move constructor
MovableClass(MovableClass&& other) noexcept {
data = other.data;
other.data = nullptr; // Transfer ownership
}
// Destructor
~MovableClass() {
delete[] data;
}
};
|
Object-Oriented Programming Questions in C++
Explain inheritance in C++.
Answer: Inheritance is an OOP concept that allows a class (derived class) to inherit properties and behaviors from another class (base class). C++ supports five types of inheritance:
- Single inheritance
- Multiple inheritance
- Multilevel inheritance
- Hierarchical inheritance
- Hybrid inheritance
// Base class
class Vehicle {
protected:
string brand;
public:
Vehicle(string b) : brand(b) {}
void honk() {
cout << "Beep!" << endl;
}
};
// Derived class
class Car : public Vehicle {
private:
int wheels;
public:
Car(string b, int w) : Vehicle(b), wheels(w) {}
void display() {
cout << "Brand: " << brand << ", Wheels: " << wheels << endl;
}
};
|
What is polymorphism in C++?
Answer: Polymorphism allows objects of different classes to be treated as objects of a common base class. C++ supports two types of polymorphism:
- Compile-time polymorphism: Achieved through function overloading and operator overloading
- Runtime polymorphism: Achieved through virtual functions and function overriding
class Animal {
public:
virtual void makeSound() {
cout << "Animal sound" << endl;
}
};
class Dog : public Animal {
public:
void makeSound() override {
cout << "Bark" << endl;
}
};
class Cat : public Animal {
public:
void makeSound() override {
cout << "Meow" << endl;
}
};
|
What is encapsulation in C++?
Answer: Encapsulation is the bundling of data and methods that operate on that data within a single unit (class). It also involves restricting direct access to some of the object's components, typically through access modifiers like private, protected, and public
class BankAccount {
private:
double balance;
string accountNumber;
public:
BankAccount(string accNum, double initialBalance) :
accountNumber(accNum), balance(initialBalance) {}
void deposit(double amount) {
if (amount > 0)
balance += amount;
}
bool withdraw(double amount) {
if (amount > 0 && balance >= amount) {
balance -= amount;
return true;
}
return false;
}
double getBalance() const {
return balance;
}
};
|
C++ STL Interview Questions
What is the C++ STL?
Answer: The Standard Template Library (STL) is a powerful set of C++ template classes to provide general-purpose classes and functions with templates that implement many popular and commonly used algorithms and data structures like vectors, lists, queues, and stacks.
Explain the components of STL.
Answer: The STL consists of three main components:
- Containers: Objects that store data (vector, list, map, set, etc.)
- Algorithms: Functions for processing sequences (sort, find, count, etc.)
- Iterators: Objects that connect algorithms with containers
What are the different types of containers in STL?
Answer: STL containers are divided into:
- Sequence containers: vector, list, deque, array, forward_list
- Associative containers: set, multiset, map, multimap
- Unordered associative containers: unordered_set, unordered_multiset, unordered_map, unordered_multimap
- Container adapters: stack, queue, priority_queue
#include <vector>
#include <map>
#include <stack>
void stlContainersExample() {
// Sequence container
std::vector<int> vec = {1, 2, 3, 4, 5};
// Associative container
std::map<string, int> scores = {{"Alice", 95}, {"Bob", 89}};
// Container adapter
std::stack<int> stack;
stack.push(10);
stack.push(20);
}
|
Memory Management Interview Questions on C++
What is the difference between new/delete
and malloc/free
?
Answer:
new/delete
are operators in C++, while malloc/free
are functions in C
new
calls constructors, malloc
doesn't
delete
calls destructors, free
doesn't
new
returns the exact data type, malloc
returns void*
new
can be overloaded, malloc
can't
new
throws an exception on failure, malloc
returns NULL
// Using new/delete
int* p1 = new int;
*p1 = 10;
delete p1;
// Using malloc/free
int* p2 = (int*)malloc(sizeof(int));
*p2 = 10;
free(p2);
|
What are memory leaks and how to prevent them in C++?
Answer: Memory leaks occur when dynamically allocated memory is not deallocated properly, causing the program to consume more memory over time. To prevent memory leaks:
- Always match
new
with delete
and new[]
with delete[]
- Use smart pointers (unique_ptr, shared_ptr)
- Implement RAII (Resource Acquisition Is Initialization)
- Use containers from the STL instead of manual memory management
- Consider using memory leak detection tools
void preventLeaks() {
// Use smart pointers
std::unique_ptr<int> ptr = std::make_unique<int>(42);
// Use RAII
{
ResourceManager rm; // Automatically cleaned up when going out of scope
}
// Use STL containers
std::vector<int> vec = {1, 2, 3};
// No need to manually deallocate
}
|
Multithreading and Concurrency Questions
What is a mutex in C++?
Answer: A mutex (mutual exclusion) is a synchronization primitive that ensures exclusive access to a shared resource in a multi-threaded environment. It prevents data races and ensures thread safety when multiple threads need to access shared data.
#include <mutex>
#include <thread>
std::mutex mtx;
int sharedCounter = 0;
void incrementCounter() {
std::lock_guard<std::mutex> lock(mtx); // RAII-style lock
sharedCounter++;
// lock automatically released when lock_guard goes out of scope
}
|
Explain condition variables in C++
Answer: Condition variables are synchronization primitives used for thread communication. They allow threads to wait until a specific condition is met. Condition variables are typically used with mutexes to solve producer-consumer problems
#include <condition_variable>
#include <mutex>
#include <queue>
std::mutex mtx;
std::condition_variable cv;
std::queue<int> dataQueue;
void producer() {
for (int i = 0; i < 10; ++i) {
{
std::lock_guard<std::mutex> lock(mtx);
dataQueue.push(i);
}
cv.notify_one(); // Notify one waiting thread
}
}
void consumer() {
while (true) {
std::unique_lock<std::mutex> lock(mtx);
cv.wait(lock, [] { return !dataQueue.empty(); });
int data = dataQueue.front();
dataQueue.pop();
lock.unlock();
// Process data
if (data == 9) break;
}
}
|
Common C++ Coding Interview Questions
How would you implement a singleton pattern in C++?
Answer: A singleton pattern ensures a class has only one instance and provides a global point of access to it. Here's a thread-safe implementation in C++11:
class Singleton {
private:
// Private constructor
Singleton() {}
// Delete copy constructor and assignment operator
Singleton(const Singleton&) = delete;
Singleton& operator=(const Singleton&) = delete;
public:
static Singleton& getInstance() {
static Singleton instance; // Guaranteed to be destroyed, instantiated on first use
return instance;
}
void someBusinessLogic() {
// Function implementation
}
};
|
How would you reverse a linked list in C++?
Answer: Here's how to reverse a singly linked list in C++:
struct ListNode {
int val;
ListNode* next;
ListNode(int x) : val(x), next(nullptr) {}
};
ListNode* reverseList(ListNode* head) {
ListNode* prev = nullptr;
ListNode* current = head;
ListNode* next = nullptr;
while (current != nullptr) {
next = current->next; // Store next node
current->next = prev; // Reverse the link
prev = current; // Move prev one step forward
current = next; // Move current one step forward
}
return prev; // New head of the reversed list
}
|
Write a function to find if a string is a palindrome
Answer: A palindrome is a string that reads the same backward as forward. Here's a C++ function to check if a string is a palindrome:
bool isPalindrome(const std::string& str) {
int left = 0;
int right = str.length() - 1;
while (left < right) {
// Skip non-alphanumeric characters
while (left < right && !isalnum(str[left])) left++;
while (left < right && !isalnum(str[right])) right--;
// Compare characters ignoring case
if (tolower(str[left]) != tolower(str[right])) {
return false;
}
left++;
right--;
}
return true;
}
|
These C++ interview questions and answers cover a wide range of topics that you might encounter during programming interviews. Study them thoroughly, practice coding implementations, and you'll be well-prepared to tackle C++ coding interview questions and ace your next technical interview!
Remember that interviewers aren't just looking for correct answers but also your problem-solving approach, coding style, and understanding of C++ concepts. Be ready to explain your solutions and discuss alternative approaches as well.
Good luck with your C++ programming interview!