Preparing for a C++ programming job interview? This section is designed to help you tackle some of the most common and challenging questions that you might encounter. Whether you're a beginner or an experienced developer, these questions will test your understanding of core concepts, problem-solving skills, and coding efficiency.
new and delete in C++?Answer:
new is used to allocate memory for an object at runtime, while delete is used to deallocate that memory. Using new without a corresponding delete can lead to memory leaks.
1#include <iostream>23int main() {4int* ptr = new int(10);5std::cout << *ptr << std::endl;6delete ptr; // Don't forget to free the allocated memory7return 0;8}
std::vector and std::array?Answer:
std::vector is a dynamic array that can resize itself during runtime, while std::array is a fixed-size array with a size known at compile time.
1#include <iostream>2#include <vector>3#include <array>45int main() {6std::vector<int> vec = {1, 2, 3};7std::array<int, 3> arr = {4, 5, 6};89vec.push_back(4); // Can add elements to vector10// arr.push_back(7); // Error: push_back is not a member of std::array1112return 0;13}
std::unique_ptr, std::shared_ptr, and std::weak_ptr.Answer:
std::unique_ptr: Owns the object it points to and does not allow copying.std::shared_ptr: Allows multiple pointers to share ownership of an object, with reference counting.std::weak_ptr: Does not own the object but provides a non-owning reference.1#include <iostream>2#include <memory>34int main() {5std::unique_ptr<int> uniquePtr = std::make_unique<int>(10);6// std::unique_ptr<int> anotherUniquePtr = uniquePtr; // Error: cannot copy78std::shared_ptr<int> sharedPtr = std::make_shared<int>(20);9std::shared_ptr<int> anotherSharedPtr = sharedPtr; // Valid, reference count increases1011std::weak_ptr<int> weakPtr = sharedPtr;1213return 0;14}
override and final keywords?Answer:
override: Used to explicitly indicate that a member function is intended to override a base class function.final: Used to prevent further overriding of a virtual function in derived classes.1#include <iostream>23class Base {4public:5virtual void display() final { // 'display' cannot be overridden6std::cout << "Display from Base" << std::endl;7}8};910class Derived : public Base {11public:12// void display() override; // Error: 'display' is final in base class13};1415int main() {16Base* basePtr = new Base();17basePtr->display(); // Outputs: Display from Base18delete basePtr;19return 0;20}
std::move and std::forward?Answer:
std::move: Converts an lvalue to an rvalue reference, effectively transferring ownership.std::forward: Preserves the value category (lvalue or rvalue) of its argument.1#include <iostream>2#include <utility>34void print(int& x) { std::cout << "L-value: " << x << std::endl; }5void print(int&& x) { std::cout << "R-value: " << x << std::endl; }67template<typename T>8void forward_example(T&& arg) {9print(std::forward<T>(arg));10}1112int main() {13int a = 10;14forward_example(a); // Outputs: L-value15forward_example(20); // Outputs: R-value16return 0;17}
std::bind and lambda expressions?Answer:
std::bind: Binds arguments to a function, creating a callable object.1#include <iostream>2#include <functional>34void print(int x) {5std::cout << "Value: " << x << std::endl;6}78int main() {9int value = 10;1011// Using std::bind12auto boundFunc = std::bind(print, value);13boundFunc(); // Outputs: Value: 101415// Using lambda expression16auto lambdaFunc = [value]() { print(value); };17lambdaFunc(); // Outputs: Value: 101819return 0;20}
Answer:
A template allows you to write generic code that can operate on different data types.
1#include <iostream>23template<typename T>4T add(T a, T b) {5return a + b;6}78int main() {9std::cout << "Sum of integers: " << add(3, 4) << std::endl;10std::cout << "Sum of doubles: " << add(2.5, 3.1) << std::endl;11return 0;12}
std::vector and std::list?Answer:
std::vector: Provides fast random access but slower insertions/deletions.std::list: Provides fast insertions/deletions but slower random access.1#include <iostream>2#include <vector>3#include <list>45int main() {6std::vector<int> vec = {1, 2, 3};7std::list<int> lst = {4, 5, 6};89// Inserting at the end10vec.push_back(7);11lst.push_back(8);1213// Inserting at the front14vec.insert(vec.begin(), 0);15lst.insert(lst.begin(), 9);1617return 0;18}
Answer:
A friend class is a class whose members can access the private and protected members of another class.
1#include <iostream>23class SecretHolder {4private:5int secret = 42;67public:8friend class FriendClass;9};1011class FriendClass {12public:13void revealSecret(const SecretHolder& obj) {14std::cout << "The secret is: " << obj.secret << std::endl;15}16};1718int main() {19SecretHolder holder;20FriendClass friendObj;21friendObj.revealSecret(holder); // Outputs: The secret is: 4222return 0;23}
Answer:
A copy constructor is a special member function that initializes an object using another object of the same class.
1#include <iostream>2#include <string>34class Person {5public:6std::string name;78Person(const std::string& n) : name(n) {}910// Copy constructor11Person(const Person& other) : name(other.name) {12std::cout << "Copy constructor called" << std::endl;13}14};1516int main() {17Person original("Alice");18Person copy = original; // Copy constructor is called1920std::cout << "Original: " << original.name << ", Copy: " << copy.name << std::endl;2122return 0;23}
std::string and char*?Answer:
std::string: Provides a high-level interface for strings with automatic memory management.char*: A pointer to a character array, requires manual memory management.1#include <iostream>2#include <string>34int main() {5std::string str = "Hello";6char* cstr = new char[6];7strcpy(cstr, "World");89std::cout << "String: " << str << std::endl;10std::cout << "Char array: " << cstr << std::endl;1112delete[] cstr; // Don't forget to free the allocated memory13return 0;14}
std::set and std::unordered_set?Answer:
std::set: Maintains elements in sorted order, with logarithmic time complexity for insertions and deletions.std::unordered_set: Uses a hash table to store elements, providing average constant-time complexity for insertions and deletions.1#include <iostream>2#include <set>3#include <unordered_set>45int main() {6std::set<int> s = {5, 3, 8};7std::unordered_set<int> us = {2, 7, 1};89// Inserting elements10s.insert(6);11us.insert(4);1213// Iterating over sets14for (const auto& elem : s) {15std::cout << elem << " ";16}17std::cout << std::endl;1819for (const auto& elem : us) {20std::cout << elem << " ";21}22return 0;23}
std::thread and std::async?Answer:
std::thread: Creates a new thread of execution.std::async: Launches a task asynchronously and returns a std::future.1#include <iostream>2#include <thread>3#include <future>45int compute() {6return 42;7}89int main() {10std::thread t(compute);11t.join();1213auto future = std::async(std::launch::async, compute);14int result = future.get();15std::cout << "Result: " << result << std::endl; // Outputs: Result: 421617return 0;18}
std::shared_ptr and std::unique_ptr?Answer:
std::shared_ptr: Allows multiple pointers to share ownership of an object.std::unique_ptr: Owns the object exclusively, cannot be copied.1#include <iostream>2#include <memory>34int main() {5std::unique_ptr<int> uniquePtr = std::make_unique<int>(10);6// std::unique_ptr<int> anotherUniquePtr = uniquePtr; // Error: cannot copy78std::shared_ptr<int> sharedPtr = std::make_shared<int>(20);9std::shared_ptr<int> anotherSharedPtr = sharedPtr; // Valid, reference count increases1011return 0;12}
Answer:
A functor is an object that can be called like a function.
1#include <iostream>23class Adder {4public:5int operator()(int a, int b) const {6return a + b;7}8};910int main() {11Adder adder;12std::cout << "Sum: " << adder(3, 4) << std::endl; // Outputs: Sum: 713return 0;14}
Answer:
Template specialization allows you to provide a specific implementation for a particular type.
1#include <iostream>23template<typename T>4T add(T a, T b) {5return a + b;6}78// Specialization for std::string9template<>10std::string add<std::string>(std::string a, std::string b) {11return a + " " + b;12}1314int main() {15std::cout << "Sum of integers: " << add(3, 4) << std::endl;16std::cout << "Concatenation of strings: " << add("Hello", "World") << std::endl;17return 0;18}
Answer:
A move constructor is a special member function that transfers resources from one object to another.
1#include <iostream>2#include <string>34class Resource {5public:6std::string data;78Resource(const std::string& d) : data(d) {9std::cout << "Resource created: " << data << std::endl;10}1112// Move constructor13Resource(Resource&& other) noexcept : data(std::move(other.data)) {14std::cout << "Resource moved: " << data << std::endl;15}16};1718int main() {19Resource original("Data");20Resource moved = std::move(original); // Move constructor is called2122return 0;23}
Answer:
A namespace is a declarative region that provides a scope to the identifiers (names of types, functions, variables) inside it.
1#include <iostream>23namespace Math {4int add(int a, int b) {5return a + b;6}7}89int main() {10std::cout << "Sum: " << Math::add(3, 4) << std::endl; // Outputs: Sum: 711return 0;12}
Answer:
A mutex (mutual exclusion) is a synchronization primitive used to protect shared data from being simultaneously accessed by multiple threads.
1#include <iostream>2#include <thread>3#include <mutex>45std::mutex mtx;6int counter = 0;78void increment() {9std::lock_guard<std::mutex> lock(mtx);10++counter;11}1213int main() {14std::thread t1(increment);15std::thread t2(increment);1617t1.join();18t2.join();1920std::cout << "Counter: " << counter << std::endl; // Outputs: Counter: 221return 0;22}
Answer:
A smart pointer is an object that manages another object, providing automatic memory management.
1#include <iostream>2#include <memory>34int main() {5std::shared_ptr<int> sharedPtr = std::make_shared<int>(10);6std::cout << "Shared ptr count: " << sharedPtr.use_count() << std::endl; // Outputs: 178{9std::shared_ptr<int> anotherSharedPtr = sharedPtr;10std::cout << "Shared ptr count inside block: " << sharedPtr.use_count() << std::endl; // Outputs: 211}1213std::cout << "Shared ptr count after block: " << sharedPtr.use_count() << std::endl; // Outputs: 11415return 0;16}
Answer:
A function pointer is a variable that stores the address of a function.
1#include <iostream>23void greet() {4std::cout << "Hello, World!" << std::endl;5}67int main() {8void (*funcPtr)() = &greet; // Function pointer9funcPtr(); // Calls the function1011return 0;12}
std::vector and std::deque?Answer:
std::vector: Provides fast random access but slower insertions/deletions at the front.