C++ Multiple Choice Questions


C++ Multiple Choice Questions

These multiple-choice questions and answers (MCQs) on "C++ Programming" focus on all areas of C++ Programming covering almost all topics. These topics are chosen from a collection of the most authoritative and best reference books on C++ Programming.

1) Which of the following keywords is used to write assembly code in a C ++ program?
ASM
asm
Not possible
Compiler specific 



Answer: b

Description:

In the C ++ programming language, one can use the "asm" keyword to write assembly code as an inline function. To understand this in more detail, please consider the following example:

Sample demo of "asm" keyword use:

#include<bits/stdc++.h>
usingnamespacestd;
intmain()
{
// generates interrupt 5
asmint5;

return0;
} #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 



Answer: b

Description: Typecasting is referred to as converting a specific expression type to another type. However, in the C++ programming language, the reinterpret_ cast is considered as the least safe typecasting. Therefore the correct answer will be option B.

3) ISO/IEC 14882:1998 addresses which version of C++?
C++ 98
C++ 93
C++ 0
C++ 03 



Answer: a

Description: The "ISO / IEX14882:1998 represents the C++ 0x version of the C++ language that also informally known as the "C++98". Hence the correct answer will be the 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 



Answer: a

Description: Command-line arguments are usually passed to the main() function from where the program's execution usually begins.

5) What will be the output if we execute the following C++ code and pass the given arguments on the terminal?

#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
======================================= #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 



Answer: a

Description: As you can see in the above given C++ program, we are trying to display (or print)all the command line arguments. Therefore the list contains "./output," "Hello," "World", as shown in the output. It is quite possible that you may be thinking why the first string is not the "program. Cpp". The main reason behind this is that the first string represents the name of the program's output file. So the correct answer will be 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 



Answer: b

Description: We can use either single or double quotes to handle the command-line arguments with spaces in between.

7) According to you, which of the following is the correct way to interpret Hello World as a single argument?

1. $ ./output 'Hello World'

2. $ ./output "Hello World"
Only 1
Only 2
Neither 1 nor 2
Both 1 and 2 



Answer: d

Description: Typically, both single and double quotes can be used 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 



Answer: d

Description: All the statements in the above questions are related to the second parameter. Therefore the correct answer is D.

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 



Answer: d

Description: All the statements given in the above questions are true for the first parameter of the "main()"function. The first parameter is of non-negative integer type and stores the count of command-line arguments.

10) Which of the following given can be considered as the correct output of the following 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;
} #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 



Answer: a

Description: If you look at the above-given program carefully, you will find that the lambda expression does not capture the value of variable "y" at all. Besides, it tries to access the value of the external variable y. Thus the above-given program will obtain or result in an Error. Therefore the correct answer is A.

11) What will be the output of the following C++ code?

#include<iostream>
usingnamespace std;
int main()
{
int a =5;
auto check =[](int x)
{
if(x ==0)
returnfalse;
else
returntrue;
};
cout<<check(a)<<endl;
return0;
} #include<iostream> usingnamespace std; int main() { int a =5; auto check =[](int x) { if(x ==0) returnfalse; else returntrue; }; cout<<check(a)<<endl; return0; }
0
Segmentation fault
Error



Answer: d

Description: The above program is absolutely fine. In the above program, you can observe that we have specified the return type of the expression. Hence the programs will normally work as it is able to find 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 



Answer: a

Description: Usually, the first parameter in the main() function or we can also say the first argument of the main() function denotes the number of command-line arguments that are passed to 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 



Answer: a

Description: Compilers may try to move the catch-code far away from the try-code, which reduces the amount of code to keep in the cache, thus it will enhance the overall performance.

14) What will be the output of the following C++ 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;
} #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 



Answer: d

Description: As you can see in the above-given program, we have given "3" to "num", it arising the exception called "wrong number used." So the correct answer is D.

15) What will be the output of the following C++ code?

#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;
} #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 



Answer: a

Description: In the given program, the value will be allocated if there is enough memory in the system. Therefore it depends entirelyon the memory of the system.

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 



Answer: d

Description: The Increment operator (or ++) is one of the basic operators in C++. Usually, it is used in several types of loop statements for the counter. Whenever the increment operator (or ++) gets executed, it adds or made an increment of 1 to its operand. To understand it more clearly, you can consider the example given 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

