Practice
Resources
Contests
Online IDE
New
Free Mock
Events New Scaler
Practice
Improve your coding skills with our resources
Contests
Compete in popular contests with top coders
logo
Events
Attend free live masterclass hosted by top tech professionals
New
Scaler
Explore Offerings by SCALER
exit-intent-icon

Download Interview guide PDF

Before you leave, take this C++ Interview Questions interview guide with you.
Get a Free Personalized Career Roadmap
Answer 4 simple questions about you and get a path to a lucrative career
expand-icon Expand in New Tab
/ Interview Guides / C++ Interview Questions

C++ Interview Questions

Last Updated: Feb 23, 2026

Download PDF


Your requested download is ready!
Click here to download.
Learn via Video Course
Data Structures in C++ Course
By Aditya Jain
Popular
Certificate included
About the Speaker
What will you Learn?
Register Now
Learn via Video Course
Data Structures in C++ Course
By Aditya Jain
Popular
ai interview ai interview

C++ is a powerful and all-purpose programming tool developed by Bjarne Stroustrup at Bell Labs. This language is an extension of C and is by far one of the fastest object-oriented programming languages. C++ is super popular because of its high speed and compatibility.

It is widely used in the development of games and servers while some of the real-world applications of C++ are as follows

  • Operating systems
  • GUI based applications
  • Distributed systems
  • Database software
  • Banking applications
  • Advanced computations and graphics
  • Embedded systems

So, today, well understand the different C++ questions asked in an interview at a basic, intermediate and advanced level.

C++ Interview Questions For Freshers

1. What do you mean by abstraction in C++?

Abstraction is the process of showing the essential details to the user and hiding the details which we don’t want to show to the user or hiding the details which are irrelevant to a particular user.

Create a free personalised study plan Create a FREE custom study plan
Get into your dream companies with expert guidance
Get into your dream companies with expert..
Real-Life Problems
Prep for Target Roles
Custom Plan Duration
Flexible Plans

2. What are the different data types present in C++?

The 4 data types in C++ are given below:

  • Primitive Datatype(basic datatype). Example- char, short, int, float, long, double, bool, etc.
  • Derived datatype. Example- array, pointer, etc.
  • Enumeration. Example- enum
  • User-defined data types. Example- structure, class, etc.

3. Explain inheritance

Inheritance is the process of creating new classes, called derived classes, from existing classes. These existing classes are called base classes. The derived classes inherit all the capabilities of the base class but can add new features and refinements of their own.

Example-

Inheritance in C++

Class Bus, Class Car, and Class Truck inherit the properties of Class Vehicle.

The most important thing about inheritance is that it permits code reusability.

You can download a PDF version of Cpp Interview Questions.

Download PDF


Your requested download is ready!
Click here to download.

4. What are the static members and static member functions?

When a variable in a class is declared static, space for it is allocated for the lifetime of the program. No matter how many objects of that class have been created, there is only one copy of the static member. So same static member can be accessed by all the objects of that class.

A static member function can be called even if no objects of the class exist and the static function are accessed using only the class name and the scope resolution operator ::

5. What are destructors in C++?

A constructor is automatically called when an object is first created. Similarly when an object is destroyed a function called destructor automatically gets called. A destructor has the same name as the constructor (which is the same as the class name) but is preceded by a tilde.

Example:

class A{
 private:
  int val;
 public:
  A(int x){           
   val=x;
  }
  A(){                
  }
  ~A(){                  //destructor
  }
}
int main(){
 A a(3);     
 return 0;
}

Learn via our Video Courses

6. What is an abstract class and when do you use it?

A class is called an abstract class whose objects can never be created. Such a class exists as a parent for the derived classes. We can make a class abstract by placing a pure virtual function in the class.

7. What do you mean by call by value and call by reference?

In call by value method, we pass a copy of the parameter is passed to the functions. For these copied values a new memory is assigned and changes made to these values do not reflect the variable in the main function.

In call by reference method, we pass the address of the variable and the address is used to access the actual argument used in the function call. So changes made in the parameter alter the passing argument.

Advance your career with   Mock Assessments Refine your coding skills with Mock Assessments
Real-world coding challenges for top company interviews
Real-world coding challenges for top companies
Real-Life Problems
Detailed reports

8. Is deconstructor overloading possible? If yes then explain and if no then why?

No destructor overloading is not possible. Destructors take no arguments, so there’s only one way to destroy an object. That’s the reason destructor overloading is not possible.

9. What is a reference in C++?

A reference is like a pointer. It is another name of an already existing variable. Once a reference name is initialized with a variable, that variable can be accessed by the variable name or reference name both.

For example-

int x=10;
int &ref=x;           //reference variable

If we change the value of ref it will be reflected in x. Once a reference variable is initialized it cannot refer to any other variable. We can declare an array of pointers but an array of references is not possible.

10. Define inline function

If a function is inline, the compiler places a copy of the code of that function at each point where the function is called at compile time. One of the important advantages of using an inline function is that it eliminates the function calling overhead of a traditional function.

11. What are the C++ access specifiers?

In C++ there are the following access specifiers:

Public: All data members and member functions are accessible outside the class.

Protected: All data members and member functions are accessible inside the class and to the derived class.

Private: All data members and member functions are not accessible outside the class.

