0% found this document useful (0 votes)
32 views

50 technical C++ Interview Questions with Answers

The document contains 50 technical C++ interview questions along with their answers, covering fundamental concepts such as memory management, object-oriented programming, polymorphism, and modern C++ features. Key topics include differences between new and malloc, constructors and destructors, smart pointers, and the significance of RAII. It also discusses advanced topics like move semantics, lambda functions, and the differences between C++11 and C++17.

Uploaded by

div29042
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
32 views

50 technical C++ Interview Questions with Answers

The document contains 50 technical C++ interview questions along with their answers, covering fundamental concepts such as memory management, object-oriented programming, polymorphism, and modern C++ features. Key topics include differences between new and malloc, constructors and destructors, smart pointers, and the significance of RAII. It also discusses advanced topics like move semantics, lambda functions, and the differences between C++11 and C++17.

Uploaded by

div29042
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

50 technical C++ Interview Questions with Answers

1. What is the difference between new and malloc?

● Answer:
new is an operator that initializes the object and calls the constructor, while
malloc is a function that only allocates memory and does not initialize the
object. new returns a pointer of the appropriate type, whereas malloc returns a
void*, which needs to be cast to the appropriate type.

2. What is a constructor and a destructor in C++?

la
● Answer:
ng
A constructor is a special member function that is automatically called when an
object is created to initialize it. A destructor is a member function that is
Si
automatically invoked when an object is destroyed, typically used for cleanup
purposes such as releasing resources.
tra

3. What is the difference between struct and class in C++?


hi
C

● Answer:
The only difference between struct and class in C++ is the default access
level. For struct, members are public by default, whereas for class, members
are private by default.

4. What is the purpose of the virtual keyword in C++?

● Answer:
The virtual keyword is used to declare a function as virtual, enabling
polymorphism. It allows derived classes to override the function. When using a
base class pointer, the virtual function ensures that the correct function is called,
depending on the object's actual type.
5. Explain RAII (Resource Acquisition Is Initialization) in C++.

● Answer:
RAII is a C++ programming idiom in which resources like memory or file handles
are managed by objects. When an object is created, it acquires resources, and
when it goes out of scope or is destroyed, it releases them automatically,
preventing resource leaks.

6. What is a pure virtual function?

● Answer:
A pure virtual function is a function in a base class that has no definition. It is

la
declared using = 0 at the end of the function declaration. A class containing a
pure virtual function is an abstract class and cannot be instantiated. Derived
ng
classes must implement this function.
Si
7. What is the difference between overloading and overriding in C++?
tra

● Answer:
Overloading occurs when multiple functions with the same name are defined but
hi

have different parameters (either in number or type). Overriding occurs when a


derived class provides a new implementation for a function that is already
C

defined in its base class.

8. What is a smart pointer?

● Answer:
A smart pointer is an object in C++ that automatically manages the lifetime of
dynamically allocated memory. Smart pointers help avoid memory leaks and
dangling pointers by automatically deallocating memory when it is no longer
needed. Examples include std::unique_ptr, std::shared_ptr, and
std::weak_ptr.
9. What is the difference between a shallow copy and a deep copy?

● Answer:
A shallow copy copies the values of the members of an object, but it does not
clone dynamically allocated memory or pointed-to objects. A deep copy
duplicates everything, including dynamically allocated memory, ensuring that the
copy is independent of the original.

10. What is the use of the explicit keyword in C++?

● Answer:
The explicit keyword is used to mark constructors or conversion operators to
prevent implicit conversions. It ensures that a constructor or operator is not used
for automatic conversions unless explicitly invoked by the programmer.

la
ng
11. What is the difference between public, private, and protected
Si
access modifiers?

● Answer:
tra

○ public: Members are accessible from anywhere.


○ private: Members are only accessible within the class itself.
hi

○ protected: Members are accessible within the class and by derived


classes.
C

12. What is the this pointer in C++?

● Answer:
The this pointer is an implicit pointer passed to all non-static member functions
of a class. It points to the current instance of the class, allowing access to the
object’s members and methods.

13. What is the static keyword used for in C++?


● Answer:
The static keyword can be used in several contexts:
○ For variables inside functions, it preserves the variable’s value between
function calls.
○ For class members, it means the member is shared across all instances of
the class (i.e., it is not tied to any specific object).
○ For functions, it limits the scope of the function to the file it is declared in.

14. What is a virtual destructor, and why is it important?

● Answer:
A virtual destructor is necessary for ensuring that derived class destructors are
called when an object is deleted through a base class pointer. Without a virtual
destructor, only the base class destructor is called, leading to potential memory