17) Read the following given piece of C++ code and find out the error?

Class t
{
virtual void print();
} 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 



Answer: d

Description: The above-given code is correct, and there is no error at all.

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 



Answer: a

Description: Pre Increment is usually faster than the post-increment because it takes one-byte instruction whereas the post-increment takes two-byte instruction.

19) Which of the following concept is used by pre-increment?
call by value
call by reference
queue
call by name 



Answer: b

Description: The pre-increment usually uses the concept of " call by reference " as the changes are reflected back to the memory cells/variables.

20) How many types of representation are in the string?
3
1
2



Answer: c

Description: In C++, there are following two types of string representation are provided. The following types of representation are C-style character string and string class type with Standard C++.

21) What will be the output of the following C++ code?

#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;
} #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; }
5
55
10
11 



Answer: c

Description: In the above-given program, we are concatenating the str1 and str2 and printing

its total length. Therefore the length of the final string is 10. So the correct answer 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 



Answer: c

Description: C++ programming language usually allows to append more characters to string using either the inbuilt append() function or using operator overloaded += operator.

23) What is the return value of f(p, p) if the value of p is initialized to 5 before the call?

Program

int f(int&x, int c) {
c = c - 1;
if (c == 0) return 1;
x = x + 1;
return f(x, c) * x;
} 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 



Answer: b

Description: In the given C++ program, we can clearly see that the c is passed by the value, but the x is passed by the reference. Therefore all functions in the given program will have the same copies of the x but different copies of the c. So the correct option is 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 



Answer: b

Description: In C++, you can create a constant reference that refers to a constant. To understand it in more, you can consider the following program given as an example. #include<iostream> using namespace std; int main() { constint x = 10; constint& ref = x; cout<< ref; return 0; }


25) Read the following given program of C++ and predict the most appropriate output of the following program?

#include<iostream>
usingnamespacestd;

int&fun()
{
staticintx = 10;
returnx;
}
intmain()
{
fun() = 30;
cout<< fun();
return0;
} #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 



Answer: b

Description: Whenever a function returns by the reference, it can also be used as the lvalue. However, x is declared as the static variable, it is shared among function calls, but the initialization line "static variable x= 10;" is executed only once. Therefore the function call " fun()=30, changed the x to 30, and next call "cout<<fun" simply returns the updated or modified value. So the correct answer will be the 30.

26) Read the following given program of C++ and predict the most appropriate output of the program?

#include<iostream>
usingnamespacestd;

int&fun()
{
intx = 10;
returnx;
}
intmain()
{
fun() = 30;
cout<< fun();
return0;
} #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 



Answer: b

Description: As you can notice in the above-given program, we return a reference to a local variable, and the memory location becomes invalid after the function call is over. Hence it most probably results in segmentation fault or runtime error.

27) Which of the following functions must use the reference?
Copy constructor
Destructor
Parameterized constructor
None of the above 



Answer: a

Description: In general, a copy constructor is called when the object is passed by the value. You may know that, the copy constructor itself also a type of function. So if we pass an argument by value in a copy constructor, a call to copy constructor would be made to call copy constructor, which becomes a non-terminating chain of calls. Therefore compiler doesn't allow parameters to be passed by value.

28) Read the following given program of C++ and predict the most appropriate output of the program?

#include<iostream>
usingnamespacestd;

intmain()
{
intx = 10;
int& ref= x;
ref= 20;
cout<< "x = "<< x <<endl ;
x = 30;
cout<< "ref = "<< ref<<endl;
return0;
} #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 



Answer: a

Description: As you can see that in the above program, the "ref" is an alias of the x. Therefore if we make changes or modifies any of them, the updated one also causes to change in another. So the correct option is A.

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 



Answer: b

Description: In general, the inline functions are very small in size and more often used in the place of the macros as they are the substitute of the macros and many times better than the macros. So the correct answer is B.

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 



Answer: d

Description: In simple terms, the inline functions are just like normal functions, which are defined by the users through the "inline" keywords.

Normally they are short functions that are expended by the compiler, and their arguments are evaluated for once only.The inline functions perform the type checking of the parameters, whereas micros do not check the parameters at all.