12. What do you know about friend class and friend function?

A friend class can access private, protected, and public members of other classes in which it is declared as friends.

Like friend class, friend function can also access private, protected, and public members. But, Friend functions are not member functions.

For example -

class A{
 private:
  int data_a;
 public:
  A(int x){
   data_a=x;
  }
  friend int fun(A, B);
}
class B{
 private:
  int data_b;
 public:
  A(int x){
   data_b=x;
  }
  friend int fun(A, B);
}
int fun(A a, B b){
 return a.data_a+b.data_b;
}
int main(){
 A a(10);
 B b(20);
 cout<<fun(a,b)<<endl;
 return 0;
}

Here we can access the private data of class A and class B.

13. Compare compile time polymorphism and Runtime polymorphism

The main difference between compile-time and runtime polymorphism is provided below:

Compile-time polymorphism Run time polymorphism
In this method, we would come to know at compile time which method will be called. And the call is resolved by the compiler. In this method, we come to know at run time which method will be called. The call is not resolved by the compiler.
It provides fast execution because it is known at the compile time. It provides slow execution compared to compile-time polymorphism because it is known at the run time.
It is achieved by function overloading and operator overloading. It can be achieved by virtual functions and pointers.

Example -

int add(int a, int b){
      return a+b;
}
int add(int a, int b, int c){
      return a+b+c;
}

int main(){
    cout<<add(2,3)<<endl;
    cout<<add(2,3,4)<<endl;


     return 0;
}

 

Example -

class A{
     public:
          virtual void fun(){
               cout<<"base ";
          }
};
class B: public A{
     public:
          void fun(){
               cout<<"derived ";
          }
};
int main(){
     A *a=new B;
     a->fun();

     return 0;
}

14. Tell me about virtual function

Virtual function is a member function in the base class that you redefine in a derived class. A virtual function is declared using the virtual keyword. When the function is made virtual, C++ determines which function is to be invoked at the runtime based on the type of the object pointed by the base class pointer.

15. Explain constructor in C++

The constructor is a member function that is executed automatically whenever an object is created. Constructors have the same name as the class of which they are members so that compiler knows that the member function is a constructor. And no return type is used for constructors.

Example:

class A{
 private:
  int val;
 public:
  A(int x){             //one argument constructor
   val=x;
  }
  A(){                    //zero argument constructor
  }
}
int main(){
 A a(3);     

 return 0;
}

16. What is polymorphism in C++?

Polymorphism in simple means having many forms. Its behavior is different in different situations. And this occurs when we have multiple classes that are related to each other by inheritance.

For example, think of a base class called a car that has a method called car brand(). Derived classes of cars could be Mercedes, BMW, Audi - And they also have their own implementation of a cars

The two types of polymorphism in c++ are:

  • Compile Time Polymorphism
  • Runtime Polymorphism
Polymorphism in C++

Here is a Free C++ course with certification that can help clear your basics of C++ programming.

17. What is operator overloading?

Operator Overloading is a very essential element to perform the operations on user-defined data types. By operator overloading we can modify the default meaning to the operators like +, -, *, /, <=, etc. 

For example -

The following code is for adding two complex number using operator overloading-

class complex{
private:
 float r, i;
public:
 complex(float r, float i){
  this->r=r;
  this->i=i;
 }
 complex(){}
 void displaydata(){
  cout<<”real part = “<<r<<endl;
  cout<<”imaginary part = “<<i<<endl;
 }
 complex operator+(complex c){
  return complex(r+c.r, i+c.i);
 }
};
int main(){
complex a(2,3);
complex b(3,4);
complex c=a+b;
c.displaydata();
return 0;
}

18. What is the difference between struct and class?

In C++ a structure is the same as a class except for a few differences like security. The difference between struct and class are given below:

Structure Class
Members of the structure are public by default. Members of the class are private by default.
When deriving a struct from a class/struct, default access specifiers for base class/struct are public. When deriving a class, default access specifiers are private.

19. What are class and object in C++?

A class is a user-defined data type that has data members and member functions. Data members are the data variables and member functions are the functions that are used to perform operations on these variables.

An object is an instance of a class. Since a class is a user-defined data type so an object can also be called a variable of that data type.

A class is defined as-

class A{
private:
 int data;
public:
 void fun(){

 }
};
Class and Object in C++

For example, the following is a class car that can have properties like name, color, etc. and they can have methods like speed().

20. What is the difference between C and C++?

The main difference between C and C++ are provided in the table below:

C C++
C is a procedure-oriented programming language. C++ is an object-oriented programming language.
C does not support data hiding. Data is hidden by encapsulation to ensure that data structures and operators are used as intended.
C is a subset of C++ C++ is a superset of C.
Function and operator overloading are not supported in C Function and operator overloading is supported in C++
Namespace features are not present in C Namespace is used by C++, which avoids name collisions.
Functions can not be defined inside structures. Functions can be defined inside structures.
calloc() and malloc() functions are used for memory allocation and free() function is used for memory deallocation. new operator is used for memory allocation and deletes operator is used for memory deallocation.

C++ Interview Questions For Experienced

1. What is a copy constructor?

A copy constructor is a member function that initializes an object using another object of the same class.

Example-

