50 Best C++ Interview Questions for C++ Job Interviews

50 Best C++ Interview Questions for C++ Job Interviews

If you are a C++ programmer, then this is the right place to find C++ Interview Questions for both developers and programmers.

Since its introduction in the mid-80s, C++ has remained as relevant as ever. It is widely used as a general-purpose, object-oriented programming language. Therefore, several jobs require candidates to have a deep understanding of C++. To help you gain this knowledge, I have compiled a list of 50 most-asked C++ interview questions that will help clear all your doubts and boost your confidence before an interview.

Even though it is hard, C++ is a great language to learn because it doesn't hide anything from you, and so many other languages share a similar syntax. Moreover, C++ gives you the best support when learning other languages. Therefore, learning C++ with the best C++ tutorials will prove beneficial to you.

C++ Interview Questions and Answers For Beginners & Experienced!

1. What is C++?

Answer: C++ is a superset of C, containing additional programming features that the C language does not have. Bjarne Stroustrup developed this language to provide programmers with a high degree of control over system resources.

The probability of the interviewer asking this question is high. So start by giving a simple explanation about what C++ is and you will be fine.

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

Answer: In C++, there are 4 data types:

  1. Primitive Datatype
  2. Derived Datatype
  3. Enumeration
  4. User-defined Datatypes

3. Can we call C++ OOPS? If so, why?

Answer: Yes, we can call C++ OOPS. OOPS stands for object-oriented programming system. It is a paradigm that combines concepts such as data binding, polymorphism, inheritance, and many others.

4. What is namespace in C++?

Answer: What will the compiler do if there are two or more functions with the same name in different libraries? Therefore, namespace came into play. Namespace defines the scope and distinguishes functions, classes, variables, etc., that have the same name but from different libraries. The namespace begins with the keyword namespace.

5. Define Class in C++?

Answer: Class in C++ is a user-defined data type, which includes data members and member functions. Data members are data variables, whereas member functions are the functions that operate on these variables.

6. Define Object in C++?

Answer: An object is an instance of a class. It can have fields, methods, constructors, and related. E.g., a bike in real life is an object, but its various features - brakes, color, size, design - are instances of its class.

7. Briefly explain the concept of Inheritance in C++.

Answer: Classes in C++ can inherit some of the commonly used states and behaviors from other classes. We call this process Inheritance.

8. Define a class template?

Answer: A class template refers to the generic class. The keyword template is used for defining a class template.

9. Define Encapsulation in C++?

Answer: Encapsulation refers to the integration of data and functions within a class. For security reasons, it prevents direct access to the data. The process takes place with the help of class functions. For example, customers are only allowed access to the net banking system if they have the required username and password. Moreover, it is only applicable to their part of the information obtained from the database.

10. What is an abstraction in C++?

Answer: Abstraction in C++ is the process of hiding the internal implementations and displaying only the necessary information. At that time, when you send an important email, you can only type and click the send option. As a result, you will see a confirmation message that confirms your email was sent successfully. Nevertheless, the process followed in transferring the data via email is not displayed as it is not relevant.

11. What is the function of the keyword “Volatile”?

Answer: Volatile is a function that declares that a specific variable is volatile and, therefore, directs the compiler to change it externally, thus avoiding the compiler optimization on the variable reference.

12. Explain ‘this’ pointer?

Answer: The ‘this’ pointer is constant and contains the memory address of the current object. All nonstatic member function calls receive it as a hidden argument. Additionally, it is present as a local variable within the body of all nonstatic functions.

Because static function members are callable even without any object, namely, with the class name, they do not have the 'this' pointer.

13. Define storage class in C++? Name some?

Answer: In C++, the Storage class resembles life or even the scope of symbols, containing variables, functions, etc. C++ has several storage classes, such as mutable, auto, static, extern, register, etc.

14. Define an Inline Function in C++? Is it possible for the C++ compiler to ignore inlining?

Answer: C++ offers inline functions to reduce function call overhead. As the name implies, inline functions are expanded in line when they are called.

Once an inline function is called, its entire code is either inserted or substituted at the particular point of the inline function call. The C++ compiler completes the substitution at compile time. It might be possible to increase program efficiency by adding small inline functions.

15. Can we have a recursive inline function in C++?

