C++ MCQs - Part II
The multiple-choice queries and solutions (MCQs) regarding "C++ Programming" concentrate on various aspects of C++ Programming encompassing a wide range of subjects. These subjects are selected from a compilation of the most reputable and top-quality books on C++ Programming.
1) What keyword is utilized to incorporate assembly code within a C++ program?
- Infeasible
- Specific to the compiler
Description:
In C++, developers can utilize the "asm" keyword to incorporate assembly code within an inline function. To delve deeper into this concept, let's examine the following illustration:
Sample demo of "asm" keyword use:
#include<bits/stdc++.h>
usingnamespacestd;
intmain()
{
// generates interrupt 5
asmint5;
return0;
}
2) Which one of the following is considered as the least safe typecasting in C++?
- const_cast
- reinterpret_cast
- dynamic_cast
- None of the above
Typecasting, in programming, involves converting one data type into another. In C++ programming, the reinterpret_ cast is identified as the least secure method of typecasting. Hence, the appropriate choice is option B.
3) ISO/IEC 14882:1998 addresses which version of C++?
- C++ 98
- C++ 93
- C++ 0
- C++ 03
Description: The "ISO / IEX14882:1998 standardizes the C++ 0x iteration of the C++ programming language, which is commonly referred to as "C++98". Therefore, the accurate choice is option A.
4) Which one of the following correctly refers to the command line arguments?
- Arguments passed to the main function
- Arguments passed to the structure-function
- Arguments passed to the class functions
- Arguments passed to any functions
Command-line arguments are commonly provided to the main function, which typically marks the starting point of a program's execution.
5) What result will be displayed when the provided arguments are passed through the terminal and the below C++ code is executed?
#include <iostream>
usingnamespace std;
int main(intargc, charconst*argv[])
{
for(int i=0;i<argc;i++)
cout<<argv[i]<<"\n";
}
================commands===============
$ g++ program.cpp-o output
$ ./output Hello World
=======================================
- ./output Hello World
- Hello World
- program.cpp Hello
- program.cpp Hello World
As illustrated in the provided C++ code snippet, the objective is to showcase all the arguments passed through the command line. Thus, the array contains "./output," "Hello," and "World" as evidenced in the output. You may wonder why the initial string is not "program.cpp." This is because the first string denotes the name of the program's output file. Hence, the accurate response is A.
6) Which of the following methods can be considered the correct and efficient way of handling arguments with spaces?
- Use single quotes
- Either single or double quotes
- Use double quotes
- There is no way of handling arguments with space
We have the flexibility to utilize either single or double quotation marks to manage command-line arguments that include spaces.
7) According to you, which of the following is the correct way to interpret Hello World as a single argument?
- $ ./output 'Hello World'
- $ ./output "Hello World"
- Only 1
- Only 2
- Neither 1 nor 2
- Both 1 and 2
Typically, both single and double quotation marks are commonly employed to interpret words separated by spaces as a single argument.
8) Which of the following statements is correct about the second parameter of the main function?
- The second parameter is an array of character pointers
- The first string of the list is the name of the program's output file
- The string in the list are separated by space in the terminal
- All of the mentioned
All the statements mentioned above pertain to the second parameter. Thus, option D is the accurate response.
9) Which of the following is correct about the first parameter of the "main" function?
- The first argument is of int type
- Stores the count of command-line arguments
- The first argument is non-negative
- All of the mentioned
All the statements provided in the previous sections hold true for the initial argument of the "main" function. This first parameter is of a non-negative integer data type and holds the number of arguments passed through the command line.
10) Which of the provided options displays the accurate result of the subsequent C++ code?
#include<iostream>
usingnamespace std;
int main()
{
int x=5;
int y=5;
auto check =[&x]()
{
x =10;
y =10;
}
check();
cout<<"Value of x: "<<x<<endl;
cout<<"Value of y: "<<y<<endl;
return0;
}
- It will result in an Error
- Value of a: 10
- Value of a: 5
- It will obtain Segmentation fault
Upon examining the provided program, it becomes apparent that the lambda expression does not retain the value of the variable "y." Instead, it attempts to retrieve the value of the external variable y. Consequently, executing the aforementioned program will generate an error. Hence, the accurate response is option A.
11) The following C++ code will output the result of a specific operation.
#include<iostream>
usingnamespace std;
int main()
{
int a =5;
auto check =[](int x)
{
if(x ==0)
returnfalse;
else
returntrue;
};
cout<<check(a)<<endl;
return0;
}
- Segmentation fault
- Error
The preceding code is completely correct. Within that code snippet, you can see that we have explicitly mentioned the data type of the expression. Therefore, the code will typically function as expected since it can determine the return type of the expression.
12) Which of the following is usually represented by the first parameters of the main function?
- Number of command-line arguments
- List of command-line arguments
- Dictionary of command-line arguments
- Stack of command-line arguments
Typically, the initial parameter within the main function, or alternatively referred to as the primary argument of the main function, represents the count of command-line arguments received by it.
13) What will happen when we move the try block far away from catch block?
- Reduces the amount of code in the cache
- Increases the amount of code in the cache
- Don't alter anything
- Increases the amount of code
Compilers might attempt to relocate the catch-code away from the try-code, aiming to minimize the code stored in the cache, resulting in an improvement in performance.
14) The output of the C++ code provided below will be determined by the logic implemented within the code.
#include <iostream>
#include <string>
usingnamespace std;
int main ()
{
intnum=3;
stringstr_bad="wrong number used";
try
{
if( num ==1)
{
throw5;
}
if( num ==2)
{
throw1.1f;
}
if( num !=1|| num !=2)
{
throwstr_bad;
}
}
catch(int a)
{
cout<<"Exception is: "<< a <<endl;
}
catch(float b)
{
cout<<"Exception is: "<< b <<endl;
}
catch(...)
{
cout<<str_bad<<endl;
}
return0;
}
- Exception is 5
- Exception is 1.1f
- Exception is 1.6g
- Wrong number used
As illustrated in the provided code snippet, assigning the value "3" to the variable "num" triggers an exception labeled "incorrect number used." Therefore, the accurate solution is option D.
What is the output of the given C++ code snippet?
#include <iostream>
#include <exception>
usingnamespace std;
int main ()
{
try
{
double* i=newdouble[1000];
cout<<"Memory allocated";
}
catch(exception& e)
{
cout<<"Exception arised: "<<e.what()<<endl;
}
return0;
}
- Depends on the computer memory
- Memory will be allocated
- Exception raised
- Memory allocatedExceptionarised
In this program, memory allocation occurs only if the system has adequate memory available. As a result, the allocation process is entirely dependent on the system's memory capacity.
Output:
$ g++ expef.cpp
$ a.out
Memory allocated ( if enough memory is available in the system)
16) Which one of the following given statements is correct about the increment operator?
- Increment operator(or ++ ) usually adds 2 to its operand
- Decrement operator ++ subtracts 1 to its operand
- Decrement operator ++ subtracts 3 to its operand
- Increment operator (or ++ ) usually adds 1 to its operand
The Increment operator (++) is a fundamental operator in C++ programming. Commonly, it is employed in various loop constructs to manipulate the loop counter. Each time the increment operator (++) is triggered, it increases its operand by 1. To grasp this concept better, refer to the example provided below:
Example
#include <iostream>
using namespace std;
int main()
{
intx,i;
i=10;
x=++i;
cout<<"x: "<<x;
cout<<"i: "<<i;
return 0;
}
Output
x: 11i: 11
Examine the provided C++ code snippet below to identify any errors.
Class t
{
virtual void print();
}
- Class " t " should contain data members
- Function print; should be defined
- Function " print; " should be declared as the static function
- There is no error
The provided code above is accurate and contains no errors.
18) Which one of the following statements about the pre-increment is true?
- Pre Incrementisusually faster than the post-increment
- Post-increment is faster than the pre-Increment
- Pre increment is slower than post-increment
- pre decrement is slower than post-increment
Description: Pre-increment is typically more efficient than post-increment as it requires a one-byte instruction compared to the two-byte instruction needed for post-increment.
19) Which of the following concept is used by pre-increment?
- call by value
- call by reference
- queue
- call by name
The pre-increment operator typically employs the concept of "call by reference" where modifications are directly updated in the memory cells or variables.
How many varieties of representation exist within the string?
In C++, there are two main types of string representations available. These include C-style character strings and the string class type in Standard C++.
What output will the provided C++ code produce?
#include <iostream>
#include <cstring>
using namespace std;
int main ()
{
char str1[10] = "Hello";
char str2[10] = "World";
char str3[10];
intlen ;
strcpy( str3, str1);
strcat( str1, str2);
len = strlen(str1);
cout<<len<<endl;
return 0;
}
In the provided code snippet, we are combining the contents of str1 and str2 and then displaying the result.
Consequently, the overall length of the string is determined by its total characters, resulting in a final length of 10. Thus, the accurate choice is C.
22) Which one of the following given methods we usually use to append more than one character at a time?
- Append
- operator+=
- both append & operator+=
- Data
C++ programming language typically enables the addition of additional characters to a string by utilizing either the built-in append method or by employing the overloaded += operator.
What will be the result of f(p, p) when p is set to 5 prior to the function call?
Program
int f(int&x, int c) {
c = c - 1;
if (c == 0) return 1;
x = x + 1;
return f(x, c) * x;
}
Note that the first parameter is passed by reference, whereas the second parameter is passed by value.
- 3024
- 6561
- 55440
- 161051
In this provided C++ code snippet, it is evident that the parameter c is passed by value, while the parameter x is passed by reference. As a result, all functions within the code will work with identical copies of x but distinct copies of c. Hence, the accurate choice is option B.
24) Which one of the following given statements is not true about the references in C++?
- A reference should be initialized whenever it is declared
- A reference cannot refer to a constant value
- A reference cannot be NULL
- Once a reference is created, it cannot be later made to reference another object; it cannot be reset
In C++, it is possible to establish a constant reference that points to a constant value. To delve deeper into this concept, let's examine the provided program as an illustration.
#include<iostream>
using namespace std;
int main()
{
constint x = 10;
constint& ref = x;
cout<< ref;
return 0;
}
Read the provided C++ program below and anticipate the most suitable output it will generate.
#include<iostream>
usingnamespacestd;
int&fun()
{
staticintx = 10;
returnx;
}
intmain()
{
fun() = 30;
cout<< fun();
return0;
}
- It will obtain a compilation error
- It will print 30 as output
- It will print ten as output
- None of the above
Whenever a function returns by reference, it can also be utilized as the lvalue. In the case where x is defined as a static variable, it is shared across function invocations, with the initialization line "static variable x= 10;" being executed just once. As a result, when the function call "fun=30" changes x to 30, the subsequent call "cout<<fun" outputs the updated value. Therefore, the accurate result will be 30.
Read the provided C++ program below and anticipate the most suitable output that the program will produce.
#include<iostream>
usingnamespacestd;
int&fun()
{
intx = 10;
returnx;
}
intmain()
{
fun() = 30;
cout<< fun();
return0;
}
- It may cause the compilation error
- It may cause the runtime error
- It will work fine
- None of the above
As observed in the provided program, returning a reference to a local variable leads to an invalid memory location after the function call concludes. This typically leads to a segmentation fault or a runtime error.
27) Which of the following functions must use the reference?
- Copy constructor
- Destructor
- Parameterized constructor
- None of the above
In most cases, a copy constructor is invoked when an object is transferred by value. It's important to understand that the copy constructor functions as a specific type of function. When an argument is passed by value in a copy constructor, it triggers a call to the copy constructor, creating an endless loop of calls. Consequently, the compiler prohibits passing parameters by value in order to prevent this infinite chain of calls.
Read the provided C++ program below and anticipate the most suitable output that the program will generate.
#include<iostream>
usingnamespacestd;
intmain()
{
intx = 10;
int& ref= x;
ref= 20;
cout<< "x = "<< x <<endl ;
x = 30;
cout<< "ref = "<< ref<<endl;
return0;
}
- x=20 ref=30
- x=20 ref=20
- x=10 ref= 30
- x= 30 ref=30
In the provided code snippet, it's evident that "ref" serves as a substitute for "x". Consequently, alterations made to one will reflect in the other as well. Hence, option A is the accurate choice.
29) Why inline functions are useful?
- Functions are large and contain several nested loops
- Usually, it is small, and we want to avoid the function calls
- The function has several static variables
- All of the above
In most cases, inline functions are compact and commonly serve as replacements for macros, often proving to be more efficient than macros. Therefore, option B is the accurate choice.
30) Which of the following statements is true about the inline functions?
- Macros do not have the returns statement, while inline function has the return statement.
- Usually, the macros are processed by the preprocessor while on the other hand inline functions are processed in the later stages of compilation.
- Inline function usually performs the type checking, whereas macros do not.
- All of the above
In basic terms, inline functions are similar to regular functions, established by users using the "inline" keyword.
Normally, inline functions are concise functions that are expanded by the compiler, with their arguments evaluated only once. Inline functions validate the types of parameters, while macros do not perform any parameter checking.
Nevertheless, macros are typically handled by the preprocessor, while inline functions are processed during later stages of compilation. Another key benefit of inline functions compared to macros is that inline functions can include a return statement, whereas macros cannot. Finally, macros are prone to more bugs and errors, whereas inline functions are more reliable in this aspect.
31) How can a user make a c++class in such a way that the object of that class can be created only by using the new operator, and if the user tries to make the object directly, the program will throw a compiler error?
- By making the destructor private.
- By making the constructor private.
- Not possible
- By making both constructor and destructor private.
Description:
One could develop a C++ program where an object of a class is exclusively instantiated using the "new" operator. If an attempt is made to directly create an object, the compiler would generate an error. To grasp this concept better, you may refer to the provided example below.
Example
// in this program, Objects of test can only be created using new
class Test1
{
private:
~Test1() {}
friend void destructTest1(Test1* );
};
// Only this function can destruct objects of Test1
voiddestructTest(Test1* ptr)
{
deleteptr;
}
int main()
{
// create an object
Test1 *ptr = new Test1;
// destruct the object
destructTest1 (ptr);
return 0;
}
32) In C++, which of the following has the associatively of left to right?
- Addressof
- Unary operator
- Logical not
- Array element access
In C++, the elements in an array are organized from left to right. Therefore, the accurate choice is option D.
33) A function declared as the " friend " function can always access the data in _______.
- The private part of its class.
- The part declared as public of its class.
- Class of which it is the member.
- None of the above
In C++, a member function has the ability to access its class member variable regardless of the access specifier used to declare the member variable. This means that a member function can always retrieve the data from the class to which it belongs. Therefore, the correct choice is option C.
Predict the most suitable outcome of the provided C++ program by analyzing the following code snippet.
#include<iostream>
using namespace std;
int x[100];
int main()
{
cout<< x[99] <<endl;
}
- It will display 0 as output
- Its output is unpredictable
- It will display 99 as output
- None of the above
In C++, all global variables that are not explicitly initialized are automatically set to 0. Hence, option A is the accurate choice.
Read the provided C++ program below and determine the most likely output of the program.
#include<iostream>
usingnamespacestd;
intx = 1;
voidfun()
{
intx = 2;
{
intx = 3;
cout<< ::x <<endl;
}
}
intmain()
{
fun();
return0;
}
Whenever the scope resolution operator is employed with a variable name, it consistently references the global variable.
36) In C++, it is possible that the destructor can also be private?
- No, not at all
- May be
- Yes, it is possible.
- None of the above
In C++, the destructor is also allowed to be defined as private. Thus, the accurate response is option C.
37) In C++, it is possible that in a "class" there can more than one destructor like the constructor?
- Yes, it is possible
- Not it not possible at all
- Both A and B
- None of the above
Another crucial point to remember is that they are unable to accept arguments.
38) In C++, it is true that a destructor can be virtual?
- No, not at all
- Yew, it is true
- It may or may not be
- None of the above
Yes, it is indeed true that a destructor can be virtual. Thus, the accurate choice would be option B.
39) Which of the following statements can be considered as true about the virtual function in C++?
- In general, Virtual Functions are those functions that can be overridden in the derived class with the same signature.
- Virtual functions enable runtime polymorphism in the inheritance hierarchy.
- Both A and B
- None of the above
In object-oriented programming languages like Pascal, and particularly in C++, virtual functions (or virtual methods) are typically inheritable and can be overridden. These characteristics play a crucial role in the runtime polymorphism of object-oriented programming. Essentially, virtual functions define a specific function to be executed, with the potential for the target to be unidentified during compilation. Hence, the accurate response is option C.
40) Which of the following given statements are correct about the pure virtual functions?
- In a case where a class contains a pure virtual function, that class becomes an abstract class. In addition, the instance of that class also cannot be created.
- The implementation of the pure virtual functions is not provided in a class where they are declared.
- Only 1
- Only 2
- Both 1& 2
- Neither 1 nor 2
A pure virtual function, also known as a pure method, is a virtual function that must be implemented by any derived class that is not abstract. Nevertheless, a class that includes a pure virtual function (or method) is labeled as "abstract" and cannot be instantiated directly.
41) The following program's output will be: ```
include<bits/stdc++.h>
usingnamespacestd;
intmain
{
// generates interrupt 5
asmint5;
return0;
}
include<iostream>
usingnamespacestd;
classBase
{
public:
virtualvoidshow = 0;
};
classDerived : publicBase { };
intmain(void)
{
Derived q;
return0;
}
- It will obtain compile error because there cannot be an empty derived class
- It will obtain the compile error with "derived is abstract" warning
- Both A and B
- None of the above
Answer: b
If a user chooses not to redefine the pure function in the subclass, the subclass will be transformed into an abstract class as well. Hence, the accurate selection is option B.
42) Is it possible for a function in C++ to invoke itself?
- Yes, recursion is a technique where a function calls itself.
- If not implemented correctly, it may lead to stack overflow or infinite loop.
Answer: a
Indeed, it is accurate that a function has the capability to invoke itself. Consequently, option A is the correct response.
In C++, is it possible for a for loop statement to embed another for loop statement?
Answer: b
In the C++ programming language, a for loop statement has the capability to include another for loop within it, which is referred to as a nested for loop.
None of the operators listed above have a higher precedence than the others; they all have equal precedence.
Answer: d
All the operators listed in the preceding questions share equal precedence. Therefore, the accurate response is option D.
45) Which of the following can be considered as the correct syntax of for loop?
- for(initialization; condition; increment/decrement operator){}
- for(initialization, condition; increment/decrement operator){}
- for(initialization; increment/decrement operator;condition;{}
- None of the above
Answer: a
Typically, the for loop consists of three statements, and the functionality of these statements is illustrated in the syntax below:
for (statement 1; statement 2; statement 3) {
// code block to be executed
}
statement1: initialzation
statement2: condition to be check
statement3: increment or decrement operator
Which option is utilized to end the structure in C++?
Answer: b
In C++, a semicolon is employed to conclude a structure.
47) Inside a structure, the declared data members are known as____
- Data
- Object & data
- Members
- None of the above
Answer: c
The variables defined inside a structure are referred to as its members. Hence, option B is the accurate choice.
48) The term modularity refers to _____.
- To divide the program into small independent parts or sub-modules
- To override the parts of the program
- To wrapping things into a single unit
- None of the above
Answer: a
In C++, the concept of "modularity" refers to breaking down a large program into smaller, self-contained components or modules.