class A{
int x,y;
A(int x, int y){
 this->x=x;
 this->y=y;
}

};
int main(){
A a1(2,3);
A a2=a1;     //default copy constructor is called
return 0;
}

We can define our copy constructor. If we don’t define a copy constructor then the default copy constructor is called.

2. What is the difference between shallow copy and deep copy?

The difference between shallow copy and a deep copy is given below:

Shallow Copy Deep Copy
Shallow copy stores the references of objects to the original memory address. Deep copy makes a new and separate copy of an entire object with its unique memory address.
Shallow copy is faster. Deep copy is comparatively slower.
Shallow copy reflects changes made to the new/copied object in the original object. Deep copy doesn’t reflect changes made to the new/copied object in the original object

3. What is the difference between virtual functions and pure virtual functions?

A virtual function is a member function in the base class that you redefine in a derived class. It is declared using the virtual keyword.

Example-

class base{
public:
 virtual void fun(){

 }
};

A pure virtual function is a function that has no implementation and is declared by assigning 0. It has no body.

Example-

class base{
public:
 virtual void fun()=0;
};

Here, = sign has got nothing to do with the assignment, and value 0 is not assigned to anything. It is used to simply tell the compiler that a function will be pure and it will not have anybody.

4. If class D is derived from a base class B. When creating an object of type D in what order would the constructors of these classes get called?

The derived class has two parts, a base part, and a derived part.  When C++ constructs derived objects, it does so in phases. First, the most-base class(at the top of the inheritance tree) is constructed. Then each child class is constructed in order until the most-child class is constructed last. 
So the first Constructor of class B will be called and then the constructor of class D will be called.

During the destruction exactly reverse order is followed. That is destructor starts at the most-derived class and works its way down to base class.
So the first destructor of class D will be called and then the destructor of class B will be called.

5. Can we call a virtual function from a constructor?

Yes, we can call a virtual function from a constructor. But the behavior is a little different in this case. When a virtual function is called, the virtual call is resolved at runtime. It is always the member function of the current class that gets called. That is the virtual machine doesn’t work within the constructor.

For example-

class base{
 private:
  int value;
 public:
  base(int x){
   value=x;
  }
  virtual void fun(){
   
  }
}

class derived{
 private:
  int a;
 public:
  derived(int x, int y):base(x){
   base *b;
   b=this;
   b->fun();      //calls derived::fun()
  }
  void fun(){
   cout<<”fun inside derived class”<<endl;
  }
}

6. What are void pointers?

A void pointer is a pointer which is having no datatype associated with it. It can hold addresses of any type.

For example-

void *ptr; 
char *str;
p=str;                // no error 
str=p;                // error because of type mismatch

We can assign a pointer of any type to a void pointer but the reverse is not true unless you typecast it as

str=(char*) ptr;

7. What is this pointer in C++?

The member functions of every object have a pointer named this, which points to the object itself. The value of this is set to the address of the object for which it is called. It can be used to access the data in the object it points to.

Example

class A{
 private:
  int value;
 public:
  void setvalue(int x){
   this->value=x; 
  }
};

int main(){
 A a;
 a.setvalue(5);
 return 0;
}

8. How do you allocate and deallocate memory in C++?

The new operator is used for memory allocation and deletes operator is used for memory deallocation in C++.

For example-

int value=new int;  		//allocates memory for storing 1 integer
delete value;          		// deallocates memory taken by value

int *arr=new int[10];    	//allocates memory for storing 10 int
delete []arr;              	// deallocates memory occupied by arr

Additional Resources

Practice Coding

C++ MCQ

C++ Tutorials

C Interview Questions

Difference Between C and C++

Difference Between C++ and Java

Online C++ Compiler

Features of C++

Advanced C++ Interview Questions

1. What are templates in C++? Explain function templates vs class templates.

Templates allow writing generic code that works with multiple data types.

Function template example:

template<typename T>
T maximum(T a, T b) {
   return (a > b) ? a : b;
}
Class template example:
template<typename T>
class Stack {
private:
   std::vector<T> data;
public:
   void push(T value) {
       data.push_back(value);
   }
};

Templates support compile-time polymorphism. The compiler generates code for each used type.

Template specialization allows custom behavior for specific types.

Variadic templates (C++11) allow functions with variable number of template parameters.

Concepts (C++20) allow constraining template parameters to specific requirements.

Common issues: Templates can increase compile time and cause code bloat. Error messages can be complex.

In advanced c++ interview questions, templates are often discussed in the context of generic programming and compile-time optimization.

2. What is RAII in C++? Why is it considered a best practice?

RAII stands for Resource Acquisition Is Initialization. It means that resource allocation happens in the constructor and resource release happens in the destructor.

The lifetime of the resource is tied to the lifetime of the object.

Example with file handling:

#include <fstream>
void readFile() {
   std::ifstream file("data.txt");
   // File automatically closed when file goes out of scope
}
Example with lock_guard:
#include <mutex>

std::mutex m;

void func() {
   std::lock_guard<std::mutex> lock(m);
   // Mutex automatically released
}

RAII makes programs exception-safe. Even if an exception is thrown, destructors run and resources are released.

In C-style programming, resources must be manually freed, which increases risk of leaks.

In interviews, you should remember to state that RAII c++ is a fundamental principle that enables safe memory and resource management.
 

3. What are lambda expressions in C++? Explain capture clauses.