Answer: It is possible to call an inline function from within itself in C++, but the compiler may not produce the code. It is because the compiler will not determine the depth of the recursion during compilation.

Nonetheless, a compiler with a good optimizer can inline recursive calls until a certain depth is fixed at compile-time and insert non-recursive calls at compile time when the actual depth exceeds run time.

16. What are the main differences between C and C++?

Answer:

CC++
It doesn't support referencesIt supports references
C doesn't offer features such as friend functions, function overloading, inheritance, templates, and virtual functionsC++ has features such as friend functions, function overloading, inheritance, templates, and virtual functions.
In C, exception handling takes place in the traditional if-else style.C++ supports exception handling at the language level.
scanf() and printf() are mainly used input and output in C.cin is the standard input stream, and cout is the standard output stream in C++.
It is a procedural programming language.C++ supports both procedural and object-oriented programming approaches.

17. Why do we need the Friend class and function?

Answer: There are times when a class needs access to the private or protected members of another class. In this case, the solution is to build a friend class that can access the protected and private members of the class to which it is friended.

In the same way, there is a friend function that can access protected and private members. A friend function may either be a global function or a method of a class.

What you need to know about the friend class and friend function:

  • There is no inheritance in friendship.
  • Friendship is not mutual, i.e., if a class called Friend is a friend of a class called NotAFriend, then NotAFriend does not immediately become a friend of Friend.
  • A program's total number of friend classes and friend functions should be limited to prevent a depreciation of the principle of encapsulation of separate classes, an inherent and desirable quality of object-oriented programming.

18. Is it possible for a C++ program to be compiled without the main() function?

Answer: Certainly. Unfortunately, as the main() function is essential for the execution of the program, it will not execute after compilation.

19. What is a destructor?

Answer: It is the member function of the class. Additionally, it is prefixed with the tilde symbol and has the same name as the class name. Whenever an object loses its scope, it can be executed automatically.

20. Can we overload a destructor?

Answer: As a destructor is the only form without parameters, it cannot be overloaded.

21. What is the difference between struct and class?

Answer: Structures in C++ are similar to classes, except for a few differences like security. Below are the differences between structs and classes:

StructClass
If a struct is derived from a class/struct, the base class/struct's default access specifiers are public.Default access specifiers are private when deriving a class.
By default, each structure member is public.By default, members of the class are private.

22. What is the default constructor?

Answer: In case a constructor is not provided by the provider, the compiler provides one. Therefore, it is called a default constructor when the programmer provides the constructor with no specific parameters.

23. Is it possible to provide one default constructor for our class?

Answer: No, our class cannot have one default constructor. Furthermore, if a variable in a class type is set to null, it means the variable was never initialized and the outcomes will result in zero.

24. What is polymorphism in C++?

Answer: Having multiple forms is called polymorphism. Different situations cause it to behave differently. Multiple classes that are related by inheritance lead to this situation.

For instance, imagine a base class called a car that has a method called car brand(). Consequently, Mercedes, BMW, and Audi are derived classes of cars, and they also have their version of the car.

C++ includes two types of polymorphism:

  1. Runtime Polymorphism
  2. Compile Time Polymorphism

25. Compare Compile-time polymorphism and Runtime polymorphism

Answer:

Compile-time PolymorphismRun time Polymorphism
Using this method, we will know the method to be called at compile time. The compiler resolves the call.With this method, we know at run time which method will be called. The compiler does not resolve the call.
Because it is known at compile-time, it provides fast execution.Because it is known at run-time, it provides slower execution than compile-time polymorphism.
Function overloading and operator overloading are used to accomplish this.Virtual functions and pointers can be used to achieve this.

26. What are the C++ access specifiers?

Answer: There are the following access specifiers in C++:

  • Public - All data members and member functions are available outside the class
  • Private - All data members and member functions are not available outside the class.
  • Protected - All data members and member functions are available within the class and to the derived class.

27. What is a reference in C++?

Answer: A reference is similar to a pointer. Essentially, it is another name for an existing variable. Once a reference name is initialized with a variable, that variable can be accessed either by the variable name or by the reference name.

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

Answer: Using the call by value method, we pass a copy of the parameter to the function. Each copied value is assigned a new memory, and any changes made to these values are not reflected in the main function.