la
leaks or undefined behavior.
ng
Si
15. Explain the concept of object slicing in C++.

● Answer:
tra

Object slicing occurs when an object of a derived class is assigned to an object


of a base class, and the derived class-specific data is "sliced off". This happens
because the base class does not know about the additional members of the
hi

derived class, resulting in loss of information.


C

16. What is the difference between const and constexpr in C++?

● Answer:
const means that the value of a variable cannot be changed after initialization,
but it may be computed at runtime. constexpr indicates that the value of a
variable is constant and must be computed at compile-time.

17. What is the significance of inline functions in C++?


● Answer:
The inline keyword suggests to the compiler to replace the function call with
the function's body during compilation, potentially improving performance by
eliminating function call overhead, especially for small functions. However, the
compiler can choose to ignore the inline suggestion.

18. What is the std::move function in C++?

● Answer:
std::move is used to enable moving of resources from one object to another. It
casts an object to an rvalue reference, allowing resources to be transferred
without copying, improving performance, especially with large objects.

la
19. What is the difference between static_cast, dynamic_cast,
ng
const_cast, and reinterpret_cast?
Si
● Answer:
○ static_cast: Used for normal type conversions (e.g., converting
tra

between related classes or basic types).


○ dynamic_cast: Used for safe downcasting in polymorphic class
hierarchies.
hi

○ const_cast: Used to add or remove const qualifier from a variable.


C

○ reinterpret_cast: Used for low-level, potentially unsafe type


conversions between different types.

20. What is an rvalue reference in C++?

● Answer:
An rvalue reference is a reference to a temporary object (rvalue) that can be
used to implement move semantics. It is declared using && (double ampersand),
allowing efficient transfer of resources from one object to another.

21. What are friend functions in C++?


● Answer:
A friend function is a function that can access the private and protected
members of a class. It is not a member function but is granted access through a
friend declaration inside the class.

22. What is the nullptr keyword in C++?

● Answer:
nullptr is a type-safe null pointer constant introduced in C++11. It is used to
indicate that a pointer does not point to any object or valid memory.

23. What are template classes and functions in C++?

la
● Answer:
ng
Templates allow writing generic functions and classes that can operate with any
data type. Template classes and functions are defined using the template
Si
keyword, followed by the type parameter(s).
tra

24. Explain the concept of std::tuple in C++.


hi

● Answer:
C

std::tuple is a fixed-size collection of elements of potentially different types. It


allows grouping heterogeneous values together and is similar to a structure, but
more flexible as it can hold any type in any order.

25. What is the purpose of std::vector in C++?

● Answer:
std::vector is a dynamic array that can resize itself automatically as elements
are added or removed. It provides fast random access and is typically used when
the number of elements is not known in advance or changes frequently.

26. What are namespaces in C++?


● Answer:
Namespaces are a way to organize code and avoid name conflicts. They allow
grouping of related classes, functions, and variables. The std namespace, for
example, contains all standard library functions and classes.

27. What is the purpose of the mutable keyword in C++?

● Answer:
The mutable keyword allows modification of a member variable even in a
const object or const member function. It is often used when caching or lazy
initialization is needed.

la
28. What is the difference between std::list and std::vector?

● Answer:
ng
○ std::vector: Provides fast random access and is better for scenarios
Si
where elements are frequently accessed by index. However, insertions
and deletions in the middle are slow.
tra

○ std::list: Implements a doubly linked list, making insertions and


deletions fast, but random access is not possible (only sequential
traversal).
hi
C

29. What are the advantages of C++ over C?

● Answer:
C++ provides features like object-oriented programming, type safety with
stronger typing, templates for generic programming, and a standard library that
includes containers, algorithms, and iterators, making it more versatile and
powerful than C.

30. What is the difference between compile-time polymorphism and runtime


polymorphism in C++?
● Answer:
○ Compile-time polymorphism: Achieved using function overloading and
operator overloading. It is resolved during compilation.
○ Runtime polymorphism: Achieved using virtual functions and pointers,
resolved during program execution using dynamic dispatch.

31. What is a virtual table (vtable) in C++?

● Answer:
A vtable is a table of pointers to virtual functions in a class. It is used to support
runtime polymorphism. Each class with virtual functions has its own vtable, and
objects use it to determine the correct function to call for their type.

la
32. Explain the difference between override and final in C++11.

● Answer:
ng
Si
○ override: Indicates that a member function is meant to override a base
class function, ensuring at compile-time that the function signature
matches.
tra

○ final: Prevents further overriding of a virtual function in derived classes