Lambda expressions are anonymous function objects introduced in C++11. They allow inline function definitions.

Basic syntax:

[capture](parameters) -> return_type { body }
Example:
auto add = [](int a, int b) {
   return a + b;
};

Capture clause controls how external variables are accessed.

Capture by value:

int x = 10;
auto f = [x]() { return x; };
Capture by reference:
auto f = [&x]() { x++; };


By default, value-captured variables cannot be modified. To allow modification, use mutable:

auto f = [x]() mutable { x++; };
Common usage with STL:
#include <algorithm>
std::vector<int> v = {3,1,2};
std::sort(v.begin(), v.end(), [](int a, int b) {
   return a < b;
});

Generic lambdas were introduced in C++14 using auto parameters. Template lambdas are supported in C++20.

In lambda c++ interview questions, mention capture types and STL integration.

 

4. What are move semantics and rvalue references in C++11? Why are they important?

Move semantics allow resources to be transferred from temporary objects instead of copying them. This improves performance, especially for objects that manage dynamic memory.

An rvalue reference is declared using T&&. It binds to temporary objects.

Example:

std::string s1 = "Hello";
std::string s2 = std::move(s1);
std::move converts s1 into an rvalue reference, allowing its internal buffer to be moved instead of copied.

Difference between lvalue and rvalue:

An lvalue has a name and persists beyond the expression.
An rvalue is temporary and does not persist.

Move constructor example:

class Buffer {
public:
   Buffer(Buffer&& other) noexcept {
       data = other.data;
       other.data = nullptr;
   }
};

 

Rule of Five: If a class defines a destructor, copy constructor, copy assignment operator, it should also define move constructor and move assignment operator.

Before move semantics: vector<string> reallocation required copying each string.

After move semantics: vector<string> moves strings instead of copying, reducing overhead.

In move semantics interview, discussions majorly emphasize performance improvement and resource transfer.


 

5. What are smart pointers in C++? Explain unique_ptr, shared_ptr, and weak_ptr.

Smart pointers are wrapper classes that manage dynamically allocated memory automatically using RAII. They ensure that memory is released when the pointer goes out of scope. In modern C++, raw pointers with manual new/delete are discouraged because they can easily cause memory leaks.

unique_ptr represents exclusive ownership. Only one unique_ptr can own a resource at a time. It cannot be copied but can be moved.

Example:

#include <memory>
std::unique_ptr<int> ptr1 = std::make_unique<int>(10);
// std::unique_ptr<int> ptr2 = ptr1;  // Error: cannot copy
std::unique_ptr<int> ptr2 = std::move(ptr1);  // Ownership transferred

shared_ptr represents shared ownership. Multiple shared_ptr objects can own the same resource. It uses reference counting. When the reference count becomes zero, the memory is released.

Example:

#include <memory>
std::shared_ptr<int> p1 = std::make_shared<int>(20);
std::shared_ptr<int> p2 = p1;  // Reference count increases

weak_ptr is a non-owning observer of a shared_ptr. It does not increase the reference count. It is used to break circular references.

Example:

std::shared_ptr<int> sp = std::make_shared<int>(30);
std::weak_ptr<int> wp = sp;

If two shared_ptr objects reference each other, memory will never be freed. weak_ptr solves this issue.

In interviews, you should explain that smart pointers implement RAII c++, and they prevent memory leaks compared to raw pointers.


 

Embedded C++ Interview Questions

1. How does memory-mapped I/O work? How do you access hardware registers in C++?

In memory-mapped I/O, hardware registers are mapped to specific memory addresses. Instead of using special CPU instructions, you read or write to a memory address to control hardware.

Example:

volatile uint8_t* const GPIO_PORT =
   reinterpret_cast<volatile uint8_t*>(0x25)

*GPIO_PORT |= (1 << 3);

Here:
0x25 is the address of a hardware register.
volatile ensures every access reads or writes directly to hardware.
const ensures the pointer address itself cannot change.

Bit manipulation is commonly used:

Set a bit:

*GPIO_PORT |= (1 << 3);
Clear a bit:
*GPIO_PORT &= ~(1 << 3);
Toggle a bit:
*GPIO_PORT ^= (1 << 3);
Read a bit:
bool isSet = (*GPIO_PORT & (1 << 3));

In memory mapped IO c++ interview questions, explain why volatile and pointer-to-const-address patterns are necessary to prevent incorrect optimization.

2. What is endianness? How do you handle byte-order issues in embedded C++?

Endianness refers to the order in which bytes are stored in memory for multi-byte data types.

Little-endian stores the least significant byte first. Most modern processors such as x86 and ARM use little-endian.

Big-endian stores the most significant byte first. Some network protocols and older architectures use big-endian.

Example value: 0x12345678

Little-endian memory order: 78 56 34 12

Big-endian memory order: 12 34 56 78

To swap byte order:

uint32_t swap32(uint32_t x) {
   return ((x >> 24) & 0xff) |
          ((x << 8) & 0xff0000) |
          ((x >> 8) & 0xff00) |
          ((x << 24) & 0xff000000);
}

For network communication, functions like htonl (host to network long) and ntohl (network to host long) are used.

Compile-time detection example:

#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__

// little-endian code

#endif