Using the call by reference method, we provide the address of a variable and the address allows us to access the actual argument used in a function call. Therefore, changes to a parameter will alter its passing argument.

29. What differences separate structure from a class in C++?

Answer: C++ distinguishes between a class and a structure by two important factors. As follows:

  • Whenever a structure is derived from a class or another structure, the default access specifier for the base class or structure is public. When derived, however, a default access specifier is private.
  • By default, members of a structure are public, but members of a class are private.

30. What does a Static member in C++ mean?

Answer: Static members are allocated storage only once during the lifetime of the program, in the static storage area, as indicated by the static keyword. Static members have the following important characteristics:

  • Any static member function can not be virtual
  • They do not have 'this' pointers.
  • For static member functions, the const, const volatile, and volatile declarations are not available.

31. Draw a comparison between C++ and Java.

Answer: Below is the comparison between C++ and Java in a table form:

C++Java
Destructors are invoked automatically when an object is destroyed in C++.Java has a feature called automatic garbage collection.
C++ supports multiple inheritance, pointers, structures, operator overloading, templates, and unions.None of them exist in Java.
No inbuilt support for threads.In Java, new threads are created by inheriting the Thread class.
A goto statement in C++ allows one to jump from a location to a labeled statement within the same function.There is no goto statement in Java.
C++ is run and compiled using the compiler, which translates the source code into machine language. Therefore, it is platform-dependent.Java compilers, on the other hand, convert source code into JVM bytecode, which is platform-independent.

32. 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?

Answer: In the derived class, there are two parts: a base part, and a derived part. It works in phases to construct derived objects in C++. The most basic class (at the top of the inheritance tree) is constructed first. Afterward, every child class is constructed one by one until the most-child class is constructed last. Thus, the constructor of class B will be called first, followed by the constructor of class D.

During the destruction, the reverse order is followed exactly. The destructor begins at the most derived class and works its way down to the base class. Thus, the first destructor of class D will be called, followed by the destructor of class B.

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

Answer: In C++, the new operator is used for memory allocation, while the deletes operator is used for memory deallocation. 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

34. Observe the following code snippet:

int i = 5;
int j = i++;

After execution, what will be the value of I and j? Explain your answer.

Answer: When the above code is executed, i and j will be 6 and 5, respectively. To understand the output, you must understand how the unary ++ operator and the decrement -- operator work in C++.

When any of these operators precede a variable, the variable's value is first modified, and then the modified value is used. However, when either of the two operators follows a variable, the value is used first, and then it is modified.

In the code above, therefore, j is set to the unmodified value of 5 and then i is incremented to store 6.

35. What is a mutable storage class specifier? How can they be used?

Answer: Mutable storage class specifiers only apply to non-static and non-constant member variables of a class. Using it, you can alter the constant class object's members by declaring them. You can do this by using a storage class specifier.

36. Define an Abstract class in C++?

Answer: C++ abstract classes are called base classes, which have at least one pure virtual function. A person cannot instantiate an abstract class in such a function. As a result, Abstract classes with pure virtual functions are defined by using a pure specifier that is equal to zero in the declaration of the virtual member functions in the class declaration.

For example:

// An abstract class
class Test
{ 
    // Data members of class
public:
    // Pure Virtual Function
    virtual void show() = 0;
   /* Other members */
};

37. Explain the significance of vTable and vptr in C++ and how the compiler deals with them?

Answer: Function pointers are stored in a table called vTable. Each class has a vTable. A pointer to vTable is called vPtr. Every object has a vptr. The C++ compiler adds additional code to maintain and use vptr and vTable:

1) In every constructor – This code sets vptr:

  • Of the object being created
  • To point to vTable of the class

2) Code with the polymorphic functional call – Every time a polymorphic call is made, the compiler inserts code to look first for vptr using the base class pointer or reference. Once the vptr has been successfully retrieved, the vTable of the derived class can be accessed. The vTable is used to access and call the address of the derived class function show().

38. Define Block scope variable?

Answer: Using C++, a Block scope variable is specified as a block and can declare anywhere within a block.

39. Can we use access specifiers to achieve data hiding in C++?

Answer: In C++, we can use access specifiers to hide data. The two most common are Private and Protected.

40. Define the Copy Constructor used in C++ along with its general function prototype. Also, explain the various scenarios in which it is called.

Answer: In C++, a copy constructor is a member function that initializes an object by using another object of the same class. You can also make Copy Constructor private. There are 4 scenarios in which the Copy Constructor might be accessed:

  1. The compiler produces a temporary object.
  2. An object is constructed or derived from another object of the same class.
  3. An object of the class is returned by value.
  4. As an argument, an object of the class is passed (i.e., to a function) by value.

The Copy Constructor's general function prototype is:

ClassName (const ClassName &old_obj);
Point(int x1, int y1) { x=x1; y=y1;}
Point(const Point &p2) { x=p2.x; y=p2.y; }

41. Can we have a String primitive data type in C++?

Answer: String Primitive data types are not supported in C++. As an alternative, we can use a class from the Standard Template Library (STL).

42. What are the functions of the scope resolution operator?

Answer: Scope resolution operators perform the following functions.

  • It helps in defining the scope of various global variables.
  • When a function is defined outside a class, it helps to associate it with that class.

43. Define a token in C++? Give examples?

Answer: Tokens are names given to various functions in C++ programs. An example of a token is a keyword, symbol, string literal, identifier, constant, etc. Here is an example of token code in C++ other than C.

asm       bool     catch       class
const_cast   delete dynamic_cast   explicit
export    false    friend         inline
mutable   namespace   new  operator
private   protected   public  reinterpret_cast
static_cast  template this        throw
true      try      typeid      typename
using     virtual  wchar_t

44. Take a look at the following two code examples for printing a vector:

Sample Code 1:

vector vec;
/* ... .. ... */
for (auto itr = vec.begin(); itr != vec.end(); itr++) {
 itr->print();
}

Sample Code 2:

vector vec;
/* ... .. ... */
for (auto itr = vec.begin(); itr != vec.end(); ++itr) {
 itr->print();
}

Is there any advantage of using one over the other?

Answer: Although both codes produce the same output, sample code 2 is more efficient. Since 'itr++' is more expensive than '++itr,' it is because the post-increment operator is more expensive.

Before incrementing the element and returning the copy, the post-increment operator generates a copy of the element. Furthermore, most compilers will automatically optimize sample code 1 by converting it implicitly into sample code 2.

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

Answer: Using a constructor, we can invoke a virtual function. In this case, however, the behavior is a little different. The virtual call is resolved at runtime when a virtual function is called. Whenever a class is invoked, its member function is called. In other words, the virtual machine does not work within the constructor.

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

Answer: A virtual function is a member function of the base class that is redefined in a derived class. With the virtual keyword, it is declared.

Meanwhile, in pure virtual functions, there is no implementation and is declared by assigning 0. It has no one.

47. Which operator cannot be overloaded in C++ ?

Answer: The following operators in C++ cannot be overloaded:

  • Dot operator - “.”
  • “sizeof” operator
  • Pointer to member operator - “.*”
  • Scope resolution operator - “::”

48. What is stl in C++? Explain with example?

Answer: Standard Template Library is a library in C++ and refers to STL. STL is a generalized library that provides data structures, containers, algorithms, and iterators for various programming applications. STL consists of four components:

  • Algorithms: Searching and sorting algorithms such as binary search and merge sort.
  • Containers: Vector, list, queue, arrays, map, etc.
  • Functions: Objects that act like functions.
  • Iterators: It is an object that provides navigation through elements of a container, e.g., vector::iterator.

49. How to initialize a 2d vector in C++?

Answer: Following is the syntax for initializing a 2d vector:

std::vector<std::vector<int> > name_of_vector;

For e.g. : std::vector > v { { 1, 2, 1 }, { 2, 6, 7 } };

50. How is modularity introduced in C++?

Answer: The definition of modularity is that it refers to the mapping of encapsulated abstractions into physical ones which are related to encapsulation. Basically, it involves breaking down separate programs into separate modules.

For example: When building a house, it is done modularly. The foundation is laid first, then the structure is built, and so on.


If you have made it this far, then certainly you are willing to learn more about programming. Here are some more resources related to programming that we think will be useful to you.

Did you find this article valuable?

Support Yash Tiwari by becoming a sponsor. Any amount is appreciated!