vector<int> v(22);
bool b = (v[6]);
printf("%d", !b);
False
0
1
This code has an error.
Q2. Which of the following is a reason why using this line is considered a bad practice? (Alternative: Why is using this line considered a bad practice?)
usingnamespace std;
The compiled code is always bigger because of all of the imported symbols.
If the code uses a function defined in two different libraries with the same prototype but possibly with different implementations, there will be a compilation error due to ambiguity.
It automatically includes all header files in the standard library (cstdint, cstdlib, cstdio, iostream, etc).
It causes the compiler to enforce the exclusive inclusion of header files belonging to the standard library, generating a compilation error when a different header file is included.
Q5. Which of the following is a true statement about the difference between pointers and iterators?
While pointers are variables that hold memory addresses, iterators are generic functions used to traverse containers. This function allows the programmer to implement read and write code as the container is traversed.
Incrementing an iterator always means accessing the next element in the container(if any), no matter the container. Incrementing the pointer means pointing to the next element in memory, not always the next element.
Pointers are variables that hold memory address whereas iterator is unsigned integers that refer to offsets in arrays.
All iterators are implemented with pointers so all iterators are pointers but not all pointers are iterators.
Q9. Which of the following is not a difference between a class and a struct?
Because structs are part of the C programming language, there is some complexity between C and C++ structs. This is not the case with classes.
Classes may have member functions; structs are private.
The default access specifier for members of a struct is public, whereas, for members of the class, it is private.
Template type parameters can be declared with classes, but not with the struct keyword.
Templates can be used with both classes and structs
RefernceReference
Q10. Suppose you need to keep a data struct with permission to access some resource based on the days of the week, but you can't use a bool variable for each day. You need to use one bit per day of the week. Which of the following is a correct implementation of a structure with bit fields for this application?
A
typedefstruct {int sunday:1;
int monday:1;
// more daysint friday:1;
int saturday:1;
} weekdays;
B
typedefchar[7]: weekdays;
C
typedefstruct { bit sunday:1;
bit monday:1;
// more days bit friday:1;
bit saturday:1;
} weekdays;
D
typedefstruct { bit sunday;
bit monday;
// more days bit friday;
bit saturday;
} weekdays;
ReferenceNOTE: Correct syntax is that each variable size is 1 bit. bit is not a type in C++.
Q11. What is an lvalue?
It's a constant expression, meaning an expression composed of constants and operations.
It's an expression that represents an object with an address.
It's an expression suitable for the left-hand side operand in a binary operation.
It's a location value, meaning a memory address suitable for assigning to a pointer or reference.
Q12. What does auto type specifier do in this line of code (since C++11)?
auto x = 4000.22;
It specifies that the type of x will be deduced from the initializer - in this case, double.
It specifies that the type of x is automatic meaning that it can be assigned different types of data throughout the program.
It specifies that x is a variable with automatic storage duration.
It specifies that more memory will be allocated for x in case it needs more space, avoiding loss of data due to overflow.
Q13. A class template is a _?
class written with the generic programming paradigm, specifying behavior in terms of type parameter rather than specific type.
blank superclass intended for inheritance and polymorphism.
class that only consists of a member variable, with no constructor, destructor, or member functions.
skeleton source code for a class where the programmer has to fill in specific parts to define the data types and algorithms used.
#include<iostream>intmain(){
int x=10, y=20;
std::cout << "x = " << x++ << " and y = " << --y << std::endl;
std::cout << "x = " << x-- << " and y = " << ++y << std::endl;
return(0);
}
x = 10 and y = 20 x = 11 and y = 19
x = 11 and y = 19 x = 10 and y = 20
x = 10 and y = 19 x = 11 and y = 20
x = 11 and y = 20 x = 10 and y = 19
Q16. What is the meaning of the two parts specified between parentheses in a range-based for loop, separated by a colon?
The first is a variable declaration that will hold an element in a sequence. The second is the sequence to traverse.
The first is an iterator, and the second is the increment value to be added to the iterator.
The first is the iterating variable. The second is a std::pair that specifies the range (start and end) in which the variable will iterate.
The first is a container object. The second is a std::pair that specifies the range (start and end) in which the elements will be accessed within the loop.
intget_length(char *str){
int count=0;
while((*str)++)
count++;
return count;
}
D
intget_length(char *str){
int count=0;
while(str++)
count++;
return count;
}
Q21. Which STL class is the best fit for implementing a collection of data that is always ordered so that the pop operation always gets the greatest of the elements? Suppose you are interested only in push and pop operations.
std::list
std::vector
std::priority_queue
std::map
Q22. What is the meaning of the three sections specified between parentheses in a for loop separated by semicolons?
The first is the iterating variable name, the second is the number of times to iterate, and the third is the desired increment or decrement (specified with a signed integer).
The first is the initialization block, the second is the condition to iterate, and the third is the increment block.
The first is the iterating variable, the second is the container in which it should operate, and the third is an exit condition to abort at any time.
The first is the iterating variable name, the second is the starting value for the iterating variable, and the third is the stop value (the last value plus one).
Q23. What does this code print?
int i = 0;
printf("%d", i++);
printf("%d", i--);
printf("%d", ++i);
printf("%d", --i);
int c=3; char d='A';
std::printf("c is %d and d is %c",c,d);
c is d and d is c
c is A and d is 3
c is 3 and d is A
c is c and d is d
Q26. What is the output of this code?
printf("1/2 = %f",(float)(1/2));
1/2 = 0.499999
1/2 = 0
1/2 = 0.000000
1/2 = 0.5
Q27. What is the difference between a public and a private class member?
Public members are the same as global variables, so every part of the code has access to them. Private members are the same as automatic variables, so only their class has access to them.
Public members are made accessible to any running application. Private members are made accessible only to the application where the object is instantiated.
Public members will be compiled as shared variables in a multithreaded environment. Private members will be compiled as Thread-local variables.
Public members can be accessed by any function. Private members can be accessed only by the same class's member functions and the friends of the class.
Q28. What is the value of x after executing this code?
int x=10, a=-3;
x+=a;
3
7
-3
13
Q29. Which statement is true?
Only classes can have member variables and methods.
C++ supports multiple inheritance.
C++ supports only single inheritance.
Only structs can inherit.
Q30. Consider a pointer to void, named ptr, which has been set to point to a floating point variable g. Which choice is a valid way to dereference ptr to assign its pointed value to a float variable f later in the program?
float g;
void *ptr=&g;
float f=*(float)ptr;
float f=(float *)ptr;
float f=(float)*ptr;
float f=*(float *)ptr;
Q31. What is the .* operator and what does it do?
It is the same as the class member access operator, or arrow operator (->), which allows you to access a member of an object through a pointer to the object.
It is the pointer to the member operator, and it allows you to access a member of an object through a pointer to that specific class member.
It is the member access with an address of the operator, which returns the address of a class or struct member.
It is a combination of the member access operator (.) and the dereference operator (*), so it allows you to access the object that a member pointer points to.
Q32. For these declarations, which choice shows four equivalent ways to assign the character "y" in the string to a char variable c?
char buff[50] = "strings as arrays of characters are fun!"char *str = buff+11;
char c;
A
c = buff[16];
c = str[5];
c = *(buff+16);
c = *(str+5);
B
c = *(buff[15]);
c = *(str[4]);
c = buff+15;
c = str+4;
C
c = buff[15];
c = str[4];
c = *(buff+15);
c = *(str+4);
D
c = *(buff[16]);
c = *(str[5]);
c = buff+16;
c = str+5;
Q33. Which choice is the correct declaration for the class named Dog, derived from the Animal class?
classAnimal{//....}
A
classDog :: public Animal {
//....};
B
classDog :public Animal {
//....};
C
publicclassAnimal :: Dog {
//....};
D
publicclassDogextendsAnimal {//....};
Q34. What is the output of this code given below?
#include<cstdio>usingnamespace std;
intmain(){
char c = 255;
if(c>10)
printf("c = %i, which is greater than 10", c);
elseprintf("c = %i, which is less than 10", c);
return0;
}
c = -1, which is less than 10
c = 255, which is greater than 10
c = -1, which is greater than 10
c = 255, which is less than 10
Technically, whether a char is signed or unsigned is implementation-defined;
in the latter case, the second answer would be correct.
Reference
Q35. How can C++ code call a C function?
by simply calling the C code
There is no way for C++ to call a C function
by using extern "C"
by importing the source C code
Q36. Which choice is not a valid type definition of a structure that contains x and y coordinates as integers, and that can be used exactly as shown for the variable named center?
coord center;
center.x = 5;
center.y = 3;
A
typedefstructcoord {int x;
int y;
};
B
typedefstructcoord {int x;
int y;
} coord;
C
typedefstruct {int x;
int y;
} coord;
D
structcoord {int x;
int y;
};
typedefstructcoordcoord;
Q37. Which choice does not produce the same output as this code snippet? Assume the variable i will not be used anywhere else in the code.
for (i=1;i<10;i++){
cout<<i<<endl;
}
A
i=1;
while(i<10){
cout<<++i<<endl;
}
B
for (int i:{1,2,3,4,5,6,7,8,9}) {
cout<<i<<endl;
}
C
i = 1;
do {
cout<<i++<<endl;
} while(i<10);
D
i = 1;
loop:
cout<<i++<<endl;
if(i<10) goto loop;
Q38. What does this part of a main.cpp file do?
#include"library.h"
It causes the toolchain to compile all the contents of library.h so that its executable code is available when needed by the final application.
It cherry-picks library.h for the declarations and definitions of all data and functions used in the remainder of the source file main.cpp, finally replacing the #include directive with those declarations and definitions.
It informs the linker that some functions or data used in the source file main.cpp are contained in library.h, so that they can be called in run time. This is also known as dynamic linking.
It causes the replacement of the #include directive by the entire contents of the source file library.h. This is similar to the Copy-Paste operation of library.h into main.cpp.
Q39. Consider this function declaration of is_even, which takes in an integer and returns true if the argument is an even number and false otherwise. Which declarations are correct for overloaded versions of that function to support floating point numbers and string representations of numbers?
Q47. Which of the following STL classes is the best fit for implementing a phonebook? Suppose each entry contains a name and a phone number, with no duplicates, and you want to have a lookup by name.
Q49. Which of the following is not a consequence of declaring the member variable count of my_class as static? / Alt.: Which statement is true when declaring the member variable count as static?
classmy_class {public: staticint count;
}
The variable cannot be modified by any part of the code in the same application or thread. However, other threads may modify it.
The variable exists even when no objects of the class have been defined so it can be modified at any point in the source code.
The variable is allocated only once, regardless of how many objects are instantiated because it is bound to the class itself, not its instances.
All objects that try to access their count member variable actually refer to the only class-bound static count variable.
Yes, it causes a compiler error because the colon character is not allowed in struct definitions.
No, and child_t is a type defined as a structure with bit fields. It has 4 bits for age and 1 bit for gender in the first byte, and 2 bits for size in the second byte.
Yes, it causes a compiler error because there is an unnamed field.
Yes, it causes a compiler error because one field is defined as having a size of 0.
It allows the programmer to write the necessary code to free the resources acquired by the object prior to deleting the object itself.
It deletes an object. One example of a destructor is the delete() function.
It terminates a program. This may be achieved as a regular function call or as an exception.
There are no destructors in C++.
Q63. What is one benefit of declaring the parameter as a const reference instead of declaring it as a regular object?
intcalculateMedian(const my_array& a)
Actually, objects cannot be passed as regular variables, because they require a constructor call. Therefore, a const reference is the only way to pass class instances to functions.
There are no benefits because a reference and an object are treated as the same thing.
The const qualifier forbids the code to modify the argument, so the programmer can rest assured that the source object will remain unchanged. / Alt.: The argument is passed as a reference, so if the passed my_array object is large, the program will require less time and memory.
The argument is passed as a reference, so the function receives a copy that can be modified without affecting the original variable.
Q68. Other than shifting bits to the left, what is the << operator used for?
shifting characters to the left in a string.
inserting characters into an output stream like std::cout.
comparing floating point numbers as less-than.
assigning a variable to a reference.
Q69. Which choice is a reason to specify the type of a pointer instead of using void *, which works as a pointer to any type?
The compiler needs the data type to make sure that the pointer is not going to be used on illegal non-pointable types such as functions, labels, pointers, and references.
void * does not work for any type. The language does not allow assigning anything other than void to a pointer to void *.
The compiler needs the data type to know how much memory to allocate for the pointer because different data types require different pointer lengths.
Yes, it causes a compiler error because one field is defined as having a size of 0.
Q74. Given these records in a map, how will you update the value for the key "Sinead" to 22?
marks["Sinead"] = 22
marks["Sinead"].22
marks["Sinead"] -> 22
marks["Sinead"].value = 22
Q75. Why can the std::sort receive a function object as one of its parameters?
The std::sort function is a template. The programmer is free to enter the sorting algorithm in a function object as an argument.
Actually, std::sort takes only one argument, which is the container to be sorted.
std::sort operates on a template container. The compiler does not know how to relationally compare the values it contains, so a function must be provided to do the comparison.
std::sort will use the parameter function as an error handler. The function will be called if an error occurs.
Q76. What will happen when you execute this code snippet?
#include <iostream>
int main() {
float a = 5.51;
int b = static_cast<int>(a);
std::cout << b;
}
6 will be printed on standard output, with no compilation warnings generated.
5 will be printed on standard output, with no compilation warnings generated.
6 will be printed on standard output, with compilation warnings generated.
5 will be printed on standard output, with compilation warnings generated.
Q77. Which access specifier does not allow class members to be accessed from outside the class, but allows them to be accessed by derived classes?
guarded
protected
public
private
Q78. The default executable generation on UNIX for a C++ program is _
a.exe
a
a.out
out.a
Q79. What will be the output of the following program?
#include<iostream>usingnamespace std;
intmain(){
int a=1;
cout<<(a++)*(++a)<<endl;
return0;
}
1
2
3
6
Q80. What does "c" stand for in cout and cin?
compiler
console
character
standard namespace
Q81. What is the use of tellp()?
Current Input Pointer position
Current Output Pointer position
Last Input Pointer position
Last Output Pointer position
Q82. What is callback function?
Pointer for a pointer
Pointer for a function
function for a pointer
function for a class
Q83. What is the correct syntax to output "Hello World" in C++?
cout << "Hello World";
System.out.println("Hello World");
print("Hello World");
Console.WriteLine("Hello World");```
Q84. How many categories of iterators are there in C++?
4
3
7
5
Q85. What is the meaning of base class in C++ ?
It inherits other class
It has a pointer variable
It is the first class declared
Another class got inherited from this class
Q86. The size of C++ objects is expressed in terms of multiples of the size of a ** and the size of a char is **.
char, 4
float, 8
int, 1
char, 1
Q87. Implementation-dependent aspects about an implementation can be found in
<numeric>
<limit>
<limits>
<implementation>
Q88. What is a default constructor?
a constructor that can be used with no arguments
a constructor that does not have a return value
a constructor that is used by multiple classes
a constructor that initializes all members of a class
Q89. When protecting a header file, why would you use '#pragma once' instead of 'include' guard?
There is no reason to choose because they serve different purposes
An include guard uses a macro to achieve single inclusion, but the compiler cannot prevent the programmer from defining that macro elsewhere, which would result in no inclusion at all
defining that macro elsewhere, which would result in no inclusion at all
'#pragma once' guarantees that the header code will never be changed because it is enforced by the compiler
Include guards refer to the header file in the file system, not to the code, so they are not helpful if the header file exists
more than once in a project. This is not a problem with '#pragma once'
Q90. Which of the following statements is valid?
We can create a new C++ operator.
We can change the precedence of the C++ operator.
We can not change the operator templates.
We can change the associativity of the C++ operators.
Q91. Which of the following is/are automatically added to every class, if we do not write our own?
Copy Constructor
Assignment Operator
A constructor without any parameter
All of the above
Q92. The if-else statement can be replaced by which operator?
certain structure
choosing structure
selective structure
None of the Above
Q93. Which choice would be a recursive solution to the factorial n! problem?
voidfact(int n){
if (n <= 0)
return0;
elsereturn1;
}
Q94. A class destructor can be called when a variety of situations occur. Which choice is not one of those situations?
The program is terminated. This calls the destructor of static duration objects.
The delete () function is called for an object pointer assigned with the new operator.
The garbage collector detects that an object is no longer going to be used.
An automatic storage duration object goes out of scope.
Q95. You are designing a foreign exchange payments system in C++, You need to model a transaction of a currency that has an integer as its quantity and a float as its price. You then want to declare an actual object of this type. How will you achieve this?
A
structcurrencyDeal {float price;
int quantity;
};
currencyDeal firstDeal;
B
unioncurrencyDeal {float price;
int quantity;
};
currencyDeal firstDeal;
C
structcurrencyDeal {float price;
int quantity;
};
D
unioncurrencyDeal {float price;
int quantity;
};
Q96. What will happen if you attempt to call this function with checkConcatThreshold("a");?
intcheckConcatThreshold(string a, string b){
return (a + b).length () > 120;
}
A compilation warning will occur and the second argument will be given a default value of b.
A compilation warning will occur and the second argument will be given a default value of the empty string.
A compilation error will occur.
No compilation errors will occur and no compilation warnings will occur.
Q97. You need to define a C++ lambda function. You want the function to have access to only the variables that are local to it. The function should receive a single parameter, and a name, and construct a simple greeting. How will you achieve this?
A
auto myVeryFirstLambda = [=] (string name) {
return"Hello " + name + "!";
};
Q98. What is the value of X after running this code?
int x=10, a=-3;
X+=a;
-3
7
13
3
Explanation :+= means increasing value. So x += a is equivalent to x = x + a
Q99. Once you are done writing to a file, what method will you call on the ofstream to notify the operating system?
printout()
close()
destroy()
flush()
Q100. Which choice is not a C++ keyword?
static_assert
reinterpret_cast
comPl
alignas
Q101. The size_in_bits function seems to take any type of parameter. This can be done by overloading the function, or by letting the compiler take care of it by writing a template. Which choice is an implementation of that template?
Now here we are supposed to implement a stack data structure that follows the FILO or (First IN Last Out) principle,
stack.push() -> pushes an element into the from the end array.
stack.pop() -> removes an element from the end of the array.
stack.top() -> Just gives us the topmost element of the array.
Now following the sequences of push and pop: [1,2,3] then pop function is used,
The newly formed array is: [1,2,4] then the top is used to retrieve the topmost element '4' then again the pop function is used which removes 4.
thus, the resulting array is: 1,2.
Then it prints the topmost element (ie: 2).
Q105. Which choice is a valid way to overload the ternary conditional operator?
Q111. Consider the following code segment. What will be the output?
#include<iostream>#include<algorithm>usingnamespace std;
intmain(){
int element[5];
for(int i = 1; i <= 5; i++)
*(element + i - 1) = i * 5;
rotate(element, element + 4, element + 5);
rotate(element, element + 1, element + 4);
for (int i = 0; i < 5; ++i)
cout << element[i] << " ";
return0;
}
Q113. Consider the following code segment. Choose the appropriate option to fill in the blank at LINE-1, such that the output of the code would be: a C++ Program.
Q119. Consider the following code segment. Which line/s will give you an error?
#include<iostream>#define X 1usingnamespace std;
intmain(){
int i;
constint i1 = 2;
constint i2 = i1; //LINE-1i2 = X;
i = i1;
i1 = i;
return0;
//LINE-2//LINE-3//LINE-4}
LINE-1
LINE-2
LINE-3
LINE-4
Q120. Consider the following code segment. What will be the output/error?
#include<iostream>usingnamespace std;
intmain(){
int a = 5;
int &b = a+1;
a = a*b;
cout << a << " " << b;
return0;
}
36
30
25
Compilation Error: invalid initialization of non-const reference
#Detailed explanation:
The error is occurring because it is trying to create a reference to a temporary value. In the line int &b = a+1; we are attempting to create a reference b to the result of the expression a + 1, which is a temporary value. References must be bound to an actual object, not a temporary value or an expression that does not have a memory location.
Q121. Consider the following code segment. What will be the output?
#include<iostream>usingnamespace std;
int& func(int& i){ //LINE-1return i = i+5;
}
intmain(){
int x = 1, y = 2;
int& z = func(x);
cout << x << " " << z << " ";
func(x) = y;
cout << x << " " << z;
return0;
}
Q122. Consider the following code segment. Choose the appropriate option to fill in the blanks at LINE-1, such that the output of the code would be: 300 20000.
#include<iostream>usingnamespace std;
voidcompute(int n1, int n2, ________, ________){ //LINE-1n3 = n1 + n2;
*n4 = n1 * n2;
}
intmain(){
int a = 100, b = 200, c = 0, d = 0;
compute(a, b, c, &d); //LINE-2cout << c << ", ";
cout << d;
return0;
}
int n3, int* n4
int& n3, int *n4
int* n3, int* n4
int& n3, int& n4
Q123. Consider the following code segment. What will be the output/error?
#include<iostream>usingnamespace std;
intmain(){
int a = 2, *b;
*b = 5;
int * const ptr; // LINE-1// LINE-2ptr = b;
cout << *ptr;
return0;
}
<garbage value>
5
Compilation Error at LINE-1: uninitialized const ’ptr’
Compilation Error at LINE-2: assignment of read-only variable ’ptr’
Q124. Consider the following code segment. What will be the output/error?
#include<iostream>usingnamespace std;
voidfun(int a = 5){ cout << a << endl; }
//LINE-1intfun(int x = 10){ cout << x << endl; return0; } //LINE-2intmain(){
fun();
return0;
}
5
10
5
Compilation error at LINE-2: ambiguating new declaration of ’int fun(int)’
Q125. Consider the following code segment. Fill in the blank at LINE-1 such that the program will print 5 + i3
Q127. Consider the following class. Fill in the blanks with proper access specifiers so that member y can be accessed from outside of the class but member x cannot be accessed.
classTest{________:
int x;
________:
int y;
/* Some more code */};
public, public
public, private
private, public
private, private
Q128. Which C++ Standard did add in-class default member initializers?
C++98
C++11
C++14
C++17.
Q129. Can you use auto type deduction for non-static data members?
Yes, since C++11
No
Yes, since C++20
Q130. Do you need to define a static inline data member in a cpp file?
No, the definition happens at the same place where a static inline member is declared.
Yes, the compiler needs the definition in a cpp file.
Yes, the compiler needs a definition in all translation units that use this variable.
%OPTION% A template metaprogram is a high-level programming language.
%OPTION% It refers to metaprogramming that uses templates in C++.
%OPTION% It's a type of user interface design pattern.
%OPTION% A template metaprogram is a compile-time computation, where templates and template specialization are used to perform computations at compile time.
Q158.Identify the correct example for a pre-increment operator.
++i
i++
--i
+i
Q159. What will be the output of following code?
{% raw %}
int matrix[3][3] = {{1, 2, 3},{4, 5, 6},{7, 8, 9}};
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
int a = mat[i][j];
mat[i][j] = mat[j][i];
mat[j][i] = a;
}
}
{% endraw %}