In embedded systems, endianness matters when:

  • Communicating over network protocols
  • Interfacing with different processors
  • Reading binary file formats

In interviews, you should explain byte order differences and practical handling strategies. 

3. What is an RTOS? How does it differ from bare-metal programming in embedded C++?

An RTOS (Real-Time Operating System) is an operating system designed for deterministic task scheduling. It ensures tasks execute within strict timing constraints.

An RTOS provides:

  • Task management
  • Priority-based scheduling
  • Inter-task communication (queues, semaphores, mutexes)
  • Resource management

Example systems include FreeRTOS and ThreadX.
Bare-metal programming means writing firmware without an operating system. The program typically runs inside a superloop:

int main() {
   while (1) {
       readSensors();
       updateOutputs();
   }
}

Difference:

Bare-metal:

  • Simpler and lower overhead.
  • Harder to scale for complex systems.
  • No built-in task scheduling.

RTOS:

  • Supports multitasking.
  • Better for complex systems.
  • Adds scheduling overhead.

Choose bare-metal when the system is simple and timing requirements are straightforward.

Choose RTOS when the system has multiple tasks, strict deadlines, and communication requirements.

During RTOS interview questions, explain deterministic behavior and priority scheduling clearly.



 

4. What are Interrupt Service Routines (ISR)? What constraints apply to C++ code in an ISR?

An Interrupt Service Routine (ISR) is a function that executes automatically in response to a hardware interrupt. Interrupts can come from timers, UART, GPIO, ADC, or other peripherals.

When an interrupt occurs, normal program flow is paused, and the ISR runs immediately.

Example:

void Timer_ISR() {

   flag = 1;

}

Constraints in ISR:

The ISR must be short and fast. Long execution blocks other interrupts.

Avoid dynamic memory allocation. Do not use new or delete.

Avoid blocking calls. No sleep or waiting functions.

Avoid using printf or cout. These are slow and often not interrupt-safe.

Shared variables modified inside an ISR must be declared volatile.

Avoid virtual function calls. Virtual dispatch requires vtable lookup, which adds overhead and unpredictability.

A common pattern is to set a flag inside the ISR and handle heavy processing in the main loop.

Example:

volatile bool dataReady = false;


void ISR_Handler() {
   dataReady = true;
}

int main() {
   while (1) {
       if (dataReady) {
           dataReady = false;
           processData();
       }
   }
}

Remember: In ISR interview questions, the key concept is determinism and minimal execution time.

5. What is the volatile keyword in C++? Why is it critical in embedded systems?

The volatile keyword tells the compiler that a variable’s value may change at any time outside the program’s control. Because of this, the compiler must not optimize or cache the variable in a CPU register.

In embedded systems, hardware registers, memory-mapped I/O, and variables modified inside an ISR can change unexpectedly.

Without volatile, the compiler may optimize repeated reads into a single cached read. This can cause stale values and incorrect behavior.

Example:

volatile uint32_t* statusReg =
   (volatile uint32_t*)0x40021000;

If the hardware updates the register at address 0x40021000, every read must fetch the latest value from memory. volatile ensures that.

Important clarification: volatile prevents compiler optimization, but it does not guarantee atomicity. It does not prevent race conditions. For thread-safe operations, atomic types or synchronization mechanisms are required.

In volatile keyword c++ interview, clearly explain that volatile is about preventing compiler reordering and caching, not about thread safety.

GFG C++ Interview Questions

1. What is the difference between map and unordered_map in C++? When should you use each?

map is implemented as a balanced binary search tree, typically a red-black tree. It stores keys in sorted order. All operations take O(log n).

unordered_map is implemented as a hash table. It provides average O(1) lookup time but does not maintain order.

map characteristics:

  • Keys are sorted.
  • Supports range queries.
  • Predictable iteration order.

unordered_map characteristics:

  • Faster average lookup.
  • Order is undefined.
  • Worst-case O(n) if many collisions occur.

Use map when you need ordered traversal or operations such as lower_bound and upper_bound.

Use unordered_map when performance is critical and key order does not matter.

You can define custom hash functions in unordered_map for user-defined types.

This distinction is frequently asked in stl interview questions c++ and competitive programming interviews.

2. Explain the four type casts in C++: static_cast, dynamic_cast, const_cast, reinterpret_cast.

C++ provides four explicit type casts for safety and clarity.

static_cast performs compile-time checked conversions. It is used for standard conversions such as int to float or base-to-derived casting without runtime checking.

int x = 10;

double y = static_cast<double>(x);

dynamic_cast performs runtime-checked casting. It is mainly used for safe downcasting in polymorphic classes. If casting fails, it returns nullptr for pointers or throws an exception for references.

Derived* d = dynamic_cast<Derived*>(basePtr);

const_cast adds or removes const qualifiers. It does not change the actual object’s constness.

const int a = 5;

int* b = const_cast<int*>(&a);

reinterpret_cast performs low-level reinterpretation of bits. It is used for pointer-to-integer conversions or unrelated pointer conversions. It is unsafe and should be avoided unless absolutely necessary.

int* p = reinterpret_cast<int*>(0x1234);

C-style casts combine multiple behaviors and are unsafe. Modern C++ recommends using explicit casts for clarity and safety.

This is a common type casting c++ interview topic, so make sure to understand the concept thoroughly!

