C++ is used in a wide variety of industries, from gaming and finance to the IoT and embedded systems. The breadth of the C++ ecosystem demands that coding challenges should be tailored to developers of varying skill levels so that everyone can be evaluated accordingly.
This article presents a curated collection of C++ programming challenges appropriate for developers at all experience levels. Now, let’s start with beginner-level challenges.
Interview Questions for Beginner C++ Developers
When designing coding questions for beginner C++ developers, prepare questions that test areas of C++ like basic input/output, data types and variables, operators, control structures, functions, arrays, strings, pointers, dynamic memory allocation and references. Here are 10 coding challenges in this regard:
Question 1
What will be the output of the below code:
#include <iostream>
using namespace std;
int factorial(int n) {
if (n <= 1) {
return 1;
}
return n * factorial(n - 1);
}
int main() {
int num = 4;
cout << factorial(num) << endl;
return 0;
}:
Question 2
Guess the output of the below code:
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "Hello, World!";
char *ptr = &str[7];
cout << ptr << endl;
return 0;
}
Question 3
Identify the issue in the below code:
#include <iostream>
using namespace std;
int main() {
float a = 3.5, b = 1.5;
if (a % b == 0) {
cout << "Divisible" << endl;
} else {
cout << "Not divisible" << endl;
}
return 0;
}
Question 4
Develop a program that reads a text file and counts the total number of words in it. Use file I/O, strings, control structures and loops. To split the text into words by whitespace and punctuation, you can use a basic tokenizer.
Question 5
What will be the output of the below code?
#include <iostream>
using namespace std;
class Dog {
public:
string breed;
Dog(string breed) {
this->breed = breed;
}
void bark() {
cout << "Woof! I'm a " << breed << "!" << endl;
}
};
int main() {
Dog myDog("Golden Retriever");
myDog.bark();
return 0;
}
Question 6
Will the below code throw any error? If yes, identify the error.
#include <iostream>
using namespace std;
void doubleValue(int &num) {
num *= 2;
}
int main() {
int value = 5;
doubleValue(value);
cout << value << endl;
return 0;
}
Question 7
Implement a grade calculator that takes the scores of a student in multiple subjects and calculates the final grade based on a given weightage for each subject. You can use arrays, input/output, control structures and functions.
Question 8
Analyze the below code and suggest the output:
#include <iostream>
using namespace std;
int main() {
int a = 5, b = 2;
if (a % b == 1) {
cout << "Odd" << endl;
} else {
cout << "Even" << endl;
}
return 0;
}
Question 9
Find the issue with the below code snippet:
#include <iostream>
using namespace std;
int main() {
int arr[] = {1, 2, 3, 4, 5};
for (int i = 5; i > 0; i--) {
cout << arr[i] << " ";
}
return 0;
}
Question 10
Analyze the below code and suggest if it correctly deletes the dynamically allocated object “mycat”. Add the missing code, if any.
#include <iostream>
using namespace std;
class Cat {
public:
string name;
Cat(string name) {
this->name = name;
}
void meow() {
cout << "Meow! My name is " << name << "!" << endl;
}
};
int main() {
Cat *myCat = new Cat("Molly");
myCat->meow();
return 0;
}
Interview Questions for Mid-level C++ Developers
When designing interview questions for mid-level C++ developers, you should prepare challenges keeping in mind the understanding of advanced C++ concepts, problem-solving capabilities and grip on different libraries. Some important concepts that should be evaluated include advanced object-oriented programming, operator overloading, template programming, exception handling, C++ standard library, memory management, advanced pointers, lambda expressions and closures, design patterns and concurrency. Below you will find 10 coding challenges which are suited to mid-level C++ developers:
Question 1
What is the issue in the below code:
#include <iostream>
using namespace std;
class Base {
public:
virtual void display() { cout << "Base" << endl; }
};
class Derived:public Base {
public:
void display() { cout << "Derived" << endl; }
};
int main() {
Base* b = new Derived();
delete b;
b->display();
return 0;
}
Question 2
What will be the output of the below code:
#include <iostream>
using namespace std;
class Complex {
public:
int real, imag;
Complex(int r, int i) : real(r), imag(i) {}
Complex operator+(const Complex &c) {
return Complex(real + c.real, imag + c.imag);
}
};
int main() {
Complex c1(3, 2), c2(1, 7);
Complex c3 = c1 + c2;
cout << c3.real << " + " << c3.imag << "i" << endl;
return 0;
}
Question 3
You need to develop a custom string class having basic functionalities like concatenation, substring search and string length. You can take advantage of advanced object-oriented programming, operator overloading and exception handling to implement this class.
Question 4
Develop a command-line calculator that will take an expression as an input parameter. It will compute the result and return it as an output parameter. You can use the C++ Standard Library, lambda expressions and closures to parse and evaluate the input. Make sure to handle errors with appropriate exceptions.
Question 5
Will the below code throw any error?
#include <iostream>
using namespace std;
template <typename T>
void swap(T& a, T& b) {
T temp = a;
a = b;
b = temp;
}
int main() {
int x = 3, y = 5;
swap(x, y);
cout << x << " " << y << endl;
return 0;
}
Question 6
What will be the output of the below code:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
vector<int> nums = {1, 2, 3, 4, 5};
int x = 3;
auto result = find_if(nums.begin(), nums.end(), [x](int n) { return n > x; });
cout << *result << endl;
return 0;
}
Question 7
Analyze the below code and suggest if throwing a string literal is fine. If not, what is the best practice in this regard?
#include <iostream>
using namespace std;
double divide(double a, double b) {
if (b == 0) {
throw "Division by zero";
}
return a / b;
}
int main() {
try {
cout << divide(10, 2) << endl;
cout << divide(10, 0) << endl;
} catch (const char* msg) {
cout << "Error: " << msg << endl;
}
return 0;
}
Question 8
You need to develop a simple task scheduler that will allow users to schedule tasks with a given priority and execute them in the priority order. You can use the C++ Standard Library (e.g., priority_queue), design patterns and memory management techniques to implement the scheduler.
Question 9
Analyze the below code and advise if it will lead to data race conditions. If that is correct, what can be done to fix it?
#include <iostream>
#include <thread>
#include <vector>
using namespace std;
void worker(int id, vector<int>& data) {
data[id] = id;
}
int main() {
vector<int> data(5);
vector<thread> workers;
for (int i = 0; i < 5; ++i) {
workers.push_back(thread(worker, i, data));
}
for (auto& t : workers) {
t.join();
}
for (int v : data) {
cout << v << " ";
}
return 0;
}
Question 10
You need to create an image processing library that will have the features of read, write, and manipulate images (e.g., resize, rotate and color conversions). You can use advanced object-oriented programming, C++ Standard Library and design patterns to implement this.
Interview Questions for Expert C++ Developers
When preparing coding challenges for expert-level C++ engineers, you should expect a deep understanding of the language and the ability to apply the knowledge efficiently. Some of the core areas for evaluating expert C++ programmers are advanced template metaprogramming, modern C++ features, performance optimization, advanced concurrency, compiler and language internals, metaclasses (C++23), design patterns, architecture and interfacing with other languages. Find below 10 coding challenges for expert C++ developers:
Question 1
Is there any security vulnerability in the below code? If yes, identify it and suggest a secure implementation. Hint: Buffer overflow attack.
#include <iostream>
#include <cstring>
void getPassword(char *buffer) {
std::cout << "Enter your password: ";
std::cin >> buffer;
}
int main() {
char password[32];
getPassword(password);
std::cout << "Your password is: " << password << std::endl;
return 0;
}
Question 2
Identify the output of the below code.
#include <iostream>
template <int N>
struct Factorial {
static constexpr int value = N * Factorial<N - 1>::value;
};
template <>
struct Factorial<0> {
static constexpr int value = 1;
};
int main() {
std::cout << Factorial<5>::value << std::endl;
return 0;
}
Question 3
What is the possible performance issue in the below code? Hint: performance bottleneck due to fine-grained locking.
#include <iostream>
#include <mutex>
#include <thread>
std::mutex mtx;
int counter = 0;
void increment() {
for (int i = 0; i < 10000; ++i) {
std::unique_lock<std::mutex> lock(mtx);
++counter;
}
}
int main() {
std::thread t1(increment);
std::thread t2(increment);
t1.join();
t2.join();
std::cout << counter << std::endl;
return 0;
}
Question 4
Suggest the output of the below code:
#include <iostream>
#include <variant>
using Var = std::variant<int, double>;
double sum(Var v1, Var v2) {
return std::visit([](auto&& a, auto&& b) { return a + b; }, v1, v2);
}
int main() {
Var v1 = 3;
Var v2 = 4.5;
std::cout << sum(v1, v2) << std::endl;
return 0;
}
Question 5
You need to implement a type-safe, high-performant and generic matrix library that supports basic arithmetic operations and uses advanced template metaprogramming, modern C++ features and performance optimization techniques. This library should be able to handle different data types and automatically select the most appropriate and efficient algorithm for the given operation and data type.
Question 6
Analyze the below code and advise what is missing from the code. Hint: Missing specialization for const pointers.
template <typename T>
struct is_pointer : std::false_type {};
template <typename T>
struct is_pointer<T*> : std::true_type {}; // Issue: Missing specialization for T* const
int main() {
int* p = nullptr;
const int* cp = nullptr;
std::cout << is_pointer<decltype(p)>::value << " " << is_pointer<decltype(cp)>::value << std::endl;
return 0;
}
Question 7
What will be the output of below code snippet?
#include <iostream>
#include <future>
#include <vector>
int square(int x) {
return x * x;
}
int main() {
std::vector<int> data{1, 2, 3, 4, 5};
std::vector<std::future<int>> futures;
for (int x : data) {
futures.push_back(std::async(std::launch::async, square, x));
}
int sum = 0;
for (auto& f : futures) {
sum += f.get();
}
std::cout << sum << std::endl;
return 0;
}
Question 8
Develop a real-time image processing library using modern C++ features and performance optimization techniques, such as SIMD instructions and parallel algorithms. The library should support different image processing algorithms, such as blurring, edge detection and color manipulation. It should also be able to handle different image formats and color spaces.
Question 9
What is wrong with the below code?
#include <iostream>
#include <any>
int main() {
std::any a = 42;
try {
std::cout << std::any_cast<double>(a) << std::endl;
} catch (const std::bad_any_cast& e) {
std::cout << e.what() << std::endl;
}
return 0;
}
Question 10
Design and implement a high-performance thread-safe data structure using advanced concurrency techniques. It can be a lock-free queue or a concurrent hash map. The data structure should have excellent scalability and efficiency in multi-threaded scenarios and it should be easy to use and integrate into other projects.
Conclusion
This article presented 30 different C++ coding challenges for gauging the competence of C++ programmers of varying degrees of experience. These challenges help interviewers evaluate a developer’s technical skills in their entirety by testing them in a wide variety of contexts and focusing on various aspects of programming, such as debugging, predicting outputs and solving problems.
These challenges can be helpful evaluation instrument; however, they shouldn’t be used in isolation to judge a programmer’s competence. Different soft skills like communication, cooperation and flexibility are equally important. Incorporating these challenges into your hiring procedures will certainly help you find and nurture talented C++ developers which will ultimately benefit your organization.
Further reading: