C++ Interview Questions
C++ is backbone of many enterprise applications owing to its popularity. The job opportunities are immense in C++. Hence below are some of the c++ interview questions that you can go through which will help you prepare for c++ interview. You can also download the c++ interview questions towards the end.
Q1 : What is header file in C language?
Answer
- Header file is a file that contains functions declaration and macro definition for C in built library functions.
- All C standard library functions are declared in manyheader files which are saved as file_name.h.
- We are including these header files in our C program using “#include” command to make use of the functions those are declared in the header files.
- When we include header files in our C program using “#include” command, all c code of the header files are included in C program. Then, this C program is compiled by compiler and executed.
Q2 : What is a destructor? Can it be overloaded?
Answer
A destructor is the member function of the class which is having the same name as the class name and prefixed with tilde (~) symbol. It gets executed automatically w.r.t the object as soon as the object loses its scope. It cannot be overloaded and the only form is without the parameters.
Q3 : By default every local variable of the function is automatic (auto). In the below function both the variables ‘i’ and ‘j’ are automatic variables.
Answer
void f()
{
int i;
auto int j;
}
Q4 : What are the different ways of passing parameters to the functions? Which to use when?
Answer
- Call by value − We send only values to the function as parameters. We choose this if we do not want the used.
- Call by address − We send address of the actual parameters instead of values. We choose this if we do want the actual parameters to be modified with formal parameters.
- Call by reference − The actual parameters are received with the C++ new reference variables as formal parameters. We choose this if we do want the actual parameters to be modified with formal parameters.
Q5 : What is arithmetic operator in C?
Answer
- C Arithmetic operators are used to perform mathematical calculations like addition, subtraction, multiplication, division and modulus in C programs.
- Arithmetic operators are +, -, *, /, %.
Q6 : What are all loop controls statements in C?
Answer
Loop control statements in C are used to perform looping operations until the given condition is true. Control comes out of the loop statements once condition becomes false. There are 3 types of loop control statement in C
They are.
- for
- while
- do–while
Q7 :What is the difference between memcpy() & strcpy() functions in C?
Answer
- memcpy() function is used to copy a specified number of bytes from one memory to another. Whereas, strcpy() function is used to copy the contents of one string into another string.
- memcpy() function acts on a memory rather than value. Whereas, strcpy() function acts on value rather than memory.
Q8 : What will the line of code below print out and why?
#include <iostream>
int main(int argc, char **argv)
{
std::cout << 25u – 50;
return 0;
}
Answer
The answer is not -25. Rather, the answer (which will surprise many) is 4294967271, assuming 32 bit integers. Why?
In C++, if the types of two operands differ from one another, then the operand with the “lower type” will be promoted to the type of the “higher type” operand, using the following type hierarchy (listed here from highest type to lowest type): long double, double, float, unsigned long int, long int, unsigned int, int (lowest).
So when the two operands are, as in our example, 25u (unsigned int) and 50 (int), the 50 is promoted to also being an unsigned integer(i.e., 50u).
Moreover, the result of the operation will be of the type of the operands. Therefore, the result of 25u – 50u will itself be an unsigned integer as well. So the result of -25 converts to 4294967271 when promoted to being an unsigned integer.
Q9 :C++ supports multiple inheritance. What is the “diamond problem” that can occur with multiple inheritance? Give an example.
Answer
It means that we cannot create hybrid inheritance using multiple and hierarchical inheritance.
Let’s consider a simple example. A university has people who are affiliated with it. Some are students, some are faculty members, some are administrators, and so on. So a simple inheritance scheme might have different types of people in different roles, all of whom inherit from one common “Person” class. The Person class could define an abstract getRole() method which would then be overridden by its subclasses to return the correct role type.
But now what happens if we want to model the role of a Teaching Assistant (TA)? Typically, a TA is both a grad student and a faculty member. This yields the classic diamond problem of multiple inheritance and the resulting ambiguity regarding the TA’s getRole() method:
Q 10 : What is the error in the code below and how should it be corrected?
my_struct_t *bar;
/* … do stuff, including setting bar to point to a defined my_struct_t object … */
memset(bar, 0, sizeof(bar));
Answer
The last argument to memset should be sizeof(*bar),
not sizeof(bar). sizeof(bar) calculates the size of bar (i.e., the pointer itself) rather than the size of the structure pointed to by bar.
The code can therefore be corrected by using sizeof(*bar) as the last argument in the call to memset.
A sharp candidate might point out that using *bar will cause a de-referencing error if bar has not been assigned.Therefore an even safer solution would be to use sizeof(my_struct_t). However, an even sharper candidate must know that in this case using *bar is absolutely safe within the call to sizeof, even if bar has not been initialised yet, since sizeof is a compile time construct.
Q 11: Explain storage qualifiers in C++.
Answer
1). Const : This variable means that if the memory is initialised once, it should not be altered by a program.
2). Volatile : This variable means that the value in the memory location can be altered even though nothing in the program code modifies the contents.
3). Mutable : This variable means that a particular member of a structure or class can be altered even if a particular structure variable, class or class member function is constant.
Q12 : Write a program using Display() function which takes two arguments.
Answer
cout << A[0] << ” “;
cout << A[1] << ” “;
…..
cout << A[N-1] << ” “;
In general : cout << A[i] << ” ” ; where i = 0 to N-1
void Display( float A[ ], int N )
{
for ( int i = 0; i<= N-1; i++)
cout << A[i] << ” “;
cout << endl;
}
Q 13: What is searching? Explain linear and binary search.
Answer
Finding the location of a given element in a given data structure is called searching.
There are two types of search :
1). Linear Search :
In this, the element to be searched is compared one by one with each element of given list, starting with first element. The process of comparisons remain continue until the element is not found or list gets exhausted.
2). Binary Search :
It is another technique of searching an element in a given list in minimum possible comparisons. But for applying binary search on a list, there are two pre-conditions :
- The elements of list must be arranged either in ascending or descending order.
- The list must be of finite size and should be in form of linear array.
Q 14: Write a program using SHIFT_HALF( ) function to shift the elements of first half array to second half and vice versa.
Answer
swap(A[0], A[mid]) swap(A[1], A[mid+1])
….
swap(A[mid-1], A[N-1])
mid = n/2; i = 0, j = mid; swap( A[i], A[j] ) where i = 0 to mid-1
void SHIFT_HALF( float A[], int n )
{
int mid= n/2;
for ( int i = 0, j =mid; i<= mid-1; i++,j++)
{
float T = A[i];
A[i] = A[j];
A[j] = T;
}
}
Q 15 :Explain Bubble sorting.
Answer
In Bubble Sorting, we have to perform N-1 steps to sort a linear array.
1). In first iteration, we compare A[0] with A[1], A[1] with A[2],……….
A[N-2] with A[N-1] and interchange them if they are not in desired order.
2). In Second iteration, we compare A[0] with A[1], A[1] with A[2],……….
A[N-3] with A[N-2] and interchange them if they are not in desired order.
3). In Third iteration, we compare A[0] with A[1], A[1] with A[2],……….
A[N-4] with A[N-3]and interchange them if they are not in desired order.
4). In last iteration , we compare A[0] with A[1].
Q 16 : What are the various situations where a copy constructor is invoked?
Answer
Various situations where a copy constructor is invoked are as follows :
- When an object is defined and initializes with the values of another object of the same type, then copy constructor is invoked.
- When an object is passed by value method, then copy constructor is invoked to create the copy of the passed object for the function.
- When a function returns an object, then copy constructor is invoked to create a temporary object to hold the return value in the memory.
Q 17 : List the special characteristics of constructor.
Answer
- A constructor has the same name as that of class.
- It is automatically invoked when an object of the class is declared.
- Constructor obeys the usual access rule. Private & protected constructor can only be accessed by the member function and friend function of the class, Public constructor is available for all the function. Only that function can create the object that has access to the constructor.
- No return type is specified for the constructor.
- These cannot be inherited but a derived class can invoke base class constructor.
- A constructor can also have default arguments.
- A constructor can invoke the member functions.
- The default constructor and copy constructor are provided by the compiler only if these are not defined by the programmer.
Q 18 : How a new element can be added or pushed in a stack?
Answer
Pushing an element into stack :
-Whenever an element is to be pushed into stack, TOP is increased by 1 and then the element is inserted in the linear array denoted by S[ ] at the location with index TOP i.e. at S[TOP]. During push() operation, a
stage may come when TOP points to the last location in array S[ ] i.e. it becomes equal to stksize-1, then no more element can be pushed into stack and we say that Stack Overflow.
-Algo Push(S,Top, Item)
Step 1 : If (Top == stksize-1)
then (i) Write “Stack Overflow ”
(ii) Exit
step 2 : top = top + 1
step 3 : S[top] = Item
step 4 : Exit
Q 19 : What are virtual functions?
Answer
Polymorphism is also achieved in C++ using virtual functions. If a function with same name exists in base as well as parent class, then the pointer to the base class would call the functions associated only with the base class. However, if the function is made virtual and the base pointer is initialized with the address of the derived class, then the function in the child class would be called.
Q 20 : How should runtime errors be handled in C++?
Answer
- The runtime errors in C++ can be handled using exceptions.
- This exception handling mechanism in C++ is developed to handle the errors in software made up of independently developed components operating in one process and under synchronous control.
- According to C++, any routine that does not fulfil its promise throws an exception. The caller who knows the way to handle these exceptions can catch it.
Q 21 : Which of the following accesses the seventh element stored in array?
- array[6];
- array[7];
- array(7);
- array;
Answer
b)
Q 22 : What will be the output of this program?
advertisement
#include <stdio.h>
#include<iostream>
using namespace std;
int array1[] = {1200, 200, 2300, 1230, 1543}; int array2[] = {12, 14, 16, 18, 20};
int temp, result = 0;
int main()
{
for (temp = 0; temp < 5; temp++)
{
result += array1[temp];
}
for (temp = 0; temp < 4; temp++)
{
result += array2[temp];
}
cout << result;
return 0;
}
- 6553
- 6533
- 6522
- 12200
Answer
- b (Explanation: In this program we are adding the every element of two arrays. Finally we got output as 6533.)
Q23 : What is the index number of the last element of an array with 9 elements?
- 9
- 8
- 0
- Programmer-defined
Answer
- 2 (Explanation: Because the first element always starts at 0. So it is on 8 position.)
Q 24 : What is the correct definition of an array?
- An array is a series of elements of the same type in contiguous memory locations
- An array is a series of element
- An array is a series of elements of the same type placed in non-contiguous memory locations
- None of the mentioned
Answer
- a(Explanation: Correct definition of an array is An array is a series of elements of the same type in contiguous memory locations.)
Q25 : Which of the following gives the memory address of the first element in array?
- array[0];
- array[1];
- array(2);
- array;
Answer
- 4
(Explanation: To get the address of ith index of an array, we use following syntax (arr + i). So as we need address of first index we will use (arr + 0) equivalent to arr.)
Q 26 : What is the output of this program?
#include <stdio.h>
#include<iostream>
using namespace std;
int main()
{
int a = 5, b = 10, c = 15;
int arr[3] = {&a, &b, &c};
cout << *arr[*arr[1] – 8];
return 0;
}
- 15
- 18
- garbage value
- compile time error
Answer
4
(Explanation: The conversion is invalid in this array. So it will arise error. The following compilation error will be raised: cannot convert from ‘int *’ to ‘int’
This is because &a,&b and &c represent int* whereas the array defined is of int type.)
Q27 : What is the output of this program?
#include <iostream>
using namespace std;
int main()
{
int arr[] = {4, 5, 6, 7};
int *p = (arr + 1);
cout << *p;
return 0;
}
- 4
- 5
- 6
- 7
Answer
- 2
(Explanation: In this program, we are making the pointer point to next value and printing it.)
Q 28 : What is the output of this program?
#include <iostream>
using namespace std;
int main()
{
int arr[] = {4, 5, 6, 7};
int *p = (arr + 1);
cout << *arr + 9;
return 0;
}
- 12
- 5
- 13
- error
Answer
3
(Explanation: In this program, we are adding the value 9 to the initial value of the array, So it’s printing as 13.)
Q 29 : What are the parts of the literal constants?
- integer numerals
- floating-point numerals
- strings and boolean values
- all of the mentioned
Answer
4
(Explanation: Because these are the types used to declare variables and so these can be declared as constants.)
Q 30 : How are the constants declared?
- const keyword
- #define preprocessor
- both const keyword and #define preprocessor
- none of the mentioned
Answer
3
(Explanation: The const will declare with a specific type value and #define is used to declare user-defined constants.)
Q 31: Implement a void function F that takes pointers to two arrays of integers (A and B) and a size N as parameters. It then populates B where B[i] is the product of all A[j] where j != i.
For example: If A = {2, 1, 5, 9}, then B would be {45, 90, 18, 10}.
Answer
void F(int* A, int* B, int N)
{
int m = 1;
for (int i = 0; i < N; ++i) {
m *= A[i];
}
for (int i = 0; i < N; ++i) {
B[i] = m / A[i];
}
}
Q 32 : When you should use virtual inheritance?
Answer
While it’s ideal to avoid virtual inheritance altogether (you should know how your class is going to be used) having a solid understanding of how virtual inheritance works is still important:
So when you have a class (class A) which inherits from 2 parents (B and C), both of which share a parent (class D), as demonstrated below:
#include <iostream>
class D {
public:
void foo() {
std::cout << “Foooooo” << std::endl;
}
};
class C: public D {
};
class B: public D {
};
class A: public B, public C {
};
int main(int argc, const char * argv[]) {
A a;
a.foo();
}
Q 33 : Is there a difference between class and struct?
Answer
The only difference between a class and struct are the access modifiers. Struct members are public by default; class members are private. It is good practice to use classes when you need an object that has methods and structs when you have a simple data object.
Q34 : What is the output of the following code:
#include <iostream>
int main(int argc, const char * argv[]) { int a[] = {1, 2, 3, 4, 5, 6};
std::cout << (1 + 3)[a] – a[0] + (a + 1)[2];
}
Answer
The above will output 8, since:
(1+3)[a] is the same as a[1+3] == 5
a[0] == 1
(a + 1)[2] is the same as a[3] == 4
This question is testing pointer arithmetic knowledge, and the magic behind square brackets with pointers.
While some might argue that this isn’t a valuable question as it appears to only test the capability of reading C constructs, it’s still important for a candidate to be able to work through it mentally; it’s not an answer they’re expected to know off the top of their head, but one where they talk about what conclusion they reach and how.
Q35 : Explain the volatile and mutable keywords.
Answer
The volatile keyword informs the compiler that a variable may change without the compiler knowing it.
Variables that are declared as volatile will not be cached by the compiler, and will thus always be read from memory.
The mutable keyword can be used for class member variables. Mutable variables are allowed to change from within const member functions of the class.
Q 36 : How many times will this loop execute? Explain your answer.
unsigned char half_limit = 150;
for (unsigned char i = 0; i < 2 * half_limit; ++i)
{
// do something;
}
Answer
If you said 300, you would have been correct if it had been declared as an int. However, since i was declared as an unsigned char, the corrct answer is that this code will result in an infinite loop.
The expression 2 * half_limit will get promoted to an int (based on C++ conversion rules) and will have a value of 300. However, since i is an unsigned char, it is rerepsented by an 8-bit value which, after reaching 255, will overflow (so it will go back to 0) and the loop will therefore go on forever.
Q37 : Are you allowed to have a static const member function? Explain your answer.
Answer
A const member function is one which isn’t allowed to modify the members of the object for which it is called. A static member function is one which can’t be called for a specific object.
Thus, the const modifier for a static member function is meaningless, because there is no object associated with the call.
A more detailed explanation of this reason comes from the C programming language. In C, there were no classes and member functions, so all functions were global. A member function call is translated to a global function call. Consider a member function like this:
void foo(int i);
A call like this:
obj.foo(10);
…is translated to this:
foo(&obj, 10);
This means that the member function foo has a hidden first argument of type T*:
void foo(T* const this, int i);
If a member function is const, this is of type const T* const this:
void foo(const T* const this, int i);
Static member functions don’t have such a hidden argument, so there is no this pointer to be const or not.
Q 38 : What is a storage class?
Answer
A class that specifies the life and scope of its variables and functions is called a storage class.
In C++ following the storage classes are supported: auto, static, register, extern, and mutable.
Note, however, that the keyword register was deprecated in C++11.
In C++17, it was removed and reserved for future use.
Q 39 : How can a C function be called in a C++ program?
Answer
Using an extern “C” declaration: //C code
void func(int i)
{
//code
}
void print(int i)
{
//code
}
//C++ code
extern “C”{
void func(int i);
void print(int i);
}
void myfunc(int i)
{
func(i);
print(i);
}
Q 40 :What is a nested loop?
Answer
A nested loop is a loop that runs within another loop. Put it in another sense, you have an inner loop that is inside an outer loop.
In this scenario, the inner loop performed a number of times as specified by the outer loop.
For each turn on the outer loop, the inner loop is first performed.
Q 41 :What are linked lists?
Answer
A linked list is composed of nodes that are connected with another.
In C programming linked lists are created using pointers. Using linked lists is one efficient way of utilizing memory for storage.
Q 42 :What are reserved words?
Answer
Reserved words are words that are part of the standard C language library.
This means that reserved words have special meaning and therefore cannot be used for purpose other than what it is originally intended for.
Examples of reserved words are int, void and return.
Q 43 : What is the difference between method overloading and method overriding?
Answer
- Overloading a method (or function) in C++ is the ability for functions of the same name to be defined as long as these methods have different signatures ( different set of parameters).
- Method overriding is the ability of the inherited class rewriting the virtual method of the base class.
Q 44 : What is the output of this program?
#include <iostream>
using namespace std;
#define PI 3.14159
int main ()
{
float r = 2;
float circle;
circle = 2 * PI * r;
cout << circle;
return 0;
}
- 5664
- 5664
- 10
- compile time error
Answer
1 (Explanation: In this program, we are finding the area of the circle by using concern formula.)
Q45 : What do you mean by early binding?
Answer
Early binding refers to the events that occur at compile time.
Early binding occurs when all information needed to call a function is known at compile time.
Examples of early binding include normal function calls, overloaded function calls, and overloaded operators.
The advantage of early binding is efficiency.
Q 46 : Which of the following statement is not true about preprocessor directives?
- These are lines read and processed by the preprocessor
- They do not produce any code by themselves
- These must be written on their own line
- They end with a semicolon
Answer
4. (Explanation: No terminating character required for preprocessor directives statements.)
Q 47 : Regarding the following statement which of the statements is true?
const int a = 100;
- Declares a variable a with 100 as its initial value
- Declares a construction a with 100 as its initial value
- Declares a constant a whose value will be 100
- Constructs an integer type variable with an as identifier and 100 as the value
Answer
3 (Explanation: Because the const is used to declare changeable values only.)
Q48 :What is the main purpose of overloading operators?
Answer
-The main purpose of operator overloading is to minimize the chances of occurance of errors in a class that is using the overload operators.
-It also helps in redefining the functionalities of the operators to improve their performance.
-Operator overloading also makes the program clearer, readable and more understandable by using common operators, such as +, =, and [].
Q 49 :The difference between x and ‘x’ is
- The first one refers to a variable whose identifier is x and the second one refers to the character constant x
- The first one is a character constant x and the second one is the string literal x
- Both are same
- None of the mentioned
Answer
1 (Explanation: In a C++ code, names with quotes like ‘x’ represent a character or string(in case of collection of characters) whereas without quotes they represent an identifier.
Q50 :What is difference between C++ and Java?
Answer
- C++ has pointers Java does not.
- Java is the platform independent as it works on any type of operating systems.
- Java has no pointers where c ++ has pointers.
- Java has garbage collection C++ does not.
C++ Interview Questions And Answers PDF
You can also download c++ interview questions and answers pdf from the link below :
C++ Interview Questions & Answers
Hope the above will help you in preparing for angular interviews.
Q21, the answer is (b)???