3. What is the virtual table (vtable) mechanism in C++? How does dynamic dispatch work?

When a class contains virtual functions, the compiler creates a virtual table, also called a vtable. The vtable is an array of function pointers.

Each object of such a class contains a hidden pointer called vptr that points to the vtable.

When a virtual function is called through a base class pointer, the call is resolved at runtime using the vtable.

Execution flow:

object → vptr → vtable → function pointer → actual function

Example:

class Base {
public:
   virtual void show() { }
};

class Derived : public Base {
public:
   void show() override { }
};

If you call show() using a Base pointer pointing to a Derived object, the Derived version is executed.

Dynamic dispatch means function resolution happens at runtime.

Adding a virtual function increases object size because of the hidden vptr.

Constructors cannot be virtual because the object is not fully constructed yet, so dynamic dispatch is not meaningful.

Performance cost of virtual functions is minimal, typically one extra pointer dereference.

This is a common virtual table c++ interview question asked oftentimes.

4. What are iterators in C++? Explain the five iterator categories.

Iterators are generalized pointers used to traverse STL containers. They allow uniform access to container elements.

Basic usage:

for(auto it = v.begin(); it != v.end(); ++it) {
   std::cout << *it;
}

There are five iterator categories.

Input iterator allows reading elements forward only. It supports increment and dereference.

Output iterator allows writing elements forward only.

Forward iterator allows reading and writing forward. It supports multiple passes.

Bidirectional iterator allows forward and backward movement. Containers like list and map use bidirectional iterators.

Random access iterator allows arithmetic operations such as addition, subtraction, and indexing. Containers like vector and deque provide random access iterators.

const_iterator prevents modification of elements.

reverse_iterator allows backward traversal using rbegin() and rend().

Range-based for loop is syntactic sugar over iterators:

for(const auto& val : v) {
   std::cout << val;
}

In iterators c++ interview questions, you should clearly explain iterator categories and which containers support which type.

5. What are STL containers in C++? Compare vector, list, deque, map, and unordered_map.

STL containers are template-based data structures provided by the Standard Template Library. They are divided into sequential containers and associative containers.

Sequential containers store elements in linear order.

vector is a dynamic array. It provides O(1) random access using index. Insertions at the end are amortized O(1). Insertions in the middle are O(n). Internally, it stores elements in contiguous memory. When capacity is exceeded, it reallocates and copies elements. The reserve() function pre-allocates memory to avoid repeated reallocations.

list is a doubly-linked list. It provides O(1) insertion and deletion anywhere if you have an iterator. However, it does not support random access. Accessing the nth element takes O(n).

deque is a double-ended queue. It supports fast insertion and deletion at both ends. It provides O(1) random access but is not guaranteed to store elements contiguously like vector.

Associative containers store key-based elements.

map is an ordered key-value container implemented using a red-black tree. All operations such as insert, delete, and search take O(log n). Keys are always sorted.

unordered_map is implemented using a hash table. Average-case operations are O(1), but worst-case complexity is O(n) if many hash collisions occur. Keys are not stored in sorted order.

Iterator invalidation rules:

  • For vector, inserting or resizing may invalidate all iterators.
  • For list, inserting or deleting does not invalidate other iterators.
  • For unordered_map, rehashing invalidates iterators.
  • Use vector when you need fast indexing.
  • Use list when frequent insertion/deletion in middle is required.
  • Use map when ordered traversal or range queries are needed.
  • Use unordered_map when fast lookup is the priority and order does not matter.

These are common stl interview questions c++ in coding interviews.

Multithreading Interview Questions C++

1. What are atomic operations in C++? When should you use std::atomic vs std::mutex?

std::atomic provides lock-free, thread-safe operations for simple types such as int, bool, and pointers.

Atomic operations are indivisible. No other thread can observe intermediate states.

Example:

std::atomic<int> counter(0);

counter.fetch_add(1);

Common atomic operations:

  • load()
  • store()
  • fetch_add()
  • compare_exchange

Memory ordering options include:

  • memory_order_relaxed
  • memory_order_acquire
  • memory_order_release

At a high level:

  • Acquire ensures reads happen after acquire.
  • Release ensures writes happen before release.

Use std::atomic when:

  • You need a simple counter or flag.
  • You want lightweight synchronization.

Use std::mutex when:

  • Multiple variables must be protected together.
  • Operations are complex.
  • Critical sections contain more than one step.

Atomic is faster but limited in scope. Mutex is more flexible but heavier.

In atomic c++ interview, you should explain that atomic is for simple shared variables, while mutex protects complex critical sections.

2. What is a deadlock? How do you avoid it in C++?

A deadlock occurs when two or more threads wait indefinitely for each other to release resources.

Classic example:

std::mutex m1, m2;
void task1() {
   std::lock_guard<std::mutex> lock1(m1);
   std::lock_guard<std::mutex> lock2(m2);
}
void task2() {
   std::lock_guard<std::mutex> lock2(m2);
   std::lock_guard<std::mutex> lock1(m1);
}
If task1 locks m1 and task2 locks m2, both may wait forever.

Four necessary conditions (Coffman conditions):

  • Mutual exclusion
  • Hold and wait
  • No preemption
  • Circular wait

Prevention strategies:

Always lock mutexes in the same order.

Use std::lock to lock multiple mutexes safely:

