Advanced Topics & Design Patterns Interview Questions - C++ Programming
Last Updated :
08 Aug, 2025
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 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
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.)
2. 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.
3. 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.
4. 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.
5. 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 threadsstd::mutex
, std::lock_guard
: Synchronizationstd::condition_variable
: Thread coordinationstd::atomic
: Atomic operationsstd::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.
6. 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.
7. 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.
9. 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
10. What is an Overflow Error?
Overflow Error occurs when the number is too large for the data type to handle. In simple terms, it is a type of error that is valid for the defined but exceeds used the defined range where it should coincide/lie.
For example, the range of int data type is –2,147,483,648 to 2,147,483,647 and if we declare a variable of size 2,247,483,648 it will generate a overflow error.
11. 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
12. Define inline function. Can we have a recursive inline function in C++?
An inline function is a form of request not an order to a compiler which results in the inlining of our function to the main function body. An inline function can become overhead if the execution time of the function is less than the switching time from the caller function to called function. To make a function inline use the keyword inline before and define the function before any calls are made to the function.
Inline Function ExplanationSyntax:
inline data_type function_name(){
Body;
}
The answer is No; It cannot be recursive.
An inline function cannot be recursive because in the case of an inline function the code is merely placed into the position from where it is called and does not maintain a piece of information on the stack which is necessary for recursion.
Plus, if you write an inline keyword in front of a recursive function, the compiler will automatically ignore it because the inline is only taken as a suggestion by the compiler.
13. 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.
14. 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. |
15. What is 'this' pointer in C++?
this pointer enables every object to have access to its own address through an essential pointer. All member functions take this pointer as an implicit argument. this pointer may be used to refer to the calling object within a member function.
- this pointer is used to pass an object as a parameter to another method.
- Each object gets its own copy of the data member.
- this pointer is used to declare indexers.
Similar Reads
Master C++ Programming: A Complete Guide Welcome back, learners! Kickstart your career with C++ Master programming. Conquer C++ Programming: From Zero to Hero with GeeksforGeeks Master C++ Programming Course. C++ an enhancement of C language is a super scalable language, allowing developers to have a lot of control over how their applicati
6 min read
Persistent Pune Interview Questions Round 1: F2F. Questions Asked: 1. What is encapsulation and data abstraction? 2. Create a class implementing Data - Abstraction, and Encapsulation. 3. Use char * in your class. 4. Create the instance of your class. 5. Is the memory allocated to the class when the object is created? (Class_name <n
1 min read
C++ Interview Questions and Answers (2025) C++ - the must-known and all-time favourite programming language of coders. It is still relevant as it was in the mid-80s. As a general-purpose and object-oriented programming language is extensively employed mostly every time during coding. As a result, some job roles demand individuals be fluent i
15+ min read
C++ OOPs Quizzes Object-Oriented Programming (OOP) in C++ is a programming paradigm based on the concepts like classes, objects, inheritance, polymorphism, and encapsulation. This programming technique allows us to efficient and scalable C++ applications, so, the proper knowledge of these concepts is required to cre
3 min read
Modern C++ Design Patterns Tutorial Design patterns in C++ help developers create maintainable, flexible, and understandable code. They encapsulate the expertise and experience of seasoned software architects and developers, making it easier for newer programmers to follow established best practices. What are C++ Design Patterns?A des
7 min read
JP Morgan Interview Questions and Answers for Technical Profiles JP Morgan, a big player in finance worldwide, is well-known for being very careful when choosing new employees, especially for technical jobs. To help you do well in your upcoming technical interview at JPMorgan, we've put together a detailed list of questions that are often asked, along with their
10 min read