C++ has evolved significantly with modern standards (C++11, 14, 17, 20), introducing powerful features like move semantics, concurrency, smart pointers and design patterns. Interviewers often assess not only coding skills but also a candidate’s design thinking, performance awareness and fluency in modern C++ idioms.
1. What does the Scope Resolution operator do?
A scope resolution operator is denoted by a '::' symbol. Just like its name this operator resolves the barrier of scope in a program. A scope resolution operator is used to reference a member function or a global variable out of their scope furthermore to which it can also access the concealed variable or function in a program.
Scope Resolution is used for numerous amounts of tasks:
- To access a global variable when there is a local variable with the same name
- To define the function outside the class
- In case of multiple inheritances
- For namespace
2. Define inline function. Can we have a recursive inline function in C++?
An inline function suggests to the compiler that function calls may be replaced with the function body to reduce overhead. Recursive functions can technically be marked inline, but in practice, the compiler will inline only a limited number of calls (if any). For deep recursion, inlining is not practical.
So yes, you can declare a recursive function inline, but compilers usually ignore inlining in such cases.
Inline Function Explanation3.What is the main use of the keyword “Volatile”?
Just like its name, things can change suddenly and unexpectantly; So it is used to inform the compiler that the value may change anytime. Also, the volatile keyword prevents the compiler from performing optimization on the code. It was intended to be used when interfacing with memory-mapped hardware, signal handlers and machine code instruction.
Here, b takes ownership of the internal buffer of a, avoiding deep copy.
Benefits:
- Reduces unnecessary memory allocations and copies
- Speeds up object transfers, especially in return statements or containers
Best Use Cases:
- Classes that manage resources (like dynamic memory, file handles)
- Large containers (vector, map, etc.)
4. What is 'this' pointer in C++?
this" pointer is an implicit pointer available in all non-static member functions of a class. It points to the object that invoked the member function, allowing access to that object’s members.
It's uses:
- To return the current object (chaining methods)
- To pass the current object to another function
- To disambiguate member names from local variables
5. What is the difference between shallow copy and deep copy?
Following are the primary differences between the shallow copy VS deep copy:
Shallow Copy | Deep Copy |
---|
In Shallow copy, a copy of the original object is stored and only the reference address is finally copied. In simple terms, Shallow copy duplicates as little as possible | In Deep copy, the copy of the original object and the repetitive copies both are stored. In simple terms, Deep copy duplicates everything |
A shallow copy of a collection is a copy of the collection structure, not the elements. With a shallow copy, two collections now share individual elements. | A deep copy of a collection is two collections with all of the elements in the original collection duplicated. |
A shallow copy is faster | Deep copy is comparatively slower. |
6. What is an Overflow Error?
An overflow occurs when a calculation produces a result outside the range representable by a data type. In C++, signed integer overflow leads to undefined behavior, while unsigned integer overflow wraps around modulo the maximum value.
Example:
int x = INT_MAX;
x = x + 1; // signed overflow → undefined behavior
unsigned int y = UINT_MAX;
y = y + 1; // wraps around to 0
7. What is Move Semantics in C++? How do rvalue references enable it?
Move semantics allow the resources of a temporary (rvalue) object to be transferred (moved) rather than copied, leading to better performance, especially for large objects like containers or strings. Introduced in C++11, move semantics are enabled through rvalue references (T&&), which bind to temporaries.
Example:
string a = "Hello";
string b = std::move(a); // 'a' is moved, not copied
8. What is Perfect Forwarding in C++ and how is it achieved?
Perfect forwarding is a technique to pass arguments to another function without losing their value category (lvalue or rvalue). It's essential in generic programming to write functions that forward arguments efficiently.
Achieved using:
- Universal references (T&& when used in templates)
- std::forward<T>(arg)
Example:
C++
template<typename T>
void wrapper(T&& arg) {
process(std::forward<T>(arg)); // preserves value category
}
This ensures:
- If arg is an lvalue, it remains an lvalue
- If it's an rvalue, it is moved
Use Case: Constructors in wrapper classes, factory functions, etc.
9. Explain lambda expressions and capture modes in C++.
A lambda expression is an anonymous function that can capture variables from its enclosing scope. It's a concise way to write small functions, especially for STL algorithms or callbacks.
Syntax:
[ capture ] (parameters) -> return_type { body }
Capture Modes:
- [=]: capture all by value
- [&]: capture all by reference
- [x]: capture only x by value
- [&x]: capture only x by reference
- [=, &y]: capture all by value, except y by reference
Example:
C++
#include <bits/stdc++.h>
using namespace std;
int main()
{
int a = 10;
auto f = [=]() { return a + 5; };
cout << f(); // prints 15
return 0;
}
Closures are the underlying objects generated from lambdas that store captured variables. Lambdas simplify code in loops, sorting, threading and event handling.
10. Explain Smart Pointers in C++. How do unique_ptr
, shared_ptr
and weak_ptr
differ?
Smart pointers are template classes in <memory>
that automate memory management and prevent leaks by destroying objects when they go out of scope.
Types:
- unique_ptr<T>: Exclusive ownership, not copyable.
- shared_ptr<T>: Shared ownership via reference counting.
- weak_ptr<T>: Observes
shared_ptr
without affecting the count (avoids cyclic references).
Example:
unique_ptr<int> up = make_unique<int>(10);
shared_ptr<int> sp = make_shared<int>(20);
Best Practices:
- Use
unique_ptr
by default - Use
shared_ptr
only when ownership must be shared - Use
weak_ptr
to break cycles in graphs, trees, etc.
Smart pointers ensure exception-safe and clean RAII-based memory management.
11. What are the major multithreading features introduced in C++11 and later?
Modern C++ (from C++11) provides a full-fledged standard threading library with:
Key Features:
- std::thread: Create and run threads
- std::mutex, std::lock_guard: Synchronization
- std::condition_variable: Thread coordination
- std::atomic: Atomic operations
- std::async, std::future: Async execution and result retrieval
Example:
C++
#include <bits/stdc++.h>
using namespace std;
void task() { cout << "Running in thread\n"; }
int main() {
thread t(task);
t.join();
}
These tools help in building concurrent and parallel programs that are safe and portable, avoiding race conditions and deadlocks.
12. Explain the Singleton Design Pattern with an example in C++.
The Singleton Pattern ensures that only one instance of a class is created throughout the program and it provides a global point of access to that instance.
Example:
C++
class Singleton {
private:
static Singleton* instance;
Singleton() {}
public:
static Singleton* getInstance() {
if (!instance)
instance = new Singleton();
return instance;
}
};
Singleton* Singleton::instance = nullptr;
Use Cases:
- Logger
- Configuration manager
- Resource pools
Caution: Must be made thread-safe in multithreaded environments.
13. What is the Observer Design Pattern? How is it implemented in C++?
The Observer Pattern defines a one-to-many dependency so that when one object (subject) changes, all dependent objects (observers) are notified.
Real-world Example: GUI frameworks where clicking a button updates multiple widgets.
Components:
- Subject: Maintains list of observers
- Observer: Interface for update()
Example Sketch:
C++
class Observer {
public:
virtual void update() = 0;
};
class Subject {
vector<Observer*> observers;
public:
void attach(Observer* obs) { observers.push_back(obs); }
void notify() {
for (auto o : observers) o->update();
}
};
This pattern promotes loose coupling and event-driven design.
Template Metaprogramming (TMP) is a technique where templates are used to compute values at compile time, enabling optimization and static checks.
Example Factorial at compile time:
C++
template<int N>
struct Factorial {
static const int value = N * Factorial<N-1>::value;
};
template<>
struct Factorial<0> {
static const int value = 1;
};
// Factorial<5>::value == 120 (computed at compile time)
Use Cases:
- Compile-time constants
- Type traits
- Static assertions and checks
- Expression templates in numeric libraries
TMP makes C++ powerful for low-level systems and high-performance code.
15. How do you use C++20 concepts or features to write cleaner code?
C++20 introduces concepts, ranges, coroutines and more, enhancing code expressiveness and safety.
Example Concepts:
C++
template<typename T>
concept Integral = std::is_integral_v<T>;
template<Integral T>
T add(T a, T b) {
return a + b;
}
Benefits:
- Early error checking (at compile time)
- Better template diagnostics
- More readable and maintainable code
Other features include:
ranges::views::filter
and transform
co_await
, co_yield
for asynchronous programming