std::lock(m1, m2);
Use std::scoped_lock (C++17):
std::scoped_lock lock(m1, m2);

Use try_lock_for with timeouts to avoid indefinite blocking.

In deadlock c++ interview questions, emphasize consistent lock ordering as the most practical solution.

3. What is a race condition? How do you prevent it in C++?

A race condition occurs when two or more threads access shared data at the same time, and at least one thread modifies it. The result becomes unpredictable.

Example of race condition:

int counter = 0;
void increment() {
   counter++;
}

If two threads run increment() simultaneously, the final value may be incorrect.

Prevention methods:

Use mutex to protect critical sections.
Use std::atomic for simple types:
#include <atomic>
std::atomic<int> counter(0);
void increment() {
   counter++;
}

atomic operations are indivisible and thread-safe.

Other prevention techniques:

  • Use immutable data.
  • Use thread-safe containers.
  • Minimize shared state.

Tools like ThreadSanitizer can detect data races at runtime.

In race condition c++ discussions, clearly explain concurrent access plus write equals unpredictability.

4. What is a mutex in C++? Explain std::mutex, std::lock_guard, and std::unique_lock.

A mutex provides mutual exclusion. It ensures that only one thread can access a shared resource at a time.

Basic usage with std::mutex:

std::mutex m;
void criticalSection() {
   m.lock();
   // shared resource access
   m.unlock();
}

Manual lock/unlock is risky because forgetting unlock() can cause deadlocks.

std::lock_guard is an RAII wrapper. It locks the mutex in its constructor and unlocks automatically in its destructor.

void safeSection() {
   std::lock_guard<std::mutex> lock(m);
   // shared resource access
}

This is the safest and simplest way to protect critical sections.

std::unique_lock is more flexible. It allows deferred locking, manual unlock, and timed locking.

std::unique_lock<std::mutex> lock(m, std::defer_lock);
lock.lock();

unique_lock is required when working with condition_variable.

Without mutex (data race):

int counter = 0;
void increment() {
   counter++;
}
With mutex protection:
void increment() {
   std::lock_guard<std::mutex> lock(m);
   counter++;
}

In mutex c++ interview questions, emphasize RAII usage and avoiding manual lock/unlock.

5. How do you create and manage threads in C++? Explain std::thread with join() and detach().

C++11 introduced std::thread for creating and managing threads.

A thread is created by passing a function (or lambda) to std::thread.

Example:

#include <thread>
#include <iostream>
void task() {
   std::cout << "Thread running\n";
}
int main() {
   std::thread t(task);
   t.join();
}

join() blocks the calling thread until the created thread finishes execution.

detach() allows the thread to run independently. After detaching, the thread runs in the background and cannot be joined.

Example using lambda:

std::thread t([]() {
   std::cout << "Hello from lambda\n";
});
t.join();
Passing arguments by reference requires std::ref:
void increment(int& x) { x++; }

int value = 0;
std::thread t(increment, std::ref(value));
t.join();

Important rule: Every std::thread must be either joined or detached before it is destroyed. Otherwise, the program terminates.

You can check if a thread is joinable using joinable().

In std thread interview, you should be able to clearly explain lifecycle management and ownership rules.


 

Top 70+ C# Interview Questions and Answers You Must Prepare in 2026

1. What is composition vs aggregation in C++? How do they differ from inheritance?

Composition and aggregation both represent "has-a" relationships. Inheritance represents an "is-a" relationship.

Inheritance example: A Dog is an Animal.

Composition example: A Car has an Engine. 

If the Car object is destroyed, the Engine is also destroyed. This is a strong relationship.

class Engine {};
class Car {
private:
   Engine engine;  // Composition
};

Aggregation example: A Department has Professors, but Professors can exist independently of the Department.

class Professor {};
class Department {
private:
   Professor* professor;  // Aggregation
};

In aggregation, the lifetime of the contained object is independent.

Difference summary:

  • Inheritance: Represents is-a relationship. Creates tight coupling.
  • Composition: Strong has-a relationship. Contained object’s lifetime depends on owner.
  • Aggregation: Weak has-a relationship. Contained object exists independently.
  • Modern design principle: Favor composition over inheritance. Composition provides more flexibility and reduces dependency issues.

In interviews, clearly explain ownership and object lifetime differences between composition and aggregation.

2. What is the difference between function overloading and function overriding in C++?

Function overloading means having multiple functions with the same name but different parameter lists. It is resolved at compile time and is an example of static polymorphism.

Example:

class Calculator {
public:
   int add(int a, int b) {
       return a + b;
   }

   double add(double a, double b) {
       return a + b;
   }
};

The compiler decides which function to call based on argument types.

Function overriding happens when a derived class provides a new implementation of a base class virtual function. It is resolved at runtime and is an example of dynamic polymorphism.

Example:

class Base {
public:
   virtual void show() {
       std::cout << "Base\n";
   }
};

class Derived : public Base {
public:
   void show() override {
       std::cout << "Derived\n";
   }
};

If a Base pointer points to a Derived object, the Derived version is called.

Key differences:

Overloading:

  • Same function name.
  • Different parameters.
  • Compile-time resolution.

Overriding:

  • Same function signature.
  • Requires virtual keyword.
  • Runtime resolution.