However, macros are usually processed by the preprocessor, but the inline functions are processed in the upcoming stages of the compilation. There is one more major advantage of inline functions over the macros, which is, inline functions can also have the return function, whereas the macros do not have a return statement. Last but not least, the macroshave more bugs and errors, whereas the inline function does not have bugs.

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. 



Answer: a

Description:

One can make a c++ program in which a class's object can be created using only the " new "operator, and still, if the user wants and tries to create its object directly, the program will produce a compiler error. To can understand it more clearly, you can consider the following given example.

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 



Answer: d

Description: In C++, the array elements have the associatively of left to right. So the correct answer will be 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 



Answer: c

Description: In C++, a member function can always access its class member variable, irrespective of the access specifier in which the member variable is declared. Therefore a member function can always access the data of the class of which it is a member. So the answer will be option C.

34) Read the following given program of C++ and predict the most appropriate output of the program?

#include<iostream>
using namespace std;

int x[100];
int main()
{
cout<< x[99] <<endl;
} #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 



Answer: a

Description: In C++, all the uninitialized global variables are initialized to 0. Therefore the correct answer will be option A.

35) Read the following given program of C++, and predict the most appropriate output of the program?

#include<iostream>
usingnamespacestd;
intx = 1;
voidfun()
{
intx = 2;
{
intx = 3;
cout<< ::x <<endl;
}
}
intmain()
{
fun();
return0;
} #include<iostream> usingnamespacestd; intx = 1; voidfun() { intx = 2; { intx = 3; cout<< ::x <<endl; } } intmain() { fun(); return0; }
1
2
3



Answer: a

Description: Whenever the scope resolution operator is used with a variable name, it always refers to 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 



Answer: c

Description: In C++, the destructor can also be private. Therefore the correct answer is 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 



Answer: b

Description: Anotherimportant thing to keep in mind that they cannot passed 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 



Answer: b

Description: Yes, it is true that a destructor can be virtual. Therefore the correct answer will 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 



Answer: c

Description: In object-oriented programming languages such as Pascal, and especiallyin C++, a virtual functions(or virtual methods) are usually inheritable as well as can be overridden. These features are an important part of the runtime polymorphism of object-oriented programming. In short, we can say that the virtual functions describe a target function to be executed; it may be possible that the target may be unknown at the compile time. Therefore the correct answer is C.

40) Which of the following given statements are correct about the pure virtual functions?

1. 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.

2. 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 



Answer: b

Description: A pure virtual function or pure method is a type of virtual function which required to be implemented by the derived class if that class is not abstracted. However, a class that contains a pure virtual function (or method) is known as the "abstract" and cannot be initiated directly.

41) What will be the output of the following given program?

#include<iostream>
usingnamespacestd;
classBase
{
public:
virtualvoidshow() = 0;
};

classDerived : publicBase { };

intmain(void)
{
Derived q;
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

Description: If a user does not override the pure function in the derived class, then the derived class is also converted into an abstract class. Therefore the correct option is B.

42) In C++, can a function call itself?
Yes
No
Compilation error
Runtime error 



Answer: a

Description: Yes, it is correct, a function can call itself. Therefore the correct answer is A.

43) In C++, can a for loop statement contain another for loop statement?
No
Yes
Runtime error
None of the above 



Answer: b

Description: In the c++ programming language, afor loop statement can contain another for loop in itself known as the nested for loop.

44) Which of the following operators has the highest precedence?
%
/
*
All have the same precedence 



Answer: d

Description: All the mentioned operators in the above-given questions have the same precedence. So the correct answer is 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

Description: Usually, the for loop contains three statements and the working of these statementsis shown in the following syntax: for (statement 1; statement 2; statement 3) { // code block to be executed } statement1: initialzation statement2: condition to be check statement3: increment or decrement operator


46) Which of the following is used to terminate the structure in C++?
;
:
;;



Answer: b

Description: In C++, to terminate the structure, a semicolon is used.

47) Inside a structure, the declared data members are known as____
Data
Object & data
Members
None of the above 



Answer: c

Description: The data members declared within the structure are known as the members. Therefore the correct answer is B.

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

Description: In C++, the term "modularity" indicates the sub-dividing. A big program converts into small independent parts or modules.



Comments

Popular posts from this blog

Mini-Max Algorithm in Artificial Intelligence

Alpha-Beta Pruning

Software Engineering Multiple Choice Questions