or inheritance from a class.
hi
C

33. What are move constructors and move assignment operators in C++?

● Answer:
Move constructors and move assignment operators are special functions that
allow resources to be transferred from one object to another, instead of copying.
This is useful for optimizing performance by avoiding deep copies. Declared
using rvalue references (&&).

34. What is the significance of std::string_view in C++17?

● Answer:
std::string_view is a lightweight, non-owning reference to a string. It allows
efficient manipulation of strings without creating copies, making it faster for
read-only string operations.

35. What is the difference between throw(), noexcept, and


noexcept(true)?

● Answer:
○ throw(): Deprecated in C++11, it indicated that a function does not throw
exceptions.
○ noexcept: Introduced in C++11, it specifies that a function is guaranteed
not to throw exceptions.
○ noexcept(true): Explicitly indicates that the function does not throw
exceptions.

la
ng
36. What is the role of std::unordered_map in C++?
Si
● Answer:
std::unordered_map is an associative container that provides fast access to
tra

key-value pairs using a hash table. It has average constant-time complexity for
lookups, insertions, and deletions.
hi
C

37. What is a lambda function in C++?


Answer:
A lambda function is an anonymous function that can be defined in-place using the
syntax:

[capture_list](parameters) -> return_type { body };

● Lambda functions are often used for short, throwaway functions in algorithms.

38. What is the difference between std::shared_ptr and


std::unique_ptr?
● Answer:
○ std::shared_ptr: Allows multiple shared ownership of a resource. The
resource is destroyed when the last shared_ptr pointing to it is
destroyed.
○ std::unique_ptr: Provides sole ownership of a resource. It cannot be
copied, only moved.

39. What is the difference between delete and delete[]?

● Answer:
○ delete: Used to deallocate memory for a single object allocated with
new.
○ delete[]: Used to deallocate memory for arrays allocated with new[].

la
40. What is a function pointer in C++?
ng
Si
Answer:
A function pointer is a pointer that stores the address of a function. It allows functions to
be passed as arguments to other functions or stored in containers.
tra

Example:
hi

void foo() { std::cout << "Hello"; }


void (*funcPtr)() = foo;
C

funcPtr();

41. What is a dangling pointer in C++?

● Answer:
A dangling pointer is a pointer that points to memory that has been deallocated
or released. Accessing it leads to undefined behavior.

42. What is type casting in C++?


● Answer:
Type casting converts one data type into another. C++ provides four types of
casts:
○ static_cast: Compile-time type checking.
○ dynamic_cast: For safe downcasting in polymorphism.
○ const_cast: Adds/removes const qualifier.
○ reinterpret_cast: For low-level type conversions.

43. What is std::atomic in C++?

● Answer:
std::atomic provides a way to perform lock-free and thread-safe operations
on shared variables. It is commonly used in multi-threaded programs.

la
44. What are variadic templates in C++?
ng
Si
Answer:
Variadic templates allow a function or class template to accept an arbitrary number of
template arguments. Defined using ... (ellipsis).
tra

Example:
hi

template<typename... Args>
void func(Args... args) { }
C

45. What are the differences between inline and constexpr functions?

● Answer:
○ inline: Suggests to the compiler to replace function calls with the
function body to reduce overhead.
○ constexpr: Ensures that the function can be evaluated at compile-time if
the input is constant.

46. What is the difference between typedef and using in C++?


Answer:
Both are used for type aliasing. using is introduced in C++11 and is more readable,
especially for template aliases.
Example:

typedef int* IntPtr; // Typedef


using IntPtr = int*; // Using

47. What is the difference between shallow and deep copying in C++?

● Answer:
○ Shallow Copy: Copies object structure as-is, including pointers, without
duplicating pointed-to data.
○ Deep Copy: Creates new copies of the pointed-to data, ensuring

la
independence from the original object.

ng
48. What is the rule of three in C++?
Si
● Answer:
If a class requires a user-defined destructor, copy constructor, or copy
tra

assignment operator, it likely needs all three. This is because the class manages
resources that need explicit handling.
hi
C

49. What is the role of the std::function class in C++?

● Answer:
std::function is a wrapper for callable entities (functions, lambda functions,
function pointers). It provides a uniform way to store and invoke any callable
entity.

50. What are the major differences between C++11 and C++17?

● Answer:
○ C++11: Introduced features like auto, lambda expressions, nullptr,
smart pointers, and move semantics.
○ C++17: Added std::optional, std::variant, std::string_view,
structured bindings, and constexpr improvements.

la
ng
Si
tra
hi
C

You might also like