In interviews, clearly mention that overriding requires the virtual keyword in the base class.

3. Why do we need virtual destructors in C++? What happens without one?

When a derived class object is deleted using a base class pointer, the destructor must be virtual to ensure proper cleanup.

Example without virtual destructor:

class Base {
public:
   ~Base() {
       std::cout << "Base destructor\n";
   }
};

class Derived : public Base {
public:
   ~Derived() {
       std::cout << "Derived destructor\n";
   }
};


int main() {
   Base* ptr = new Derived();
   delete ptr;
}
Output:
Only "Base destructor" is called.

The Derived destructor is not executed. This can cause memory leaks if the derived class allocates resources.

Correct approach:

class Base {
public:
   virtual ~Base() {
       std::cout << "Base destructor\n";
   }
};

Now, when deleting through a base pointer, both destructors execute in the correct order.

If a class has any virtual function, it should also have a virtual destructor. This ensures proper polymorphic cleanup.

The virtual destructor c++ question is frequently asked to test understanding of runtime polymorphism and memory safety.

4. What is the diamond problem in C++? How does virtual inheritance solve it?

The diamond problem occurs in multiple inheritance when two classes inherit from the same base class, and another class inherits from both of them.

Structure:

       A

      / \

     B   C

      \ /

       D

If B and C both inherit from A, and D inherits from both B and C, then D contains two copies of A. This creates ambiguity.

Example without virtual inheritance:

class A {

public:

   int value;

};

class B : public A {};

class C : public A {};

class D : public B, public C {};

Now, if you try:

D obj;

obj.value = 10;   // Error: ambiguous

The compiler does not know which copy of A to use.

Virtual inheritance solves this problem by ensuring only one shared copy of the base class exists.

class B : virtual public A {};

class C : virtual public A {};

class D : public B, public C {};

Now D contains only one copy of A, and ambiguity is removed.

Why Java avoids this? 

Java does not allow multiple inheritance of classes. It uses interfaces instead, which do not contain state in the same way.

In C++, virtual inheritance must be explicitly declared to avoid duplicate base class instances.

The diamond problem c++ question is common in interviews to test understanding of multiple inheritance behavior.


 

5. What is encapsulation in C++? How is it implemented?

Encapsulation in C++ means bundling data and the functions that operate on that data into a single unit, which is a class. It also means restricting direct access to internal data so that it cannot be modified in an unsafe way.

Encapsulation is implemented using access specifiers such as private, protected, and public.

The common practice is:

  • Keep data members private.
  • Provide public getter and setter methods to access or modify them.

Example:

class BankAccount {
private:
   double balance;


public:
   void deposit(double amount) {
       if (amount > 0)
           balance += amount;
   }


   double getBalance() const {
       return balance;
   }
};

Here, the balance variable cannot be accessed directly. It can only be modified through controlled methods.

Encapsulation matters because It protects data integrity. It prevents external code from setting invalid values.

For example, an ATM machine hides internal banking logic. You cannot directly change your account balance. You must use allowed operations like deposit or withdraw.

Difference between encapsulation and abstraction:

  • Encapsulation hides internal data and protects it.
  • Abstraction hides implementation details and exposes only essential behavior.

For broader OOP comparisons, you can also check out:

Coding Problems

View All Problems

C++ Coding Questions

1.

Which operator can not be overloaded in C++?

2.

What will be the output of the following C++ program:

#include<iostream>
using namespace std;
int main(){
int a=1;
cout<<(a++)*(++a)<<endl;
return 0;
}
3.

What will be the value of x in the following C++ program

#include<iostream>
using namespace std;
int main(){
int a=1;
int x=(a++)++;
cout<<x<<endl;
return 0;
}
4.

What is an abstract class?

5.

Consider the following C++ program

#include<iostream>
using namespace std;
class A{
public:
virtual void a()=0;
A(){
 cout<<"A ";
}
};
class B: public A
{
public:
B(){
 cout<<"B ";
} 
};

int main(){
A *a=new B();

return 0;
}

What will be output?

6.

What is the size of void in C++?

7.

If a base class and derived class each include a member function with the same name. Function from which class will be called if called by an object of the derived class

8.

Memory used by an array is

9.

Which of the following statement is correct?

Excel at your interview with Masterclasses Know More
Certificate included
What will you Learn?
Free Mock Assessment
Fill up the details for personalised experience.
Phone Number *
OTP will be sent to this number for verification
+91 *
+91
Change Number
Graduation Year *
Graduation Year *
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
*Enter the expected year of graduation if you're student
Current Employer
Company Name
College you graduated from
College/University Name
Job Title
Job Title
Engineering Leadership
Software Development Engineer (Backend)
Software Development Engineer (Frontend)
Software Development Engineer (Full Stack)
Data Scientist
Android Engineer
iOS Engineer
Devops Engineer
Support Engineer
Research Engineer
Engineering Intern
QA Engineer
Co-founder
SDET
Product Manager
Product Designer
Backend Architect
Program Manager
Release Engineer
Security Leadership
Database Administrator
Data Analyst
Data Engineer
Non Coder
Other
Please verify your phone number
Edit
Resend OTP
By clicking on Start Test, I agree to be contacted by Scaler in the future.
Already have an account? Log in
Free Mock Assessment
Instructions from Interviewbit
Start Test