Professional Documents
Culture Documents
This section on C++ interview questions and answers focuses on “Types”. One shall practice
these interview questions to improve their C++ programming skills needed for various
interviews (campus interviews, walkin interviews, company interviews), placements, entrance
exams and other competitive exams. These questions can be attempted by anyone focusing on
learning C++ programming language. They can be a beginner, fresher, engineering graduate or
an experienced IT professional. Our C++ interview questions come with detailed explanation of
the answers which helps in better understanding of C++ concepts.
Here is a listing of C++ interview questions on “Types” along with answers, explanations and/or
solutions:
Answer: d
Explanation: Compiler wants to make CPU as more efficient in accessing the next value.
Answer: a
Explanation: Array type is not the basic type and it is constructed using the basic type.
Answer: c
Explanation: void will not return anything.
4. What does a escape code represent?
a) alert
b) backslash
c) tab
d) form feed
View Answer
Answer: a
Explanation: Because a is used to produce a beep sound.
Answer: b
Explanation: Logical values can be either true or false, so the boolean type is suited for it.
Answer: c
Explanation: They must be defined by the users before use unlike the other types which are
readily available.
Answer: b
Explanation: The argument that is passed to a function f is of float type and the function finally
retruns a value that id is of integer type.
Answer: a
Explanation: The given value is with decimal points, so float or double can be used.
9. When a language has the capability to produce new data type mean, it can be called as
a) overloaded
b) extensible
c) encapsulated
d) reprehensible
View Answer
Answer: b
Explanation: Extensible is used to add new features to C++.
Answer: c
Explanation: Option a consists of all fundamental types, option b consists of user-definied types
and option d consists of derived types but option c is a mixture.
This section on C++ language interview questions and answers focuses on “Booleans”. One shall
practice these interview questions to improve their C++ programming skills needed for various
interviews (campus interviews, walkin interviews, company interviews), placements, entrance
exams and other competitive exams. These questions can be attempted by anyone focusing on
learning C++ programming language. They can be a beginner, fresher, engineering graduate or
an experienced IT professional. Our C++ language interview questions come with detailed
explanation of the answers which helps in better understanding of C++ concepts.
Here is a listing of C++ language interview questions on “Booleans” along with answers,
explanations and/or solutions:
Answer: a
Explanation: C++ has bool as a fundamental data type.
Answer: d
Explanation: std::vector<bool> is a specialized version of vector, which is used for elements of
type bool and optimizes for space. It behaves like the unspecialized version of vector and the
storage is not necessarily an array of bool values, but the library implementation may optimize
storage so that each value is stored in a single bit.
a) True
b) False
c) 1
d) None of the mentioned
View Answer
Answer: b
Explanation: The given number is a double not an integer, so the function returns 0 which is
boolean false.
Answer: c
Explanation: A pointer can be implicitly converted to a bool. A nonzero pointer converts to true
and zerovalued pointer converts to false.
Answer: b
Explanation: None.
Answer: c
Explanation: The if-statement block is only not executed when the expression evaluates to 0. It’s
just syntactic sugar for a branch-if-zero instruction.
7. Which of the two operators ++ and — work for the bool datatype in C++?
a) None
b) ++
c) —
d) ++ & —
View Answer
Answer: b
Explanation: Due to history of using integer values as booleans, if an integer is used as a
boolean, then incrementing will mean that whatever its truth value before the operation, it will
have a truth-value of true after it. However, it’s not possible to predict the result of — given
knowledge only of the truth value of x, as it could result in false.
1. #include <iostream>
2. using namespace std;
3. int f(int p, int q)
4. {
5. if (p > q)
6. return p;
7. else
8. return q;
9. }
10. main()
11. {
12. int a = 5, b = 10;
13. int k;
14. bool x = true;
15. bool y = f(a, b);
16. k =((a * b) + (x + y));
17. cout << k;
18. }
a) 55
b) 62
c) 52
d) none of the mentioned
View Answer
Answer: c
Explanation: None.
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int p;
6. bool a = true;
7. bool b = false;
8. int x = 10;
9. int y = 5;
10. p = ((x | y) + (a + b));
11. cout << p;
12. return 0;
13. }
a) 0
b) 16
c) 12
d) 2
View Answer
Answer: b
Explanation: None.
Answer: b
Explanation: None.
Online C++ Test - Character Types - Sanfoundry
by Manish
This section on online C++ test focuses on “Character Types”. One shall practice these test
questions to improve their C++ programming skills needed for various interviews (campus
interviews, walkin interviews, company interviews), placements, entrance exams and other
competitive exams. These questions can be attempted by anyone focusing on learning C++
programming language. They can be a beginner, fresher, engineering graduate or an experienced
IT professional. Our online C++ test questions come with detailed explanation of the answers
which helps in better understanding of C++ concepts.
Here is a listing of online C++ test questions on “Character Types” along with answers,
explanations and/or solutions:
Answer: b
Explanation: None.
Answer: c
Explanation: Every character constant has an integer value. Also char belongs to the integral type
hence arithmetic and logical operations can be performed on them.
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. char c = 74;
6. cout << c;
7. return 0;
8. }
a) A
b) N
c) J
d) I
View Answer
Answer: c
Explanation: The literal value for 74 is J. So it will be printing J.
Answer: a
Explanation: A wide character is always indicated by immediately preceding the character literal
by an L.
1. #include <stdio.h>
2. int main()
3. {
4. char a = '\012';
5.
6. printf("%d", a);
7. return 0;
8. }
a) Compiler error
b) 12
c) 10
d) Empty
View Answer
Answer: c
Explanation: The value ‘\012’ means the character with value 12 in octal, which is decimal 10.
Answer: c
Explanation: The standard does not specify if plain char is signed or unsigned. There are three
distinct character types according to the standard: char, signed char and unsigned char.
Answer: c
Explanation: In C++, sizeof(‘a’) == sizeof(char) == 1. In C however, sizeof(‘a’) == sizeof(int).
9. Suppose in a hypothetical machine, the size of char is 32 bits. What would sizeof(char) return?
a) 4
b) 1
c) Implementation dependent
d) Machine dependent
View Answer
Answer: b
Explanation: The standard does NOT require a char to be 8-bits, but does require that
sizeof(char) return 1.
10. What constant defined in <climits> header returns the number of bits in a char?
a) CHAR_SIZE
b) SIZE_CHAR
c) BIT_CHAR
d) CHAR_BIT
View Answer
Answer: d
Explanation: None.
This section on C++ interview questions and answers focuses on “Integer Types”. One shall
practice these interview questions to improve their C++ programming skills needed for various
interviews (campus interviews, walkin interviews, company interviews), placements, entrance
exams and other competitive exams. These questions can be attempted by anyone focusing on
learning C++ programming language. They can be a beginner, fresher, engineering graduate or
an experienced IT professional. Our C++ interview questions come with detailed explanation of
the answers which helps in better understanding of C++ concepts.
Here is a listing of C++ interview questions on “Integer Types” along with answers, explanations
and/or solutions:
Answer: c
Explanation: The size_t type is used to represent the size of an object. Hence, it’s always
unsigned. According to the language specification, it is at least 16 bits.
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int x = -1;
6. unsigned int y = 2;
7.
8. if(x > y)
9. {
10. cout << "x is greater";
11. }
12. else
13. {
14. cout << "y is greater";
15. }
16. }
a) x is greater
b) y is greater
c) implementation defined
d) arbitrary
View Answer
Answer: a
Explanation: x is promoted to unsigned int on comparison. On conversion x has all bits set,
making it the bigger one.
3. Which of these expressions will return true if the input integer v is a power of two?
a) (v | (v + 1)) == 0;
b) (~v & (v – 1)) == 0;
c) (v | (v – 1)) == 0;
d) (v & (v – 1)) == 0;
View Answer
Answer: d
Explanation: Power of two integers have a single set bit followed by unset bits.
4. What is the value of the following 8-bit integer after all statements are executed?
1. int x = 1;
2. x = x << 7;
3. x = x >> 7;
a) 1
b) -1
c) 127
d) Implementation defined
View Answer
Answer: d
Explanation: Right shift of signed integers is undefined, and has implementation-defined
behaviour.
5. Which of these expressions will make the rightmost set bit zero in an input integer x?
a) x = x | (x-1)
b) x = x & (x-1)
c) x = x | (x+1)
d) x = x & (x+1)
View Answer
Answer: b
Explanation: None.
6. Which of these expressions will isolate the rightmost set bit?
a) x = x & (~x)
b) x = x ^ (~x)
c) x = x & (-x)
d) x = x ^ (-x)
View Answer
Answer: c
Explanation: None.
7. 0946, 786427373824, ‘x’ and 0X2f are _____ _____ ____ and _____ literals respectively.
a) decimal, character,octal, hexadecimal
b) octal, hexadecimal, character, decimal
c) hexadecimal, octal, decimal, character
d) octal, decimal, character, hexadecimal
View Answer
Answer: d
Explanation: Literal integer constants that begin with 0x or 0X are interpreted as hexadecimal
and the ones that begin with 0 as octal. The character literal are written within ”.
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int a = 8;
6. cout << "ANDing integer 'a' with 'true' :" << a && true;
7. return 0;
8. }
Answer: a
Explanation: None.
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int i = 3;
6. int l = i / -2;
7. int k = i % -2;
8. cout << l << k;
9. return 0;
10. }
Answer: b
Explanation: Sign of result of mod operation on negative numbers is sign of the dividend.
1. int main()
2. {
3. register int i = 1;
4. int *ptr = &i;
5. cout << *ptr;
6. return 0;
7. }
a) 0
b) 1
c) Compiler error may be possible
d) Runtime error may be possible
View Answer
Answer: c
Explanation: Using & on a register variable may be invalid, since the compiler may store the
variable in a register, and finding the address of it is illegal.
This section on advanced C++ programming questions focuses on “Floating Point Types”. One shall
practice these advanced C++ questions to improve their C++ programming skills needed for various
interviews (campus interviews, walkin interviews, company interviews), placements, entrance exams
and other competitive exams. These questions can be attempted by anyone focusing on learning
C++ programming language. They can be a beginner, fresher, engineering graduate or an
experienced IT professional. Our advanced C++ questions come with detailed explanation of the
answers which helps in better understanding of C++ concepts.
Here is a listing of advanced C++ programming questions on “Floating Point Types” along with
answers, explanations and/or solutions:
1. Which of the following is not one of the sizes of the floating point types?
a) short float
b) float
c) long double
d) double
View Answer
Answer: a
Explanation: Floating point types occur in only three sizes-float, long double and double.
Answer: c
Explanation: To make a floating point literal, we should attach a suffix of ‘f’ or ‘F’ and there should
not be any blank space.
Answer: a
Explanation: None.
4. Which of three sizes of floating point types should be used when extended precision is required?
a) float
b) double
c) long double
d) extended float
View Answer
Answer: c
Explanation: Float for single precision, double for double precision and long double for extended
precision.
#include <iostream>
int main()
if (num1 == num2)
else
return 0;
a) harvard
b) stanford
c) compile time error
d) runtime error
View Answer
Answer: a
Explanation: Float store floating point numbers with 8 place accuracy and requires 4 bytes of
Memory. Double has 16 place accuracy having size of 8 bytes.
Output:
$ g++ float3.cpp
$ a.out
harvard
#include <iomanip>
#include <iostream>
int main()
double d = 0.1;
return 0;
a) 0.11
b) 0.10000000000000001
c) 0.100001
d) compile time error
View Answer
Answer: b
Explantion: The double had to truncate the approximation due to it’s limited memory, which resulted
in a number that is not exactly 0.1.
Output:
$ g++ float2.out
$ a.out
0.10000000000000001
#include <iostream>
int main()
float i = 123.0f;
return 0;
a) 123.00
b) 1.23
c) 123
d) compile time error
View Answer
Answer: c
Explanation: The value 123 is printed because of its precision.
$ g++ float.cpp
$ a.out
123
Answer: a
Explanation: None.
int main()
float f1 = 0.5;
double f2 = 0.5;
if (f1 == 0.5f)
else
return 0;
a) equal
b) not equal
c) compile time error
d) runtime error
View Answer
Answer: a
Explanation: 0.5f results in 0.5 to be stored in floating point representations.
Output:
$ g++ float.cpp
$ a.out
equal
Answer: d
Explanation: The char has lesser bytes than int and int has lesser bytes than double whereas int and
float can potentially have same sizes.
Here is a listing of C++ interview questions on “Sizes” along with answers, explanations and/or
solutions:
Answer: b
Explanation: The sizeof operator gives the size of the object or type.
2. It is guaranteed that a ____ has atleast 8bits and a ____ has atleast 16 bits.
a) int, float
b) char, int
c) bool, char
d) char, short
View Answer
Answer: d
Explanation: None.
Answer: b
Explanation: The limit header holds the details of the machine dependent details.
4. Size of C++ objects are expressed in terms of multiples of the size of a ____ and the size of a
char is _______
a) char, 1
b) int, 1
c) float, 8
d) char, 4
View Answer
Answer: a
Explanation: None.
Answer: c
Explanation: sizeof(char) <= sizeof(wchar_t) <= sizeof(long).
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int num = 0x20 + 020 + 20;
6. cout << sizeof(num)<<'\n';
7. return 0;
8. }
a) 2
b) 4
c) Depends on compiler
d) Garbage
View Answer
Answer: c
Explanation: The sum of three numbers are belongs to different number systems, so the result is
typecasted into integer.
Output:
$ g++ size.cpp
$ a.out
4
1. #include <iostream>
2. using namespace std;
3. int main ( )
4. {
5. static double i;
6. i = 20;
7. cout << sizeof(i);
8. return 0;
9. }
a) 4
b) 2
c) 8
d) garbage
View Answer
Answer: c
Explanation: The size of the double data type is 8.
$ g++ size1.cpp
$ a.out
8
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int num1 = 10;
6. float num2 = 20;
7. cout << sizeof(num1 + num2);
8. return 0;
9. }
a) 2
b) 4
c) 8
d) garbage
View Answer
Answer: b
Explanation: In this program, integer is converted into float. Therefore the result of num1 and
num2 is float. And it is returning the size of the float.
Output:
$ g++ size2.cpp
$ a.out
4
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int a = 5;
6. float b;
7. cout << sizeof(++a + b);
8. cout << a;
9. return 0;
10. }
a) 2 6
b) 4 6
c) 2 5
d) 4 5
View Answer
Answer: d
Explanation: The a as a integer will be converted to float while calculating the size. The value of
any variable doesn’t modify inside sizeof operator. Hence value of variable a will remain 5.
Output:
$ g++ size3.cpp
$ a.out
45
10. What would be the output of the following program (in 32-bit systems)?
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. cout << sizeof(char);
6. cout << sizeof(int);
7. cout << sizeof(float);
8. return 0;
9. }
a) 1 4 4
b) 1 4 8
c) 1 8 8
d) none of the mentioned
View Answer
Answer: a
Explanation: Character is 1 byte, integer 4 bytes and float 4 bytes.
This section on C++ language interview questions and answers focuses on “Void”. One shall
practice these interview questions to improve their C++ programming skills needed for various
interviews (campus interviews, walkin interviews, company interviews), placements, entrance exams
and other competitive exams. These questions can be attempted by anyone focusing on learning
C++ programming language. They can be a beginner, fresher, engineering graduate or an
experienced IT professional. Our C++ language interview questions come with detailed explanation
of the answers which helps in better understanding of C++ concepts.
Here is a listing of C++ language interview questions on “Void” along with answers, explanations
and/or solutions:
Answer: b
Explanation: None.
Answer: d
Explanation: Constructor creats an Object and Destructor destroys the object. They are not
supposed to return anything, not even void.
Answer: d
Explanation: There are no void objects.
Answer: b
Explanation: void fundamental type is used in the cases of a and c.
#include <iostream>
int c;
c = a + b;
cout << c;
return 0;
a) 20
b) compile time error
c) runtime error
d) none of the mentioned
View Answer
Answer: b
Explanation: void will not accept any values to its type.
This section on online C++ test focuses on “Enumerations”. One shall practice these test questions
to improve their C++ programming skills needed for various interviews (campus interviews, walkin
interviews, company interviews), placements, entrance exams and other competitive exams. These
questions can be attempted by anyone focusing on learning C++ programming language. They can
be a beginner, fresher, engineering graduate or an experienced IT professional. Our C online test
questions come with detailed explanation of the answers which helps in better understanding of C++
concepts.
Here is a listing of online C++ test questions on “Enumerations” along with answers, explanations
and/or solutions:
Answer: c
Explanation: Enumerators are used in order to create our own types whereas macros are textual
substitutions.
Answer: b
Explanation: None.
Answer: d
Explanation: Since enumerators evaluate to integers, and integers can be assigned to enumerators,
enumerators can be assigned to other enumerators.
Answer: a
Explanation: Enumerator will allocate the memory when its variables are defined.
Answer: a
Explanation: The enum variable are converted to integer and stored by compiler. So both are equal
in size.
#include <iostream>
enum cat
temp = 7
};
int main()
age /= temp;
cout << "If you were cat, you would be " << age << endl;
return 0;
Answer: b
Explanation: The age will be divided by using compound assignment operator and so it will return
the age of the cat according to your age.
$ g++ enum1.cpp
$ a.out
If you were cat, you would be 2
#include <iostream>
enum test
A = 32, B, C
};
int main()
return 0;
a) 323334
b) 323232
c) 323130
d) none of the mentioned
View Answer
Answer: a
Explanation: If we not assigned any value to enum variable means, then the next number to
initialized number will be allocated to the variable.
Output:
$ g++ enum2.cpp
$ a.out
323334
#include <iostream>
enum colour {
};
int main()
return 0;
a) 012345
b) 123456
c) compile time error
d) runtime error
View Answer
Answer: a
Explanation: The enumerator values start from zero if it is unassigned.
Output:
$ g++ enum3.cpp
$ a.out
012345
#include <iostream>
int i = 0;
return 0;
a) 012
b) 123
c) compile time error
d) runtime error
View Answer
Answer: c
Explanation: Enumartion variable ‘star’ appears two times in main() which causes the error. An
enumaration constant must be unique within the scope.
#include <iostream>
int main()
int i;
enum month {
JAN = 1, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC
};
cout << i;
return 0;
}
a) 01234567891011
b) 123456789101112
c) 34567891011
d) 123456789
View Answer
Answer: c
Explanation: We are getting the values from march to november and printing its concern number.
This section on C++ interview questions and answers focuses on “Declaration”. One shall
practice these interview questions to improve their C++ programming skills needed for various
interviews (campus interviews, walkin interviews, company interviews), placements, entrance
exams and other competitive exams. These questions can be attempted by anyone focusing on
learning C++ programming language. They can be a beginner, fresher, engineering graduate or
an experienced IT professional. Our C++ interview questions come with detailed explanation of
the answers which helps in better understanding of C++ concepts.
Here is a listing of C++ interview questions on “Declaration” along with answers, explanations
and/or solutions:
Answer: d
Explanation: The keyword extern is not a definition and is not allocated storage until it is
initialized.
Answer: c
Explanation: No extern are allowed for class declarations.
Answer: c
Explanation: Global values are implicitly initialised to 0, but local values have to be initialised
by the system.
1. #include <iostream>
2. using namespace std;
3. int g = 100;
4. int main()
5. {
6. int a;
7. {
8. int b;
9. b = 20;
10. a = 35;
11. g = 65;
12. cout << b << a << g;
13. }
14. a = 50;
15. cout << a << g;
16. return 0;
17. }
a) 2035655065
b) 2035655035
c) 2035635065
d) none of the mentioned
View Answer
Answer: a
Explanation: The local values of a and g within the block are more dominant than the global
values.
Output:
$ g++ dec1.cpp
$ a.out
2035655065
6. Can two functions declare variables(non static) with the same name.
a) No
b) Yes
c) Yes, but not a very efficient way to write programs
d) No, it gives a runtime error
View Answer
Answer: c
Explanation: We can declare variables with the same name in two functions because their scope
lies within the function.
1. #include <iostream>
2. using namespace std;
3. void addprint()
4. {
5. static int s = 1;
6. s++;
7. cout << s;
8. }
9. int main()
10. {
11. addprint();
12. addprint();
13. addprint();
14. return 0;
15. }
a) 234
b) 111
c) 123
d) 235
View Answer
Answer: a
Output:
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int a = 10;
6. if (a < 10) {
7. for (i = 0; i < 10; i++)
8. cout << i;
9. }
10. else {
11. cout << i;
12. }
13. return 0;
14. }
a) 0123456789
b) 123456789
c) 0
d) error
View Answer
Answer: d
Explanation: We will get compilation error because ‘i’ is an undeclared identifier.
Answer: c
Explanation: In statement 1 lvalue is required as unary ‘&’ operand and in statement 3 lvalue is
required as left operand.
Answer: a
Explanation: The statement makes CHAR a synonym for char*.
This section on C++ aptitude questions and answers focuses on “Pointers”. One shall practice
these aptitude questions to improve their C++ programming skills needed for various interviews
(campus interviews, walkin interviews, company interviews), placements, entrance exams,
aptitude tests and other competitive exams. These questions can be attempted by anyone
focusing on learning C++ programming language. They can be a beginner, fresher, engineering
graduate or an experienced IT professional. Our C++ questions come with detailed explanation
of the answers which helps in better understanding of C++ concepts.
Here is a listing of C++ aptitude questions on “Pointers” along with answers, explanations and/or
solutions:
Answer: c
Explanation: None.
Answer: a
Explanation: None.
3. Choose the right option
string* x, y;
a) x is a pointer to a string, y is a string
b) y is a pointer to a string, x is a string
c) both x and y are pointer to string types
d) none of the mentioned
View Answer
Answer: a
Explanation: * is to be grouped with the variables not the data types.
Answer: d
Explanation: A pointer can be in only 3 states a,b and c.
Answer: c
Explanation: dp is initialized int value of i.
a) b is assigned to a
b) p now points to b
c) a is assigned to b
d) q now points to a
View Answer
Answer: b
Explanation: Assigning to refrence changes the object to which the refrence is bound.
a) 5
b) 10
c) 15
d) it will return some random number
View Answer
Answer: d
Explanation: Array element cannot be address of auto variable. It can be address of static or
extern variables.
8. The correct statement for a function that takes pointer to a float, a pointer to a pointer to a char
and returns a pointer to a pointer to a integer is
a) int **fun(float**, char**)
b) int *fun(float*, char*)
c) int ***fun(float*, char**)
d) int ***fun(*float, **char)
View Answer
Answer: c
Explanation: None.
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. char arr[20];
6. int i;
7. for(i = 0; i < 10; i++)
8. *(arr + i) = 65 + i;
9. *(arr + i) = '\0';
10. cout << arr;
11. return(0);
12. }
a) ABCDEFGHIJ
b) AAAAAAAAAA
c) JJJJJJJJ
d) None of the mentioned
View Answer
Answer: a
Explanation: Each time we are assigning 65 + i. In first iteration i = 0 and 65 is assigned. So it
will print from A to J.
$ g++ point1.cpp
$ a.out
ABCDEFGHIJ
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. char *ptr;
6. char Str[] = "abcdefg";
7. ptr = Str;
8. ptr += 5;
9. cout << ptr;
10. return 0;
11. }
a) fg
b) cdef
c) defg
d) abcd
View Answer
Answer: a
Explanation: Pointer ptr points to string ‘fg’. So it prints fg.
Output:
$ g++ point.cpp
$ a.out
fg
This section on C++ interview questions and answers focuses on “Arrays”. One shall practice these
interview questions to improve their C++ programming skills needed for various interviews (campus
interviews, walkin interviews, company interviews), placements, entrance exams and other
competitive exams. These questions can be attempted by anyone focusing on learning C++
programming language. They can be a beginner, fresher, engineering graduate or an experienced IT
professional. Our C++ interview questions come with detailed explanation of the answers which
helps in better understanding of C++ concepts.
Here is a listing of C++ interview questions on “Arrays” along with answers, explanations and/or
solutions:
1. Which of the following correctly declares an array?
a) int array[10];
b) int array;
c) array{10};
d) array array[10];
View Answer
Answer: a
Explanation: Because array variable and values need to be declared after the datatype only.
2. What is the index number of the last element of an array with 9 elements?
a) 9
b) 8
c) 0
d) Programmer-defined
View Answer
Answer: b
Explanation: Because the first element always starts at 0. So it is on 8 position.
3. What is a array?
a) An array is a series of elements of the same type in contiguous memory locations
b) An array is a series of element
c) An array is a series of elements of the same type placed in non-contiguous memory locations
d) None of the mentioned
View Answer
Answer: a
Explanation: None.
Answer: a
Explanation: The array location starts from zero, So it can accessed by array[6].
5. Which of the following gives the memory address of the first element in array?
a) array[0];
b) array[1];
c) array(2);
d) array;
View Answer
Answer: d
Explanation: None.
6. What will be the output of this program?
#include <stdio.h>
int main()
result += array1[temp];
result += array2[temp];
return 0;
a) 6553
b) 6533
c) 6522
d) 12200
View Answer
Answer: b
Explanation: In this program we are adding the every element of two arrays. Finally we got output as
6533.
Output:
$ g++ array.cpp
$ a.out
6533
#include <stdio.h>
using namespace std;
int main ()
int n, result = 0;
result += array[n];
return 0;
a) 25
b) 26
c) 27
d) None of the mentioned
View Answer
Answer: d
Explanation: We are adding all the elements in the array and printing it. Total elements in the array is
7, but our for loop will go beyond 7 and add a garbage value.
#include <stdio.h>
int main()
return 0;
a) 15
b) 18
c) garbage value
d) compile time error
View Answer
Answer: d
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’
#include <stdio.h>
int main()
return 0;
a) ABC
b) ABCD
c) AB
d) None of the mentioned
View Answer
Answer: a
Explanation: We are just printing the values of first 3 values.
$ g++ array.cpp
$ a.out
ABC
#include <stdio.h>
int main()
a) -15
b) -30
c) compile time error
d) garbage value
View Answer
Answer: b
Explanation: It’s just printing the negative value of the concern element.
$ g++ array.cpp
$ a.out
-30
This section on C++ language interview questions and answers focuses on “Pointers into Arrays”.
One shall practice these interview questions to improve their C++ programming skills needed for
various interviews (campus interviews, walkin interviews, company interviews), placements,
entrance exams and other competitive exams. These questions can be attempted by anyone
focusing on learning C++ programming language. They can be a beginner, fresher, engineering
graduate or an experienced IT professional. Our C++ language interview questions come with
detailed explanation of the answers which helps in better understanding of C++ concepts.
Here is a listing of C++ language interview questions “Pointers into Arrays” along with answers,
explanations and/or solutions:
Answer: b
Explanation: In the above declaration the variable p is array not pointer.
Answer: b
Explanation: Size of any type of pointer is 4 bytes in 32-bit platforms.
3. What is the output of this program?
#include <iostream>
int main()
return 0;
a) 15 18 21
b) 21 21 21
c) 24 24 24
d) Compile time error
View Answer
Answer: b
Explanation: a[1][2] means 1 * (4)+2 = 6th element of an array staring from zero.
Output:
$ g++ point.cpp
$ a.out
21 21 21
#include <iostream>
int main()
int i;
return 0;
a) ava
b) java
c) c++
d) compile time error
View Answer
Answer: a
Explanation: In this program we are moving the pointer from first position to second position and
printing the remaining value.
Output:
$ g++ point1.cpp
$ a.out
ava
#include <iostream>
int main()
return 0;
a) 4
b) 5
c) 6
d) 7
View Answer
Answer: b
Explanation: In this program, we are making the pointer point to next value and printing it.
$ g++ point3.cpp
$ a.out
5
#include <iostream>
int main()
{
int arr[] = {4, 5, 6, 7};
return 0;
a) 4
b) 5
c) address of arr
d) 7
View Answer
Answer: c
Explanation: As we couted to print only arr, it will print the address of the array.
Output:
$ g++ point2.cpp
$ a.out
0xbfb1cff
#include <iostream>
int main ()
int numbers[5];
int * p;
p = numbers; *p = 10;
p++; *p = 20;
p = &numbers[2]; *p = 30;
p = numbers + 3; *p = 40;
return 0;
}
a) 10,20,30,40,50,
b) 1020304050
c) compile error
d) runtime error
View Answer
Answer: a
Explanation: In this program, we are just assigning a value to the array and printing it and
immediately dereferencing it.
Output:
$ g++ point4.cpp
$ a.out
10,20,30,40,50,
#include <iostream>
int main()
return 0;
a) 12
b) 5
c) 13
d) error
View Answer
Answer: c
Explanation: In this program, we are adding the value 9 to the initial value of the array, So it’s
printing as 13.
Output:
$ g++ point5.cpp
$ a.out
13
Here is a listing of online C++ test questions on “Constants” along with answers, explanations
and/or solutions:
Answer: c
EXplanation: None.
Answer: d
Explanation: Because these are the types used to declare variables and so these can be declared
as constants.
Answer: c
Explanation: The const will declare with a specific type values and #define is used to declare
user definied constants.
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int const p = 5;
6. cout << ++p;
7. return 0;
8. }
a) 5
b) 6
c) Error
d) None of the mentioned
View Answer
Answer: c
Explanation: We cannot modify a constant integer value.
1. #include <iostream>
2. using namespace std;
3. #define PI 3.14159
4. int main ()
5. {
6. float r = 2;
7. float circle;
8. circle = 2 * PI * r;
9. cout << circle;
10. return 0;
11. }
a) 12.5664
b) 13.5664
c) 10
d) compile time error
View Answer
Answer: a
Explanation: In this program, we are finding the area of the circle by using concern formula.
Output:
$ g++ cons.cpp
$ a.out
12.5664
Answer: c
Explanation: Because the const is used to declare non-changable values only.
Answer: a
Explanation: None.
Answer: a
Explanation: It can turn this as wide character instead of narrow characters.
This section on C++ interview questions and answers focuses on “References”. One shall
practice these interview questions to improve their C++ programming skills needed for various
interviews (campus interviews, walkin interviews, company interviews), placements, entrance
exams and other competitive exams. These questions can be attempted by anyone focusing on
learning C++ programming language. They can be a beginner, fresher, engineering graduate or
an experienced IT professional. Our C++ interview questions come with detailed explanation of
the answers which helps in better understanding of C++ concepts.
Here is a listing of C++ interview questions on “References” along with answers, explanations
and/or solutions:
Answer: d
Explanation: If it can be assigned with a null value means, it is a copy of pointer.
Answer: b
Explanation: Reference is a thing which points to valid memory address, so it can’t be
redesigned.
Answer: a
Explanation: None.
1. #include <iostream>
2. using namespace std;
3. void swap(int &a, int &b);
4. int main()
5. {
6. int a = 5, b = 10;
7. swap(a, b);
8. cout << "In main " << a << b;
9. return 0;
10. }
11. void swap(int &a, int &b)
12. {
13. int temp;
14. temp = a;
15. a = b;
16. b = temp;
17. cout << "In swap " << a << b;
18. }
Answer: a
Explanation: As we are calling by reference the values in the address also changed. So the main
and swap values also changed.
Output:
$ g++ ref.cpp
$ a.out
In swap 105 In main 105
Answer: b
Explanation: Because we are pointing memory address using temp variable.
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int a = 9;
6. int & aref = a;
7. a++;
8. cout << "The value of a is " << aref;
9. return 0;
10. }
a) 9
b) 10
c) error
d) 11
View Answer
Answer: b
Explanation: The value is declared and it is post incremented, so it’s value is 10.
$ g++ ref1.cpp
$ a.out
10
1. #include <iostream>
2. using namespace std;
3. void print (char * a)
4. {
5. cout << a << endl;
6. }
7. int main ()
8. {
9. const char * a = "Hello world";
10. print(const_cast<char *> (a) );
11. return 0;
12. }
a) Hello world
b) Hello
c) world
d) compile time error
View Answer
Answer: a
Explanation: In this program we used the concept of constant casting to cast the variable and
printing it.
Output:
$ g++ ref2.cpp
$ a.out
Hello world
8. Identify the correct sentence regarding inequality between reference and pointer.
a) we can not create the array of reference
b) we can create the Array of reference
c) we can use reference to reference
d) none of the mentioned
View Answer
Answer: a
Explanation: None.
This section on C++ programming questions and answers focuses on “Pointer to Void”. One shall
practice these questions to improve their C++ programming skills needed for various interviews
(campus interviews, walkin interviews, company interviews), placements, entrance exams and other
competitive exams. These questions can be attempted by anyone focusing on learning C++
programming language. They can be a beginner, fresher, engineering graduate or an experienced IT
professional. Our C++ programming questions come with detailed explanation of the answers which
helps in better understanding of C++ concepts.
Here is a listing of C++ programming questions on “Pointer to Void” along with answers,
explanations and/or solutions:
Answer: d
Explanation: Because it doesn’t know the type of object it is pointing to, So it can point to all objects.
Answer: b
Explanation: By casting the pointer to another data type, it can dereferenced from void pointer.
3. The pointer can point to any variable that is not declared with which of these?
a) const
b) volatile
c) both const & volatile
d) static
View Answer
Answer: c
Explanation: None.
Answer: d
Explanation: None.
5. What is the output of this program?
#include <iostream>
int main()
func(Str);
return 0;
return 0;
a) abcdefghij
b) address of string “abcdefghij”
c) compile time error
d) runtime error
View Answer
Answer: b
Explanation: Even though it is a void pointer, we gets the address.
Output:
$ g++ b.cpp
$ a.out
0x8048714
#include <iostream>
int main()
int *p;
void *vp;
if (vp == p);
return 0;
a) equal
b) no output
c) compile error
d) runtime error
View Answer
Answer: a
Explanation: The void pointer is easily converted to any other type of pointer, so these are equal.
Output:
$ g++ poi4.cpp
$ a.out
equal
#include <iostream>
int main()
int i;
char c;
void *data;
i = 2;
c = 'd';
data = &i;
cout << "the data points to the integer value" << data;
data = &c;
cout << "the data now points to the character" << data;
return 0;
}
a) 2d
b) two memory addresses
c) both of the mentioned
d) none of the mentioned
View Answer
Answer: b
Explanation: Because the data points to the address value of the variables only, So it is printing the
memory address of these two variable.
Output:
$ g++ poi2.cpp
$ a.out
the data points to the integer value0xbfc81824 the data now points to the character0xbfc8182f
#include <iostream>
int main()
int n = 5;
void *p = &n;
return 0;
a) 5
b) 6
c) compile time error
d) runtime error
View Answer
Answer: a
Explanation: We just casted this from void to int, so it prints 5
Output:
$ g++ poi1.cpp
$ a.out
5
#include <iostream>
using namespace std;
int main()
int a = 5, c;
void *p = &a;
double b = 3.14;
p = &b;
c = a + b;
return 0;
a) 8, memory address
b) 8.14
c) memory address
d) none of the mentioned
View Answer
Answer: a
Explanation: In this program, we are just adding the two values and printing it.
Output:
$ g++ poi.cpp
$ a.out
8
0xbfef0378
Answer: a
Explanation: Because void pointer is used to cast the variables only, So pointer arithemetic can’t be
done in a void pointer.
This section on C++ interview questions and answers focuses on “Structures”. One shall practice
these interview questions to improve their C++ programming skills needed for various interviews
(campus interviews, walkin interviews, company interviews), placements, entrance exams and other
competitive exams. These questions can be attempted by anyone focusing on learning C++
programming language. They can be a beginner, fresher, engineering graduate or an experienced IT
professional. Our C++ interview questions come with detailed explanation of the answers which
helps in better understanding of C++ concepts.
Here is a listing of C++ interview questions on “Structures” along with answers, explanations and/or
solutions:
Answer: b
Explanation: None.
Answer: c
Explanation: While terminating a structure, a semi colon is used to end this up.
Answer: a
Explanation: While the structure is declared, it will not be initialized, So it will not allocate any
memory.
Answer: c
Explanation: The structure declaration with open and close braces and with a semicolon is also
called structure specifier.
5. What is the output of this program?
#include <iostream>
#include <string.h>
int main()
struct student
int num;
char name[25];
};
student stu;
stu.num = 123;
strcpy(stu.name, "John");
return 0;
a) 123
john
b) john
john
c) compile time error
d) none of the mentioned
View Answer
Answer: a
Explanation: We are coping the value john to the name and then we are printing the values that are
in the program.
Output:
$ g++ stu.cpp
$ a.out
123
john
struct Time
int hours;
int minutes;
int seconds;
};
int main()
Time t;
t.hours = 5;
t.minutes = 30;
t.seconds = 45;
return 0;
a) 19845
b) 20000
c) 15000
d) 19844
View Answer
Answer: a
Explanation: In this program, we are just converting the given hours and minutes into seconds.
Output:
$ g++ stu1.cpp
$ a.out
Total seconds:19845
7. What will be the output of this program?
#include <iostream>
int main()
struct ShoeType
string style;
double price;
};
shoe1.style = "Adidas";
shoe1.price = 9.99;
shoe2 = shoe1;
shoe2.price = shoe2.price / 9;
return 0;
a) Adidas $ 9.99
Adidas $ 1.11
b) Adidas $ 9.99
Adidas $ 9.11
c) Adidas $ 9.99
Adidas $ 11.11
d) none of the mentioned
View Answer
Answer: a
Explanation: We copied the value of shoe1 into shoe2 and divide the shoe2 value by 9, So this is the
output.
Output:
$ g++ stu2.cpp
$ a.out
Adidas $ 9.99
Adidas $ 1.11
#include <iostream>
struct sec
int a;
char b;
};
int main()
return 0;
a) 252
b) 253
c) 254
d) 262
View Answer
Answer: a
Explanation: In this program, We are dividing the values of a and b, printing it.
Output:
$ g++ stu5.cpp
$ a.out
252
Answer: a
Explanation: Because in a structure pointer, the data element is declared as above only.
This section on C++ language interview questions and answers focuses on “Operators”. One shall
practice these interview questions to improve their C++ programming skills needed for various
interviews (campus interviews, walkin interviews, company interviews), placements, entrance exams
and other competitive exams. These questions can be attempted by anyone focusing on learning
C++ programming language. They can be a beginner, fresher, engineering graduate or an
experienced IT professional. Our C++ language interview questions come with detailed explanation
of the answers which helps in better understanding of C++ concepts.
Here is a listing of C++ language interview questions on “Operators” along with answers,
explanations and/or solutions:
Answer: d
Explanation: None.
Answer: a
Explanation: The operator which is having highest precedence is postfix and lowest is equality.
Answer: a
Explanation: In this operator, if the condition is true means, it will return the first operator, otherwise
second operator.
#include <iostream>
int main()
int a;
a = 5 + 3 * 5;
cout << a;
return 0;
a) 35
b) 20
c) 25
d) 30
View Answer
Answer: b
Explanation: Because the * operator is having highest precedence, So it is executed first and then
the + operator will be executed.
Output:
$ g++ op1.cpp
$ a.out
20
Answer: a
Explanation: Because the dynamic_cast operator is used to convert from base class to derived
class.
6. What is the output of this program?
#include <iostream>
int main()
int a = 5, b = 6, c, d;
c = a, b;
d = (a, b);
return 0;
a) 5 6
b) 6 5
c) 6 7
d) none of the mentioned
View Answer
Answer: a
Explanation: It is a separtor here.In c,the value a is stored in c and in d the value b is stored in d
because of the bracket.
Output:
$ g++ op3.cpp
$ a.out
56
#include <iostream>
int main()
int i, j;
j = 10;
cout << i;
return 0;
}
a) 1000
b) 11
c) 1010
d) 1001
View Answer
Answer: c
Explanation: j starts with the value 10. j is then incremented to 11. Next, j is added to 100. Finally, j
(still containing 11) is added to 999 which yields the result 1010.
Output:
$ g++ op2.cpp
$ a.out
1010
#include <iostream>
int main ()
int x, y;
x = 5;
y = ++x * ++x;
x = 5;
y = x++ * ++x;
return 0;
a) 749736
b) 736749
c) 367497
d) none of the mentioned
View Answer
Answer: a
Explanation: Because of the precedence the pre-increment and post increment operator, we got the
output as 749736.
Output:
$ g++ op.cpp
$ a.out
749736
#include <iostream>
int main()
int a = 5, b = 6, c;
c = (a > b) ? a : b;
cout << c;
return 0;
a) 6
b) 5
c) 4
d) 7
View Answer
Answer: a
Explanation: Here the condition is false on conditional operator, so the b value is assigned to c.
Output:
$ g++ op1.cpp
$ a.out
6
#include <iostream>
main()
double a = 21.09399;
float b = 10.20;
int c ,d;
c = (int) a;
d = (int) b;
return 0;
a) 20 10
b) 10 21
c) 21 10
d) none of the mentioned
View Answer
Answer: c
Explanation: In this program, we are casting the operator to integer, So it is printing as 21 and 10.
Output:
$ g++ op5.cpp
$ a.out
21 10
This section on C++ language interview questions and answers focuses on “Operators”. One shall
practice these interview questions to improve their C++ programming skills needed for various
interviews (campus interviews, walkin interviews, company interviews), placements, entrance exams
and other competitive exams. These questions can be attempted by anyone focusing on learning
C++ programming language. They can be a beginner, fresher, engineering graduate or an
experienced IT professional. Our C++ language interview questions come with detailed explanation
of the answers which helps in better understanding of C++ concepts.
Here is a listing of C++ language interview questions on “Operators” along with answers,
explanations and/or solutions:
Answer: d
Explanation: None.
2. Which operator is having the highest precedence?
a) postfix
b) unary
c) shift
d) equality
View Answer
Answer: a
Explanation: The operator which is having highest precedence is postfix and lowest is equality.
Answer: a
Explanation: In this operator, if the condition is true means, it will return the first operator, otherwise
second operator.
#include <iostream>
int main()
int a;
a = 5 + 3 * 5;
cout << a;
return 0;
a) 35
b) 20
c) 25
d) 30
View Answer
Answer: b
Explanation: Because the * operator is having highest precedence, So it is executed first and then
the + operator will be executed.
Output:
$ g++ op1.cpp
$ a.out
20
Answer: a
Explanation: Because the dynamic_cast operator is used to convert from base class to derived
class.
#include <iostream>
int main()
int a = 5, b = 6, c, d;
c = a, b;
d = (a, b);
return 0;
a) 5 6
b) 6 5
c) 6 7
d) none of the mentioned
View Answer
Answer: a
Explanation: It is a separtor here.In c,the value a is stored in c and in d the value b is stored in d
because of the bracket.
Output:
$ g++ op3.cpp
$ a.out
56
int main()
int i, j;
j = 10;
cout << i;
return 0;
a) 1000
b) 11
c) 1010
d) 1001
View Answer
Answer: c
Explanation: j starts with the value 10. j is then incremented to 11. Next, j is added to 100. Finally, j
(still containing 11) is added to 999 which yields the result 1010.
Output:
$ g++ op2.cpp
$ a.out
1010
#include <iostream>
int main ()
int x, y;
x = 5;
y = ++x * ++x;
x = 5;
y = x++ * ++x;
cout << x << y;
return 0;
a) 749736
b) 736749
c) 367497
d) none of the mentioned
View Answer
Answer: a
Explanation: Because of the precedence the pre-increment and post increment operator, we got the
output as 749736.
Output:
$ g++ op.cpp
$ a.out
749736
#include <iostream>
int main()
int a = 5, b = 6, c;
c = (a > b) ? a : b;
cout << c;
return 0;
a) 6
b) 5
c) 4
d) 7
View Answer
Answer: a
Explanation: Here the condition is false on conditional operator, so the b value is assigned to c.
Output:
$ g++ op1.cpp
$ a.out
6
10. What is the output of this program?
#include <iostream>
main()
double a = 21.09399;
float b = 10.20;
int c ,d;
c = (int) a;
d = (int) b;
return 0;
a) 20 10
b) 10 21
c) 21 10
d) none of the mentioned
View Answer
Answer: c
Explanation: In this program, we are casting the operator to integer, So it is printing as 21 and 10.
Output:
$ g++ op5.cpp
$ a.out
21 10
This section on online C++ test focuses on “Statements”. One shall practice these test questions to
improve their C++ programming skills needed for various interviews (campus interviews, walkin
interviews, company interviews), placements, entrance exams and other competitive exams. These
questions can be attempted by anyone focusing on learning C++ programming language. They can
be a beginner, fresher, engineering graduate or an experienced IT professional. Our online C++ test
questions come with detailed explanation of the answers which helps in better understanding of C++
concepts.
Here is a listing of online C++ test questions on “Statements” along with answers, explanations
and/or solutions:
1. How many sequence of statements are present in c++?
a) 4
b) 3
c) 5
d) 6
View Answer
Answer: c
Explanation: There are five sequence of statements. They are Preprocessor directives, Comments,
Declarations, Function Declarations, Executable statements.
Answer: b
Explanation: In the conditional operator,it will predicate the output using the given condition.
Answer: b
Explanation: The switch statement is used to choose the certain code to execute, So it is also called
as selective structure.
4. The destination statement for the goto label is identified by what label?
a) $
b) @
c) *
d) :
View Answer
Answer: d
Explanation: None.
#include <iostream>
int main ()
{
int n;
cout << n;
if (n == 3)
break;
return 0;
a) 543
b) 54
c) 5432
d) 53
View Answer
Answer: a
Explanation: Inthis program, We are printing the numbers in reverse order but by using break
statement we stopped printing on 3.
Output:
$ g++ stat.cpp
$ a.out
543
#include <iostream>
int main()
int a = 10;
if (a < 15)
time:
cout << a;
goto time;
}
break;
return 0;
a) 1010
b) 10
c) infinitely print 10
d) compile time error
View Answer
Answer: d
Explanation: Because the break statement need to be presented inside a loop or a switch statement.
#include <iostream>
int main()
int n = 15;
for ( ; ;)
cout << n;
return 0;
a) error
b) 15
c) infinite times of printing n
d) none of the mentioned
View Answer
Answer: c
Explanation: There is not a condition in the for loop, So it will loop continuously.
#include <iostream>
int main()
{
int i;
cout << i;
return 0;
a) 0123456789
b) 10
c) 012345678910
d) compile time error
View Answer
Answer: b
Explanation: for loop with a semicolon is called as body less for loop. It is used only for incrementing
the variable values. So in this program the value is incremented and printed as 10.
Output:
$ g++ stat2.cpp
$ a.out
10
Answer: a
Explanation: There are four types of loop. They are while, do while, nested, for loop.
10. Which looping process is best used when the number of iterations is known?
a) for
b) while
c) do-while
d) all looping processes require that the iterations be known
View Answer
Answer: a
Explanation: None.
Here is a listing of C++ interview questions on “Comments and Indentation” along with answers,
explanations and/or solutions:
Answer: b
Explanation: There are two types of comments. They are double slash and slash stared.
Answer: a
Explanation: Comments are used to add meaning to the program.
Answer: c
Explanation: None.
#include <iostream>
int main()
{
/* this is comment*
return 0;
a) hello world
b) hello
c) compile time error
d) none of the mentioned
View Answer
Answer: c
Explanation: Because the slash should need to be forward not backward.
Answer: a
Explanation: The /* is used to write the multi line comment.
Answer: a
Explanation: None.
#include <iostream>
if (a > 1)
else
return (1);
int main ()
long num = 3;
return 0;
a) 6
b) 24
c) segmentation fault
d) compile time error
View Answer
Answer: c
Explanation: As we have given in the function as a+1, it will exceed the size and so it arises the
segmentation fault.
Output:
$ g++ arg3.cpp
$ a.out
segmentation fault
#include <iostream>
*x = (*x + 1) * (*x);
int main ( )
square(&num);
return 0;
}
a) 100
b) compile time error
c) 144
d) 110
View Answer
Answer: d
Explanation: We have increased the x value in operand as x + 1, so it will return as 110.
Output:
$ g++ arg2.cpp
$ a.out
110
#include <iostream>
int main()
int i = 5, j = 6;
return 0;
int sum = a + b;
a = 7;
return a + b;
a) 11
b) 12
c) 13
d) compile time error
View Answer
Answer: c
Explanation: The value of a has been changed to 7, So it returns as 13.
Output:
$ g++ arg1.cpp
$ a.out
13
Answer: a
Explanation: As void is not having any return value, it will not return the value to the caller.
#include <iostream>
a = b + c;
b = a + c;
c = a + b;
int main()
int x = 2, y =3;
Sum(x, y, y);
return 0;
a) 2 3
b) 6 9
c) 2 15
d) compile time error
View Answer
Answer: c
Explanation: We have passed three values and it will manipulate according to the given condition
and yield the result as 2 15.
Output:
$ g++ arg.cpp
$ a.out
2 15
Here is a listing of tough C++ programming questions on “Function Declarations” along with answers,
explanations and/or solutions:
Answer: b
Explanation: Normally the execution of the program in c++ starts from main only.
Answer: a
Explanation: In a function, return type and function name are mandatory all else are just used as a
choice.
Answer: c
Explanation: None.
4. How many max number of arguments can present in function in c99 compiler?
a) 99
b) 90
c) 102
d) 127
View Answer
Answer: d
Explanation: None.
Answer: b
Explanation: In the call by reference, it will just copy the address of the variable to access it, so it will
reduce the memory in accessing it.
#include <iostream>
void mani()
void mani()
cout<<"hai";
int main()
mani();
return 0;
a) hai
b) haihai
c) compile time error
d) none of the mentioned
View Answer
Answer: c
Explanation: We have to use the semicolon to declare the function in line 3. If we did means, the
program will execute.
#include <iostream>
x = 20;
y = 10;
int main()
int x = 10;
fun(x, x);
cout << x;
return 0;
a) 10
b) 20
c) compile time error
d) none of the mentioned
View Answer
Answer: a
Explanation: In this program, we called by value so the value will not be changed, So the output is 10
Output:
$ g++ fun.cpp
$ a.out
10
8. What is the scope of the variable declared in the user definied function?
a) whole program
b) only inside the {} block
c) main function
d) none of the mentioned
View Answer
Answer: b
Explanation: The variable is valid only in the function block as in other.
Answer: b
Explanation: The main function is the mandatory part, it is needed for the execution of the program to
start.
Here is a listing of tough C++ programming questions on “Argument Passing” along with answers,
explanations and/or solutions:
Answer: c
Explanation: There are three ways of passing a parameter. They are pass by value,pass by reference and
pass by pointer.
Answer: b
Explanation: Because const will not change the value of the variables during the execution.
Answer: a
Explanation: None.
#include <iostream>
a *= 2;
b *= 2;
c *= 2;
int main ()
int x = 1, y = 3, z = 7;
copy (x, y, z);
cout << "x =" << x << ", y =" << y << ", z =" << z;
return 0;
a) 2 5 10
b) 2 4 5
c) 2 6 14
d) none of the mentioned
View Answer
Answer: c
Explanation: Because we multiplied the values by 2 in the copy function.
Output:
$ g++ arg6.cpp
$ a.out
x = 2,y = 6,z = 14
#include <iostream>
x = 20;
int main()
int x = 10;
fun(x);
return 0;
a) 10
b) 20
c) 15
d) none of the mentioned
View Answer
Answer: b
Explanation: As we passed by reference, the value is changed and it is returned as 20.
Output:
$ g++ arg5.cpp
$ a.out
20
#include <iostream>
if (a > 1)
else
return (1);
int main ()
long num = 3;
return 0;
a) 6
b) 24
c) segmentation fault
d) compile time error
View Answer
Answer: c
Explanation: As we have given in the function as a+1, it will exceed the size and so it arises the
segmentation fault.
Output:
$ g++ arg3.cpp
$ a.out
segmentation fault
#include <iostream>
*x = (*x + 1) * (*x);
int main ( )
square(&num);
return 0;
a) 100
b) compile time error
c) 144
d) 110
View Answer
Answer: d
Explanation: We have increased the x value in operand as x+1, so it will return as 110.
Output:
$ g++ arg2.cpp
$ a.out
110
#include <iostream>
int i = 5, j = 6;
return 0;
int sum = a + b;
a = 7;
return a + b;
a) 11
b) 12
c) 13
d) compile time error
View Answer
Answer: c
Explanation: The value of a has been changed to 7, So it returns as 13.
Output:
$ g++ arg1.cpp
$ a.out
13
Answer: a
Explanation: As void is not having any return value, it will not return the value to the caller.
#include <iostream>
using namespace std;
a = b + c;
b = a + c;
c = a + b;
int main()
int x = 2, y =3;
Sum(x, y, y);
return 0;
a) 2 3
b) 6 9
c) 2 15
d) compile time error
View Answer
Answer: c
Explanation: We have passed three values and it will manipulate according to the given condition and
yield the result as 2 15
Output:
$ g++ arg.cpp
$ a.out
2 15
This section on C++ interview questions and answers focuses on “Value Return”. One shall practice
these interview questions to improve their C++ programming skills needed for various interviews
(campus interviews, walkin interviews, company interviews), placements, entrance exams and other
competitive exams. These questions can be attempted by anyone focusing on learning C++
programming language. They can be a beginner, fresher, engineering graduate or an experienced IT
professional. Our C++ interview questions come with detailed explanation of the answers which
helps in better understanding of C++ concepts.
Here is a listing of C++ interview questions on “Value Return” along with answers, explanations
and/or solutions:
Answer: c
Explanation: The three types of returning values are return by value, return by reference and return
by address.
2. What will you use if you are not intended to get a return value?
a) static
b) const
c) volatile
d) void
View Answer
Answer: d
Explanation: Void is used to not to return anything.
3. Where does the return statement returns the execution of the program?
a) main function
b) caller function
c) same function
d) none of the mentioned
View Answer
Answer: b
Explanation: None.
#include <iostream>
return ( a > b ? a : b );
int main()
{
int i = 5;
int j = 7;
return 0;
a) 5
b) 7
c) either 5 or 7
d) none of the mentioned
View Answer
Answer: b
Explanation: In this program, we are returning the maximum value by using conditional operator.
Output:
$ g++ ret.cpp
$ a.out
7
#include <iostream>
double h = 46.50;
double &hours = h;
return hours;
int main()
return 0;
a) 46.5
b) 6.50
c) compile time error
d) none of the mentioned
View Answer
Answer: a
Explanation: We are returning the value what we get as input.
Output:
$ g++ ret1.cpp
$ a.out
46.5
#include <iostream>
int result;
result = 0;
while (y != 0)
result = result + x;
y = y - 1;
return(result);
int main ()
int x = 5, y = 5;
return(0);
a) 20
b) 25
c) 30
d) 35
View Answer
Answer: b
Explanation: We are multiplying these values by adding every values.
Output:
$ g++ ret.cpp
$ a.out
25
Answer: a
Explanation: In function overloading, we can use any number of arguments but same function name.
#include <iostream>
int temp;
while (b != 0)
temp = a % b;
a = b;
b = temp;
return(a);
int main ()
return(0);
a) 15
b) 25
c) 375
d) 5
View Answer
Answer: d
Explanation: In this program, we are finding the gcd of the number.
Output:
$ g++ ret5.cpp
$ a.out
5
This section on C++ language interview questions and answers focuses on “Overloaded Function
Names”. One shall practice these interview questions to improve their C++ programming skills
needed for various interviews (campus interviews, walkin interviews, company interviews),
placements, entrance exams and other competitive exams. These questions can be attempted by
anyone focusing on learning C++ programming language. They can be a beginner, fresher,
engineering graduate or an experienced IT professional. Our C++ language interview questions
come with detailed explanation of the answers which helps in better understanding of C++
concepts.
Here is a listing of C++ language interview questions on “Overloaded Function Names” along
with answers, explanations and/or solutions:
Answer: c
Explanation: None.
2. In which of the following we cannot overload the function?
a) return function
b) caller
c) called function
d) none of the mentioned
View Answer
Answer: a
Explanation: While overloading the return function, it will rise a error, So we can’t overload the
return function.
Answer: b
Explanation: In constructor overloading, we will be using the same options availed in function
overloading.
1. #include <iostream>
2. using namespace std;
3. void print(int i)
4. {
5. cout << i;
6. }
7. void print(double f)
8. {
9. cout << f;
10. }
11. int main(void)
12. {
13. print(5);
14. print(500.263);
15. return 0;
16. }
a) 5500.263
b) 500.2635
c) 500.263
d) none of the mentioned
View Answer
Answer: a
Explanation: In this program, we are printing the values and the values will be print(5) will be
printed first because of the order of the execution.
Output:
$ g++ over.cpp
$ a.out
5500.263
1. #include <iostream>
2. using namespace std;
3. int Add(int X, int Y, int Z)
4. {
5. return X + Y;
6. }
7. double Add(double X, double Y, double Z)
8. {
9. return X + Y;
10. }
11. int main()
12. {
13. cout << Add(5, 6);
14. cout << Add(5.5, 6.6);
15. return 0;
16. }
a) 11 12.1
b) 12.1 11
c) 11 12
d) compile time error
View Answer
Answer: d
Explanation: None.
1. #include <iostream>
2. using namespace std;
3. int operate (int a, int b)
4. {
5. return (a * b);
6. }
7. float operate (float a, float b)
8. {
9. return (a / b);
10. }
11. int main()
12. {
13. int x = 5, y = 2;
14. float n = 5.0, m = 2.0;
15. cout << operate(x, y) <<"\t";
16. cout << operate (n, m);
17. return 0;
18. }
a) 10.0 5.0
b) 5.0 2.5
c) 10.0 5
d) 10 2.5
View Answer
Answer: d
Explanation: In this program, we are divide and multiply the values.
Output:
$ g++ over3.cpp
$ a.out
10 2.5
Answer: c
Explanation: None.
Answer: b
Explanation: In pass by reference, we can use the function to access the variable and it can
modify it. Therefore we are using pass by reference.
9. When our function doesn’t need to return anything means what will we use/send as parameter
in function?
a) void
b) blank space
c) both void & blank space
d) none of the mentioned
View Answer
Answer: b
Explanation: None.
Answer: d
Explanation: None.
This section on C++ questions and puzzles focuses on “Default Arguments”. One shall practice
these questions and puzzles to improve their C++ programming skills needed for various
interviews (campus interviews, walkin interviews, company interviews), placements, entrance
exams and other competitive exams. These programming puzzles can be attempted by anyone
focusing on learning C++ programming language. They can be a beginner, fresher, engineering
graduate or an experienced IT professional. Our C++ questions come with detailed explanation
of the answers which helps in better understanding of C++ concepts.
Here is a listing of C++ questions and puzzles on “Default Arguments” along with answers,
explanations and/or solutions:
1. If the user didn’t supply the value, what value will it take?
a) default value
b) rise an error
c) both default value & rise an error
d) none of the mentioned
View Answer
Answer: a
Explanation: If the user didn’t supply the value means, the compiler will take the given value in
the argument list.
3. Which value will it take when both user and default values are given?
a) user value
b) default value
c) custom value
d) none of the mentioned
View Answer
Answer: a
Explanation: The default value will be used when the user value is not given, So in this case, the
user value will be taken.
1. #include <iostream>
2. using namespace std;
3. void func(int a, bool flag = true)
4. {
5. if (flag == true )
6. {
7. cout << "Flag is true. a = " << a;
8. }
9. else
10. {
11. cout << "Flag is false. a = " << a;
12. }
13. }
14. int main()
15. {
16. func(200, false);
17. return 0;
18. }
Answer: c
Explanation: In this program, we are passing the value, as it evaluates to false, it produces the
output as following.
Output:
$ g++ def.cpp
$ a.out
Flag is false. a = 200
a) 5
b) 6
c) the number you entered
d) compile time error
View Answer
Answer: c
Explanation: In this program, we are getting a number and printing it.
Output:
$ g++ def1.cpp
$ a.out
Please enter a number:
5
Here is your number:5
1. #include <iostream>
2. using namespace std;
3. void Values(int n1, int n2 = 10)
4. {
5. using namespace std;
6. cout << "1st value: " << n1;
7. cout << "2nd value: " << n2;
8. }
9. int main()
10. {
11. Values(1);
12. Values(3, 4);
13. return 0;
14. }
a) 1st value: 1
2nd value: 10
1st value: 3
2nd value: 4
b) 1st value: 1
2nd value: 10
1st value: 3
2nd value: 10
c) compile time error
d) none of the mentioned
View Answer
Answer: a
Explanation: In this program, We are passing the values as by default values rules it is working.
Output:
$ g++ def2.cpp
$ a.out
1st value: 1
2nd value: 10
1st value: 3
2nd value: 4
Answer: b
Explanation: None.
8. If we start our function call with default arguments means, what will be proceeding
arguments?
a) user argument
b) empty arguments
c) default arguments
d) none of the mentioned
View Answer
Answer: c
Explanation: As a rule, the default argument must be followed by default arguments only.
Answer: b
Explanation: None.
1. #include <iostream>
2. using namespace std;
3. int func(int m = 10, int n)
4. {
5. int c;
6. c = m + n;
7. return c;
8. }
9. int main()
10. {
11. cout << func(5);
12. return 0;
13. }
a) 15
b) 10
c) compile time error
d) none of the mentioned
View Answer
Answer: c
Explanation: We can’t use the user argument infront of the default argument.
Here is a listing of C++ Programming quiz on “Unspecified Number of Arguments” along with answers,
explanations and/or solutions:
Answer: c
Explanation: Because the cstdarg defines this header file to process the unknown number of arguments.
2. How can you access the arguments that are manipulated in the function?
a) va_list
b) arg_list
c) both va_list & arg_list
d) none of the mentioned
View Answer
Answer: a
Explanation: None.
#include <iostream>
#include <stdarg.h>
va_list Numbers;
va_start(Numbers, Count);
int Sum = 0;
va_end(Numbers);
return (Sum/Count);
int main()
a) 4
b) 5
c) 6
d) 7
View Answer
Answer: a
Explanation: We are just calculating the average of these numbers using cstdarg.
Output:
$ g++ uka.cpp
$ a.out
Average of first 10 whole numbers 4
Answer: b
Explanation: None.
#include <iostream>
#include <stdarg.h>
int sum = 0;
va_list args;
va_start (args,num);
va_end (args);
return sum;
return 0;
a) 32
b) 23
c) 48
d) compile time error
View Answer
Answer: a
Explanation: We are adding these numbers by using for statement and stdarg.
Output:
$ g++ uka.cpp
$ a.out
The result is 32
#include <iostream>
#include <stdarg.h>
int main()
dumplist(2, 4, 8);
dumplist(3, 6, 9, 7);
return 0;
}
va_list p;
int i;
va_start(p, n);
while (n-->0)
i = va_arg(p, int);
cout << i;
va_end(p);
a) 2436
b) 48697
c) 1111111
d) compile time error
View Answer
Answer: b
Explanation: In this program, we are eradicating the first value
by comparing using while operator.
Output:
$ g++ rka3.cpp
$ a.out
48697
#include <iostream>
#include <stdarg.h>
int main()
{
int x, y;
x = flue('A', 1, 2, 3);
return 0;
return c;
a) 6549
b) 4965
c) 6646
d) compile time error
View Answer
Answer: a
Explanation: In this program, we are returning the ascii value of the character and printing it.
Output:
$ g++ rka4.cpp
$ a.out
6549
8. Which header file should you include if you are to develop a function that can accept variable number
of arguments?
a) varag.h
b) stdlib.h
c) stdio.h
d) stdarg.h
View Answer
Answer: d
Explanation: None.
#include <iostream>
#include <stdarg.h>
int main()
return 0;
va_list ptr;
int num;
va_start(ptr, msg);
a) 6
b) 5
c) 8
d) 4
View Answer
Answer: d
Explanation: In this program, we are moving the pointer to the second value and printing it.
Output:
$ g++ uka6.cpp
$ a.out
4
10. What will initialize the list of arguments in stdarg.h header file?
a) va_list
b) va_start
c) va_arg
d) none of the mentioned
View Answer
Answer: b
Explanation: None.
Here is a listing of C++ questions and puzzles on “Pointer to Function” along with answers, explanations
and/or solutions:
Answer: c
Explanation: None.
Answer: c
Explanation: As it is used to execute a block of code, So we will not allocate or deallocate memory.
Answer: a
Explanation: None.
4. What is te output of this program?
#include <iostream>
int main()
int a;
cout << a;
return 0;
a) 25
b) 35
c) 40
d) 45
View Answer
Answer: c
Explanation: In this program, we are adding two numbers with 15, So we got the output as 40.
Output:
$ g++ pfu2.cpp
$ a.out
40
#include <iostream>
using namespace std;
void func(int x)
cout << x ;
int main()
void (*n)(int);
n = &func;
(*n)( 2 );
n( 2 );
return 0;
a) 2
b) 20
c) 21
d) 22
View Answer
Answer: d
Explanation: As we are calling the function two times with the same value, So it is printing as 22.
Output:
$ g++ pfu.cpp
$ a.out
22
#include <iostream>
int main()
(*p)('d', 9);
p(10, 9);
return 0;
return 0;
a) d9
9
b) d9d9
c) d9
d) compile time error
View Answer
Answer: a
Explanation: None.
Output:
$ g++ pfu1.cpp
$ a.out
d9
9
#include <iostream>
cout << a;
cout << b;
return 0;
int main(void)
{
int(*ptr)(char, int);
ptr = func;
func(2, 3);
ptr(2, 3);
return 0;
a) 2323
b) 232
c) 23
d) compile time error
View Answer
Answer: d
Explanation: In this program, we can’t do the casting from char to int, So it is raising an error.
Answer: c
Explanation: The data types are mandatory for declaring the variables in the function pointers.
Answer: c
Explanation: None.
Here is a listing of C++ interview questions on “Macros” along with answers, explanations and/or
solutions:
Answer: c
Explanation: None.
Answer: a
Explanation: None.
Answer: b
Explanation: There are two types of macros. They are object-like and function-like.
4. What is the mandatory preprosessor directive for c++?
a) #define <iostream>
b) #include <iostream>
c) #undef <iostream>
d) none of the mentioned
View Answer
Answer: b
Explanation: For a c++ program to execute, we need #include<iostream>.
#include <iostream>
int main ()
float i, j;
i = 100.1;
j = 100.01;
return 0;
a) 100.01
b) 100.1
c) compile time error
d) none of the mentioned
View Answer
Answer: a
Explanation: In this program, we are getting the minimum number using conditional operator.
Output:
$ g++ mac3.cpp
$ a.out
The minimum value is 100.01
#include <iostream>
using namespace std;
int main ()
return 0;
a) 5
b) details about your file
c) compile time error
d) none of the mentioned
View Answer
Answer: b
Explanation: In this program, we are using the macros to print the information about the file.
Output:
$ g++ mac2.cpp
$ a.out
Value of __LINE__ : 5
Value of __FILE__ : mac1.cpp
Value of __DATE__ : Oct 10 2012
Value of __TIME__ : 22:24:37
#include <iostream>
#define SquareOf(x) x * x
int main()
int x;
return 0;
}
a) 16
b) 64
c) compile time error
d) none of the mentioned
View Answer
Answer: d
Explanation: In this program, as we haven’t initiailzed the variable x, we will get a output of ending digit
of 4.
Output:
$ g++ mac1.cpp
$ a.out
75386824
#include <iostream>
#define PR(id) cout << "The value of " #id " is "<<id
int main()
int i = 10;
PR(i);
return 0;
a) 10
b) 15
c) 20
d) none of the mentioned
View Answer
Answer: a
Explanation: In this program, we are just printing the declared values.
Output:
$ g++ mac.cpp
$ a.out
10
#define MAX 10
int main()
int num;
num = ++MAX;
return 0;
a) 11
b) 10
c) compile time error
d) none of the mentioned
View Answer
Answer: c
Explanation: Macro Preprocessor only replaces occurance of macro symbol with macro symbol value, So
we can’t increment the value.
Answer: a
Explanation: When the compiler encounters a previously defined macro, it will take the result from that
execution itself.
Here is a listing of C++ quiz on “Modularization and Interfaces” along with answers, explanations and/or
solutions:
Answer: b
Explanation: None.
2. What is the ability to group some lines of code that can be included
in the program?
a) specific task
b) program control
c) modularization
d) macros
View Answer
Answer: c
Explanation: Modularization is also similar to macros but it is used to build large projects.
Answer: b
Explanation: There are two types of functions.They are program control and specific task.
Answer: c
Explanation: Because they access the functions in the module using interface.
Answer: a
Explanation: None.
Answer: c
Explanation: None.
Answer: b
Explanation: We can include the group of code by using the #include header file.
C++ Puzzles - Namespaces - Sanfoundry
by Manish
This section on C++ questions and puzzles focuses on “Namespaces”. One shall practice these
questions and puzzles to improve their C++ programming skills needed for various interviews
(campus interviews, walkin interviews, company interviews), placements, entrance exams and
other competitive exams. These programming puzzles can be attempted by anyone focusing on
learning C++ programming language. They can be a beginner, fresher, engineering graduate or
an experienced IT professional. Our C++ questions come with detailed explanation of the
answers which helps in better understanding of C++ concepts.
Here is a listing of C++ questions and puzzles on “Namespaces” along with answers,
explanations and/or solutions:
Answer: c
Explanation: None.
Answer: a
Explanation: Namespace allow you to group class, objects and functions. It is used to divide the
global scope into the sub-scopes.
Answer: b
Explanation: The main aim of the namespace is to understand the logical units of the program
and to make the program so robust.
4. What is the general syntax for accessing the namespace variable?
a) namespaceid::operator
b) namespace,operator
c) namespace#operator
d) none of the mentioned
View Answer
Answer: a
Explanation: None.
1. #include <iostream>
2. using namespace std;
3. namespace first
4. {
5. int var = 5;
6. }
7. namespace second
8. {
9. double var = 3.1416;
10. }
11. int main ()
12. {
13. int a;
14. a = first::var + second::var;
15. cout << a;
16. return 0;
17. }
a) 8.31416
b) 8
c) 9
d) compile time error
View Answer
Answer: b
Explanation: As we are getting two variables from namespace variable and we are adding that.
Output:
$ g++ name.cpp
$ a.out
8
1. #include <iostream>
2. using namespace std;
3. namespace first
4. {
5. int x = 5;
6. int y = 10;
7. }
8. namespace second
9. {
10. double x = 3.1416;
11. double y = 2.7183;
12. }
13. int main ()
14. {
15. using first::x;
16. using second::y;
17. bool a, b;
18. a = x > y;
19. b = first::y < second::x;
20. cout << a << b;
21. return 0;
22. }
a) 11
b) 01
c) 00
d) 10
View Answer
Answer: d
Explanation: We are inter mixing the variable and comparing it which is bigger and smaller and
according to that we are printing the output.
Output:
$ g++ name1.cpp
$ a.out
10
1. #include <iostream>
2. using namespace std;
3. namespace Box1
4. {
5. int a = 4;
6. }
7. namespace Box2
8. {
9. int a = 13;
10. }
11. int main ()
12. {
13. int a = 16;
14. Box1::a;
15. Box2::a;
16. cout << a;
17. return 0;
18. }
a) 4
b) 13
c) 16
d) compile time error
View Answer
Answer: c
Explanation: In this program, as there is lot of variable a and it is printing the value inside the
block because it got the highest priority.
Output:
$ g++ name2.cpp
$ a.out
16
1. #include <iostream>
2. using namespace std
3. namespace space
4. {
5. int x = 10;
6. }
7. namespace space
8. {
9. int y = 15;
10. }
11. int main(int argc, char * argv[])
12. {
13. space::x = space::y =5;
14. cout << space::x << space::y;
15. }
a) 1015
b) 1510
c) 55
d) compile time error
View Answer
Answer: c
Explanation: We are overriding the value at the main function and so we are getting the output as
55.
Output:
$ g++ name4.cpp
$ a.out
55
1. #include <iostream>
2. using namespace std;
3. namespace extra
4. {
5. int i;
6. }
7. void i()
8. {
9. using namespace extra;
10. int i;
11. i = 9;
12. cout << i;
13. }
14. int main()
15. {
16. enum letter { i, j};
17. class i { letter j; };
18. ::i();
19. return 0;
20. }
a) 9
b) 10
c) compile time error
d) none of the mentioned
View Answer
Answer: a
Explanation: A scope resolution operator without a scope qualifier refers to the global
namespace.
Answer: a
Explanation: None.
Answer: b
Explanation: When a exception is arised mean, the exception is caught by handlers and then it decides
the type of exception.
Answer: c
Explanation: The try() statement is used for exceptios in c++.
3. What will happen when the exception is not caught in the program?
a) error
b) program will execute
c) block of that code will not execute
d) none of the mentioned
View Answer
Answer: a
Explanation: None.
#include <iostream>
int main()
int age = 0;
try
{
if (age < 0)
return 0;
a) 0
b) error:Positive Number Required
c) compile time error
d) none of the mentioned
View Answer
Answer: a
Explanation: As the zero marks the beginning of the positive number, it is printed as output
Output:
$ g++ excep.cpp
$ a.out
0
#include <iostream>
int Num;
Num = 1;
while (true)
{
throw Num;
Num++;
int main(void)
try
PrintSequence(20);
catch(int ExNum)
return 0;
Answer: c
Explanation: In this program, we are printing upto 19 numbers and when executing the 20, we are
raising a exception.
Output:
$ g++ excep1.cpp
$ a.out
12345678910111213141516171819Caught an exception with value: 20
if (b == 0)
return (a / b);
int main ()
int x = 50;
int y = 2;
double z = 0;
try
z = division(x, y);
cout << z;
return 0;
a) 25
b) 20
c) Division by zero condition!
d) None of the mentioned
View Answer
Answer: a
Explanation: In this program, we resembling the division by using the exception handling.
Output:
$ g++ excep2.cpp
$ a.out
25
#include <iostream>
int main()
char* buff;
try
if (buff == 0)
else
catch(char *strg)
return 0;
Answer: d
Explanation: As we are allocating the memory to the variables and if there is not suffcient size means, it
will throw an exception.
Output:
$ g++ excep3.cpp
$ a.out
4 Bytes allocated successfully
#include <iostream>
void Funct();
int main()
try
Funct();
catch(double)
return 0;
void Funct()
throw 3;
Answer: c
Explanation: As we are throwing integer to double it will raise as abnormal program after termination
throw statement.
Output:
$ g++ excep4.cpp
$ a.out
terminate called after throwing an instance of ‘int’
Aborted
#include <iostream>
#include <exception>
int main()
try
catch(bad_alloc&)
return 0;
a) Allocated successfully
b) Error allocating the requested memory
c) Depends on the memory of the computer
d) None of the mentioned
View Answer
Answer: c
Explanation: In this program, we allocating the memory to the arrays by using excetion handling and we
handled the exception by standard exception.
Output:
$ g++ excep5.cpp
$ a.out
Allocated successfully
10. What will happen when the handler is not found for exception?
a) calls the standard library function terminate()
b) raise an error
c) executes the remaining block
d) none of the mentioned
View Answer
Answer: a
Explanation: None.
Here is a listing of C++ questions and puzzles on “Linkage” along with answers, explanations and/or
solutions:
Answer: c
Explanation: There are three types of linkage in c++. They are internal linkage, external linkage and no
linkage.
Answer: a
Explanation: None.
Answer: b
Explanation: In the external linkage, it is used to refer to identifiers in various programs.
#ifndef Exercise_H
#define Exercise_H
#endif
2.
#include <iostream>
#include "exe.h"
{
cout << number++;
return 0;
a) 842
b) 843
c) compile time error
d) none of the mentioned
View Answer
Answer: a
Explanation: In this program, we have created a header file and linked that into the source program and
we are post incrementing that because of that it is printed as 842.
Output:
$ g++ link.cpp
$ a.out
842
5. What is the defualt type oof linkage that are available for identifires?
a) internal
b) external
c) no linkage
d) none of the mentioned
View Answer
Answer: b
Explanation: None.
Answer: b
Explanation: Extern keyword is used to represent identifiers from other programs.
Answer: c
Explanation: None.
Here is a listing of C++ interview questions on “Header Files Usage” along with answers, explanations
and/or solutions:
Answer: b
Explanation: None.
Answer: a
Explanation: The iostream.h is used in the older versions of c++ and iostream is evolved from it in the std
namespace.
Answer: c
Explanation: In the header file, we define something that to be manipulated in the program.
#include <iostream>
int main()
char name[30];
gets(name);
puts(name);
return 0;
}
a) jobsjobs
b) jobs
c) compile time error
d) program will not run
View Answer
Answer: c
Explanation: In this program,we need to string header file to run this program.
Answer: b
Explanation: The iomanip header file is used to correct the precision of the values.
Answer: c
Explanation: None.
Answer: b
Explanation: None.
9. Which of the following header files is required for creating and reading data files?
a) ofstream.h
b) fstream.h
c) ifstream.h
d) console.h
View Answer
Answer: b
Explanation: In this fstream.h header file is used for accessing the files only.
#include <iostream>
#include <stdarg.h>
va_list Numbers;
va_start(Numbers, Count);
int Sum = 0;
va_end(Numbers);
return (Sum/Count);
int main()
return 0;
a) 4
b) 5
c) 6
d) compile time error
View Answer
Answer: a
Explanation: In this program, we are finding the average of first 10 numbers using stdarg header file
Output:
$ g++ std.cpp
$ a.out
4
Here is a listing of C++ quiz on “Classes” along with answers, explanations and/or solutions:
Answer: C
Explanation: The classes in c++ are used to manipulate both data and functions.
Answer: c
Explanation: There are three types of access specifiers. They are public, protected and private.
Answer: b
Explanation: None.
4. Which other keywords are also used to declare the class other than class?
a) struct
b) union
c) object
d) both struct & union
View Answer
Answer: d
Explanation: Struct and union take the same definition of class but differs in the access techniques.
#include <iostream>
class rect
int x, y;
public:
int area ()
return (x * y);
};
x = a;
y = b;
int main ()
rect rect;
a) rect area:12
b) rect area: 12
c) rect area:24
d) none of the mentioned
View Answer
Answer: b
Explanation: In this program, we are calculating the area of rectangle based on given values.
Output:
$ g++ class.cpp
$ a.out
rect area: 12
#include <iostream>
class CDummy
public:
};
if (¶m == this)
return true;
else
return false;
int main ()
CDummy a;
CDummy *b = &a;
if (b->isitme(a))
else
cout<<"not execute";
return 0;
a) execute
b) not execute
c) none of the mentioned
d) both execute & not execute
View Answer
Answer: a
Explanation: In this program, we are just pointing the pointer to a object and printing execute if it is
correctly pointed.
Output:
$ g++ class1.cpp
$ a.out
execute
Answer: a
Explanation: None.
Answer: b
Explanation: None.
Answer: a
Explanation: Once the object is declared means, the constructor are also declared by default.
10. When struct is used instead of the keyword class means, what will happen in the program?
a) access is public by default
b) access is private by default
c) access is protected by default
d) none of the mentioned
View Answer
Answer: a
Explanation: None.
This section on C++ MCQs (multiple choice questions) focuses on “User Defined Types”. One
shall practice these MCQs to improve their C++ programming skills needed for various
interviews (campus interviews, walkin interviews, company interviews), placements, entrance
exams and other competitive exams. These questions can be attempted by anyone focusing on
learning C++ programming language. They can be a beginner, fresher, engineering graduate or
an experienced IT professional. Our multiple choice questions come with detailed explanation of
the answers which helps in better understanding of C++ concepts.
Here is a listing of C multiple choice questions on “User Defined Types” along with answers,
explanations and/or solutions:
Answer: c
Explanation: None.
Answer: a
Explanation: By using typedef, we can create a type of pre-existing type only not our own type
of data.
Answer: d
Explanation: Union is used to define the data types of our choice and it will store the data type in
one location make them accessible.
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. typedef int num;
6. num a = 10, b = 15;
7. num c = a + b + a - b;
8. cout << c;
9. return 0;
10. }
a) 20
b) 15
c) 30
d) 25
View Answer
Answer: a
Explanation: In this program, we are manipulating the numbers and printing the result using
user-defined data types.
Output:
$ g++ user.cpp
$ a.out
20
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int i;
6. enum month
7. {
8. JAN,FEB,MAR,APR,MAY,JUN,JUL,AUG,SEP,OCT,DEC
9. };
10. for (i = JAN; i <= DEC; i++)
11. cout << i;
12. return 0;
13. }
a) 012345678910
b) 0123456789
c) 01234567891011
d) none of the mentioned
View Answer
Answer: a
Explanation: In this program, we are defined the data types as enumerator and printing its value
in a order.
Output:
$ g++ user1.cpp
$ a.out
012345678910
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. typedef int num;
6. typedef char let;
7. let w = "steve";
8. num a = 10, b = 15;
9. num c = a + w;
10. cout << c;
11. return 0;
12. }
a) 10steve
b) steve10
c) compile time error
d) compile but not run
View Answer
Answer: c
Explanation: Error: invalid conversion from ‘const char*’ to ‘let {aka char}’.
Answer: a
Explanation: None.
Answer: c
Explanation: There are three types of user-defined data types. They are typedef, union,
enumerator.
Answer: b
Explanation: We are defining the user-defined data type to be availed only inside that program, if
we want to use anywhere means we have to define those types in the header file.
10. How many types of models are available to create the user-defined data type?
a) 1
b) 2
c) 3
d) 4
View Answer
Answer: b
Explanation: There are two types of models. They are references to built-in types and multipart
types.
Here is a listing of C++ quiz on “Objects” along with answers, explanations and/or solutions:
Answer: a
Explanation: In class only all the listed items except class will be declared.
Answer: c
Explanation: Objects in the method can be accessed using direct member access operator which is (.).
3. Which of these following members are not accessed by using direct member access operator?
a) public
b) private
c) protected
d) both private & protected
View Answer
Answer: d
Explanation: Because of the access given to the private and protected, We can’t access them by using
direct member access operator.
#include <iostream>
class Box
public :
double length;
double breadth;
double height;
};
int main( )
Box Box1;
double volume;
Box1.height = 5;
Box1.length = 6;
Box1.breadth = 7.1;
return 0;
a) 210
b) 213
c) 215
d) 217
View Answer
Answer: b
Explanation: In the above program, we are calculating the area of the cube by using the cube formula
Output:
$ g++ obj1.cpp
$ a.out
213
#include <iostream>
class Rect
int x, y;
public:
int area ()
return (x * y);
};
x = a;
y = b;
int main ()
return 0;
}
Answer: a
Explanation: We are calculating the area of rectangle by two objects.
Answer: d
Explanation: None.
Answer: d
Explanation: Because a class may contain any number of objects according to it’s compliance.
#include <iostream>
class sample
private:
int var;
public:
void input()
{
cout << var;
void output()
};
int main()
sample object;
object.input();
object.output();
object.var();
return 0;
a) Enter an integer 5
Variable entered is 5
b) Runtime error
c) Error
d) None of the mentioned
View Answer
Answer: c
Explanation: While using private member, you can’t access it variable.
Answer: a
Explanation: None.
10. What is the output of this program?
#include <iostream>
class number
int i;
public:
int geti();
};
int number::geti()
return i;
void number::puti(int j)
i = j;
int main()
number s;
s.puti(10);
return 0;
a) 10
b) 11
c) 20
d) 22
View Answer
Answer: a
Explanation: We are getting the number and copying it to j and printing it.
Output:
$ g++ obj2.cpp
$ a.out
10
This section on C++ questions and puzzles focuses on “Operator Functions”. One shall practice
these questions and puzzles to improve their C++ programming skills needed for various
interviews (campus interviews, walkin interviews, company interviews), placements, entrance
exams and other competitive exams. These programming puzzles can be attempted by anyone
focusing on learning C++ programming language. They can be a beginner, fresher, engineering
graduate or an experienced IT professional. Our C++ questions come with detailed explanation
of the answers which helps in better understanding of C++ concepts.
Here is a listing of C++ questions and puzzles on “Operator Functions” along with answers,
explanations and/or solutions:
Answer: b
Explanation: None.
Answer: a
Explanation: None.
Answer: a
Explanation: We have to declare the operator function by using operator, operator sign. Example
“operator +” where operator is a keyword and + is the symbol need to be overloaded.
1. #include <iostream>
2. using namespace std;
3. class sample
4. {
5. public:
6. int x, y;
7. sample() {};
8. sample(int, int);
9. sample operator + (sample);
10. };
11. sample::sample (int a, int b)
12. {
13. x = a;
14. y = b;
15. }
16. sample sample::operator+ (sample param)
17. {
18. sample temp;
19. temp.x = x + param.x;
20. temp.y = y + param.y;
21. return (temp);
22. }
23. int main ()
24. {
25. sample a (4,1);
26. sample b (3,2);
27. sample c;
28. c = a + b;
29. cout << c.x << "," << c.y;
30. return 0;
31. }
a) 5, 5
b) 7, 3
c) 3, 7
d) None of the mentioned
View Answer
Answer: b
Explanation: In this program, we are adding the first number of a with first number of b by using
opertor function and also we are adding second number by this method also.
Output:
$ g++ oper.cpp
$ a.out
7, 3
1. #include <iostream>
2. using namespace std;
3. class Box
4. {
5. double length;
6. double breadth;
7. double height;
8. public:
9. double getVolume(void)
10. {
11. return length * breadth * height;
12. }
13. void setLength( double len )
14. {
15. length = len;
16. }
17. void setBreadth( double bre )
18. {
19. breadth = bre;
20. }
21. void setHeight( double hei )
22. {
23. height = hei;
24. }
25. Box operator+(const Box& b)
26. {
27. Box box;
28. box.length = this->length + b.length;
29. box.breadth = this->breadth + b.breadth;
30. box.height = this->height + b.height;
31. return box;
32. }
33. };
34. int main( )
35. {
36. Box Box1;
37. Box Box2;
38. Box Box3;
39. double volume = 0.0;
40. Box1.setLength(6.0);
41. Box1.setBreadth(7.0);
42. Box1.setHeight(5.0);
43. Box2.setLength(12.0);
44. Box2.setBreadth(13.0);
45. Box2.setHeight(10.0);
46. volume = Box1.getVolume();
47. cout << "Volume of Box1 : " << volume <<endl;
48. volume = Box2.getVolume();
49. cout << "Volume of Box2 : " << volume <<endl;
50. Box3 = Box1 + Box2;
51. volume = Box3.getVolume();
52. cout << "Volume of Box3 : " << volume <<endl;
53. return 0;
54. }
Answer: a
Explanation: In this program, we finding the box3 area by adding box1 and box2.
Output:
$ g++ oper1.cpp
$ a.out
Volume of Box1 : 210
Volume of Box2 : 1560
Volume of Box3 : 5400
1. #include <iostream>
2. using namespace std;
3. class Integer
4. {
5. int i;
6. public:
7. Integer(int ii) : i(ii) {}
8. const Integer
9. operator+(const Integer& rv) const
10. {
11. cout << "operator+" << endl;
12. return Integer(i + rv.i);
13. }
14. Integer&
15. operator+=(const Integer& rv)
16. {
17. cout << "operator+=" << endl;
18. i += rv.i;
19. return *this;
20. }
21. };
22. int main()
23. {
24. int i = 1, j = 2, k = 3;
25. k += i + j;
26. Integer ii(1), jj(2), kk(3);
27. kk += ii + jj;
28. }
a) operator+
operator+=
b) operator+=
operator+
c) operator+
operator+
d) none of the mentioned
View Answer
Answer: a
Explanation: We are using two operator functions and executing them and result is printed
according to the order.
Output:
$ g++ oper2.cpp
$ a.out
operator+
operator+=
1. #include <iostream>
2. using namespace std;
3. class myclass
4. {
5. public:
6. int i;
7. myclass *operator->()
8. {return this;}
9. };
10. int main()
11. {
12. myclass ob;
13. ob->i = 10;
14. cout << ob.i << " " << ob->i;
15. return 0;
16. }
a) 10 10
b) 11 11
c) error
d) runtime error
View Answer
Answer: a
Explanation: In this program, -> operator is used to describe the member of the class and so we
are getting this output.
Output:
$ g++ char4.cpp
$ a.out
10 10
Answer: d
Explanation: None.
9. Operator overloading is
a) making c++ operator works with objects
b) giving new meaning to existing operator
c) making new operator
d) adding operation to the existing operators
View Answer
Answer: d
Explanation: Operator overloading is the way adding operation to the existing operators.
1. #include <iostream>
2. using namespace std;
3. ostream & operator<<(ostream & i, int n)
4. {
5. return i;
6. }
7. int main()
8. {
9. cout << 5 << endl;
10. cin.get();
11. return 0;
12. }
a) 5
b) 6
c) error
d) runtime error
View Answer
Answer: c
Explanation: In this program, there will arise an ambiguous overload for 5.
Here is a listing of C++ interview questions on “Complex Number Type” along with answers,
explanations and/or solutions:
Answer: b
Explanation: None.
Answer: b
Explanation: We can declare the complex number by using complex(3,4) where 3 is a real number and 4
is imaginary part.
#include <iostream>
#include <complex>
int main()
c2 = pow(c1, 2.0);
return 0;
a) (-240, 128)
b) (240, 128)
c) (240, 120)
d) None of the mentioned
View Answer
Answer: a
Explanation: In this program, we are finding the square of the complex number.
Output:
$ g++ comp.cpp
$ a.out
(-240,128)
#include <iostream>
#include <complex>
int main()
c_double *= 2;
c_double = c_int;
return 0;
a) (2, 3)
b) (4, 5)
c) (8, 15)
d) None of the mentioned
View Answer
Answer: b
Explanation: We are just copying the value of c_int into c_double, So it’s printing as (4,5).
Output:
$ g++ comp1.cpp
$ a.out
(4,5)
#include <iostream>
#include <complex>
int main()
i = i * 6 / 3;
cout << i;
return 0;
a) (4, 6)
b) (2, 3)
c) (6, 12)
d) None of the mentioned
View Answer
Answer: a
Explanation: We are multiplying the complex number by 2.
Output:
$ g++ comp2.cpp
$ a.out
(4,6)
#include <iostream>
#include <complex>
int main()
complex<double> c1(4.0,3.0);
complex<float> c2(polar(5.0,0.75));
return 0;
a) c1: (4,3)(7.65844,6.40819)
b) c1: (4,3)(7,6)
c) both c1: (4,3)(7.65844,6.40819) & c1: (4,3)(7,6)
d) None of the mentioned
View Answer
Answer: a
Explanation: We are adding the two complex numbers and printing the result.
Output:
$ g++ comp3.cpp
$ a.out
c1: (4,3)(7.65844,6.40819)
#include <iostream>
#include <complex>
return 0;
a) (4.0, 3.0)
b) (6.12132, 3.70711)
c) (5.0, 0.75)
d) None of the mentioned
View Answer
Answer: b
Explanation: In this program, we are adding both complex number and finding the square root of it.
Output:
$ g++ comp4.cpp
$ a.out
(6.12132,3.70711)
Answer: d
Explanation: None.
#include <iostream>
#include <complex>
int main ()
return 0;
a) 2
b) 20
c) 40
d) None of the mentioned
View Answer
Answer: a
Explanation: imag part will return the imaginery part of the complex number.
Output:
$ g++ comp5.cpp
$ a.out
2
Here is a listing of C++ quiz on “Conversion Operators” along with answers, explanations and/or
solutions:
Answer: d
Explanation: Conversion operator doesn’t have any return type not even void.
Answer: a
Explanation: It is used to check that operators and operands are compatible after conversion.
Answer: a
Explanation: None.
#include <iostream>
class sample1
float i, j;
};
class sample2
int x, y;
public:
x = a;
y = b;
int result()
return x + y;
}
};
int main ()
sample1 d;
sample2 * padd;
return 0;
a) 20
b) runtime error
c) random number
d) runtime error or random number
View Answer
Answer: d
Explanation: As it assigns to a reference to an object of another incompatible type using explicit type-
casting.
Output:
$ g++ con.cpp
$ a.out
14032334
#include <iostream>
class sample
public:
sample(int i) : m_i(i) { }
public:
{
return m_i + i;
return m_i;
private:
int m_i;
};
int f(char c)
return c;
int main()
sample f(2);
return 0;
a) 3
b) 4
c) 5
d) None of the mentioned
View Answer
Answer: b
Explanation: In this program, we are adding its value with it itself, So only we got the output as 4.
Output:
$ g++ con1.cpp
$ a.out
4
#include <cmath>
class Complex
private:
double real;
double imag;
public:
{}
double mag()
return getMag();
operator double ()
return getMag();
private:
double getMag()
};
int main()
return 0
a) 5 5
b) 4 5
c) 6 6
d) None of the mentioned
View Answer
Answer: a
Explanation: In this program, we are calculating the magnitude value by two ways.
Output:
$ g++ con3.cpp
$ a.out
55
#include <iostream>
#include <string>
class test
public:
operator string ()
return "Converted";
};
int main()
test t;
string s = t;
return 0;
}
a) converted
b) error
c) run time error
d) none of the mentioned
View Answer
Answer: a
Explanation: In this program, We casted the string to the object of the class.
Output:
$ g++ con4.cppp
$ a.out
converted
#include <iostream>
int main()
double a = 21.09399;
float b = 10.20;
int c ;
c = (int) a;
cout << c ;
c = (int) b;
cout << c ;
return 0;
a) 2110
b) 1210
c) 21
d) None of the mentioned
View Answer
Answer: a
Explanation: In this program, we casted the data type to integer.
Output:
$ g++ con5.cpp
$ a.out
2110
Answer: b
Explanation: There are two types of user-defined conversions.They are conversion by constructor,
Conversion functions.
Answer: a
Explanation: None.
This section on C++ MCQs (multiple choice questions) focuses on “Friends”. One shall practice
these MCQs to improve their C++ programming skills needed for various interviews (campus
interviews, walkin interviews, company interviews), placements, entrance exams and other
competitive exams. These questions can be attempted by anyone focusing on learning C++
programming language. They can be a beginner, fresher, engineering graduate or an experienced
IT professional. Our multiple choice questions come with detailed explanation of the answers
which helps in better understanding of C++ concepts.
Here is a listing of C multiple choice questions on “Friends” along with answers, explanations
and/or solutions:
Answer: a
Explanation: Friend is used to access private and protected members of a class from outside the
same class.
Answer: b
Explanation: None.
Answer: a
Explanation: In option a, the class2 is the friend of class1 and it can access all the private and
protected members of class1.
1. #include <iostream>
2. using namespace std;
3. class Box
4. {
5. double width;
6. public:
7. friend void printWidth( Box box );
8. void setWidth( double wid );
9. };
10. void Box::setWidth( double wid )
11. {
12. width = wid;
13. }
14. void printWidth( Box box )
15. {
16. box.width = box.width * 2;
17. cout << "Width of box : " << box.width << endl;
18. }
19. int main( )
20. {
21. Box box;
22. box.setWidth(10.0);
23. printWidth( box );
24. return 0;
25. }
a) 40
b) 5
c) 10
d) 20
View Answer
Answer: d
Explanation: We are using the friend function for printwidth and multiplied the width value by 2,
So we got the output as 20
Output:
$ g++ friend.cpp
$ a.out
20
1. #include <iostream>
2. using namespace std;
3. class sample
4. {
5. int width, height;
6. public:
7. void set_values (int, int);
8. int area () {return (width * height);}
9. friend sample duplicate (sample);
10. };
11. void sample::set_values (int a, int b)
12. {
13. width = a;
14. height = b;
15. }
16. sample duplicate (sample rectparam)
17. {
18. sample rectres;
19. rectres.width = rectparam.width * 2;
20. rectres.height = rectparam.height * 2;
21. return (rectres);
22. }
23. int main ()
24. {
25. sample rect, rectb;
26. rect.set_values (2, 3);
27. rectb = duplicate (rect);
28. cout << rectb.area();
29. return 0;
30. }
a) 20
b) 16
c) 24
d) None of the mentioned
View Answer
Answer: c
Explanation: In this program, we are using the friend function for duplicate function and
calculating the area of the rectangle.
Output:
$ g++ friend1.cpp
$ a.out
24
1. #include <iostream>
2. using namespace std;
3. class sample;
4. class sample1
5. {
6. int width, height;
7. public:
8. int area ()
9. {
10. return (width * height);}
11. void convert (sample a);
12. };
13. class sample
14. {
15. private:
16. int side;
17. public:
18. void set_side (int a)
19. {
20. side = a;
21. }
22. friend class sample1;
23. };
24. void sample1::convert (sample a)
25. {
26. width = a.side;
27. height = a.side;
28. }
29. int main ()
30. {
31. sample sqr;
32. sample1 rect;
33. sqr.set_side(6);
34. rect.convert(sqr);
35. cout << rect.area();
36. return 0;
37. }
a) 24
b) 35
c) 16
d) 36
View Answer
Answer: d
Explanation: In this program, we are using the friend for the class and calculating the area of the
square.
Output:
$ g++ friend2.cpp
$ a.out
36
1. #include <iostream>
2. using namespace std;
3. class base
4. {
5. int val1, val2;
6. public:
7. int get()
8. {
9. val1 = 100;
10. val2 = 300;
11. }
12. friend float mean(base ob);
13. };
14. float mean(base ob)
15. {
16. return float(ob.val1 + ob.val2) / 2;
17. }
18. int main()
19. {
20. base obj;
21. obj.get();
22. cout << mean(obj);
23. return 0;
24. }
a) 200
b) 150
c) 100
d) 300
View Answer
Answer: a
Explanation: In this program, We are finding the mean value by declaring the function mean as a
friend of class base.
Output:
$ g++ friend3.cpp
$ a.out
200
1. #include <iostream>
2. using namespace std;
3. class sample
4. {
5. private:
6. int a, b;
7. public:
8. void test()
9. {
10. a = 100;
11. b = 200;
12. }
13. friend int compute(sample e1);
14. };
15. int compute(sample e1)
16. {
17. return int(e1.a + e1.b) - 5;
18. }
19. int main()
20. {
21. sample e;
22. e.test();
23. cout << compute(e);
24. return 0;
25. }
a) 100
b) 200
c) 300
d) 295
View Answer
Answer: d
Explanation: In this program, we are finding a value from the given function by using the friend
for compute function.
Output:
$ g++ friend4.cpp
$ a.out
295
Answer: c
Explanation: None.
Answer: a
Explanation: The keyword friend is placed only in the function declaration of the friend function
and not in the function definition because it is used toaccess the member of a class.
This section on C++ quiz focuses on “Large Objects”. One shall practice these quizzes to
improve their C++ programming skills needed for various interviews (campus interviews, walkin
interviews, company interviews), placements, entrance exams and other competitive exams.
These questions can be attempted by anyone focusing on learning C++ programming language.
They can be a beginner, fresher, engineering graduate or an experienced IT professional. Our
C++ quiz comes with detailed explanation of the answers which helps in better understanding of
C++ concepts.
Here is a listing of C++ quiz on “Large Objects” along with answers, explanations and/or
solutions:
1. How to store the large objects in c++ if it extents its allocated memory?
a) memory heap
b) stack
c) queue
d) none of the mentioned
View Answer
Answer: a
Explanation: None.
2. When we are using heap operations what do we need to do to save the memory?
a) rename the objects
b) delete the objects after processing
c) both rename & delete the objects
d) none of the mentioned
View Answer
Answer: b
Explanation: when you allocate memory from the heap, you must remember to clean up objects
when you’re done! Failure to do so is called a memory leak.
Answer: c
Explanation: Because vector is mainly used to store large objects for game
programming and other operations etc.
1. #include <iostream>
2. using namespace std;
3. class sample
4. {
5. public:
6. sample()
7. {
8. cout << "X::X()" << endl;
9. }
10. sample( sample const & )
11. {
12. cout << "X::X( X const & )" << endl;
13. }
14. sample& operator=( sample const & )
15. {
16. cout << "X::operator=(X const &)" << endl;
17. }
18. };
19. sample f()
20. {
21. sample tmp;
22. return tmp;
23. }
24. int main()
25. {
26. sample x = f();
27. return 0;
28. }
Answer: c
Explanation: As we are passing the object without any attributes it will return as X::X().
Output:
$ g++ large.cpp
$ a.out
X::X()
Answer: d
Explanation: None.
Answer: d
Explanation: Virtual destructor means is that the object is destructed in reverse order in which it
was constructed and the smart pointer will delete the object from memory when the object goes
out of scope.
Answer: d
Explanation: None.
Answer: a
Explanation: None.
Answer: c
Explanation: In virtual memory, We can keep track of all the objects and access them much
faster than any another.
Answer: b
Explanation: Because by using pass by reference we need to pass only address location, So it can
save alot of memory.
Here is a listing of online C++ test questions on “Essential Operators” along with answers, explanations
and/or solutions:
Answer: d
Explanation: None.
Answer: b
Explanation: In assignment operation, the flow of execution will be from right to left only.
Answer: c
Explanation: When we want to modify the value of a variable by performing an operation on the value
currently stored, We will use compound assignment statement. In this option, a -=5 is equal to a = a-5.
#include <iostream>
int main ()
int a, b;
a = 10;
b = 4;
a = b;
b = 7;
cout << a;
cout << " b:";
cout << b;
return 0;
a) a:4 b:7
b) a:10 b:4
c) a:4 b:10
d) None of the mentioned
View Answer
Answer: a
Explanation: In this program, we are reassigning the values of a and b because of this we got the output
as a:4 b:7
Output:
$ g++ ess.cpp
$ a.out
a:4 b:7
#include <iostream>
int main ()
int a, b, c;
a = 2;
b = 7;
c = (a > b) ? a : b;
cout << c;
return 0;
a) 2
b) 7
c) 9
d) 14
View Answer
Answer: b
Explanation: We are using the ternary operator to evaluate this expression. It will return first option, if
first condition is true otherwise it will return second
Output:
$ g++ ess1.cpp
$ a.out
7
#include <iostream>
int main()
int a = 0;
int b = 10;
if ( a && b )
else
return 0;
a) true
b) false
c) error
d) none of the mentioned
View Answer
Answer: b
Explanation: && is called as Logical AND operator, if there is no zero in the operand means, it will be
true otherwise false.
Output:
$ g++ ess2.cpp
$ a.out
false
Answer: b
Explanation: None.
Answer: b
Explanation: | operator is used to find the ‘or’ of given values.
Answer: b
Explanation: None.
#include <iostream>
int main()
int a = 20;
int b = 10;
int c = 15;
int d = 5;
int e;
e = a + b * c / d;
return 0;
a) 50
b) 60
c) 70
d) 90
View Answer
Answer: a
Explanation: In this program, the value e is evaluated by precedence ad we got the output as 50.
Output:
$ g++ ess4.cpp
$ a.out
50
Here is a listing of C++ interview questions on “Subscripting” along with answers, explanations and/or
solutions:
2. How many arguments will the subscript operator will take for overloading?
a) 1
b) 2
c) 0
d) as many as possible
View Answer
Answer: a
Explanation: The subscript operator overload takes only one argument, but it can be of any type.
Answer: a
Explanation: None.
#include <iostream>
class safe
private:
int arr[SIZE];
public:
safe()
register int i;
{
arr[i] = i;
int &operator[](int i)
if (i > SIZE)
return arr[0];
return arr[i];
};
int main()
safe A;
return 0;
Answer: a
Explanation: In this program, We are returning the elements in the specified array location and if it is out
of bound means it will return the first element.
Output:
$ g++ sub.cpp
$ a.out
5Index out of bounds
0
#include <iostream>
class numbers
private:
int m_nValues[10];
public:
};
return m_nValues[nValue];
int main()
numbers N;
N[5] = 4;
return 0;
a) 5
b) 4
c) 3
d) 6
View Answer
Answer: b
Explanation: In this program, We are getting the values and returning it by overloading the subscript
operator.
Output:
$ g++ sub1.cpp
$ a.out
4
#include <iostream>
class safearray
private:
int arr[limit];
public:
if (n == limit - 1)
int temp;
temp = arr[n];
arr[n + 1] = temp;
return arr[n];
}
};
int main()
safearray sa1;
sa1[j] = j*10;
cout << "Element " << j << " is " << temp;
return 0;
a) 0102030
b) 1020300
c) 3020100
d) error
View Answer
Answer: a
Explanation: In this program, we are returning the array element by the multiple of 10.
Output:
$ g++ sub2.cpp
$ a.out
0102030
#include <iostream>
class A
public:
int x;
return x;
return x;
};
int z = a[2];
int main()
A a(7);
a[3] = 8;
int z = a[2];
foo(a);
return 0;
a) 110
b) 111
c) 011
d) 001
View Answer
Answer: d
Explanation: In this program, we overloading the operator[] by using subscript operator.
Output:
$ g++ sub3.cpp
$ a.out
001
#include <iostream>
class sample
private:
int* i;
int j;
public:
~sample ();
};
return i[n];
sample::sample (int j)
j = j;
sample::~sample ()
delete [] i;
int main ()
{
sample m (5);
m [0] = 25;
m [1] = 20;
m [2] = 15;
m [3] = 10;
m [4] = 5;
return 0;
a) 252015105
b) 510152025
c) 51015
d) None of the mentioned
View Answer
Answer: a
Explanation: In this program, we are printing the array in the reverse order by using subscript operator.
Output:
$ g++ sub4.cpp
$ a.out
252015105
Answer: b
Explanation: If you have a pointer to an object of some class type that overloads the subscript operator,
you have to dereference that pointer in order to free the memory.
Answer: a
Explanation: The reason is that operator[] always takes exactly one parameter, but operator() can take
any number of parameters.
This section on C++ quiz focuses on “Function Call”. One shall practice these quizzes to
improve their C++ programming skills needed for various interviews (campus interviews, walkin
interviews, company interviews), placements, entrance exams and other competitive exams.
These questions can be attempted by anyone focusing on learning C++ programming language.
They can be a beginner, fresher, engineering graduate or an experienced IT professional. Our
C++ quiz comes with detailed explanation of the answers which helps in better understanding of
C++ concepts.
Here is a listing of C++ quiz on “Function Call” along with answers, explanations and/or
solutions:
Answer: b
Explanation: None.
Answer: a
Explanation: None.
Answer: d
Explanation: It will modifies how the operator is to be interpreted when applied to objects of a
given type.
1. #include
2. using namespace std;
3. class Distance
4. {
5. private:
6. int feet;
7. int inches;
8. public:
9. Distance()
10. {
11. feet = 0;
12. inches = 0;
13. }
14. Distance(int f, int i)
15. {
16. feet = f;
17. inches = i;
18. }
19. Distance operator()(int a, int b, int c)
20. {
21. Distance D;
22. D.feet = a + c + 10;
23. D.inches = b + c + 100 ;
24. return D
25. }
26. void displayDistance()
27. {
28. cout << feet << inches << endl;
29. }
30. };
31. int main()
32. {
33. Distance D1(11, 10), D2;
34. cout << "First Distance : ";
35. D1.displayDistance();
36. D2 = D1(10, 10, 10);
37. cout << "Second Distance :";
38. D2.displayDistance();
39. return 0;
40. }
Answer: a
Explanation: We are calculating the foot and inches by using the function call operator.
Output:
$ g++ call.cpp
$ a.out
First Distance : 1110
Second Distance :30120
1. #include
2. using namespace std;
3. void duplicate (int& a, int& b, int& c)
4. {
5. a *= 2;
6. b *= 2;
7. c *= 2;
8. }
9. int main ()
10. {
11. int x = 1, y = 3, z = 7;
12. duplicate (x, y, z);
13. cout << x << y << z;
14. return 0;
15. }
a) 1468
b) 2812
c) 2614
d) none of the mentioned
View Answer
Answer: c
Explanation: We are passing the values by reference and modified the data on the function block.
Output:
$ g++ call1.cpp
$ a.out
2614
1. #include
2. using namespace std;
3. class three_d
4. {
5. int x, y, z;
6. public:
7. three_d() { x = y = z = 0; }
8. three_d(int i, int j, int k) { x = i; y = j; z = k; }
9. three_d operator()(three_d obj);
10. three_d operator()(int a, int b, int c);
11. friend ostream &operator<<(ostream &strm, three_d op);
12. };
13. three_d three_d::operator()(three_d obj)
14. {
15. three_d temp;
16. temp.x = (x + obj.x) / 2;
17. temp.y = (y + obj.y) / 2;
18. temp.z = (z + obj.z) / 2;
19. return temp;
20. }
21. three_d three_d::operator()(int a, int b, int c)
22. {
23. three_d temp;
24. temp.x = x + a;
25. temp.y = y + b;
26. temp.z = z + c;
27. return temp;
28. }
29. ostream &operator<<(ostream &strm, three_d op) {
30. strm << op.x << ", " << op.y << ", " << op.z << endl;
31. return strm;
32. }
33. int main()
34. {
35. three_d objA(1, 2, 3), objB(10, 10, 10), objC;
36. objC = objA(objB(100, 200, 300));
37. cout << objC;
38. return 0;
39. }
Answer: a
Explanation: In this program, We are using the function call operator to calculate the value of
objc.
Output:
$ g++ call2.cpp
$ a.out
55, 106, 156
a) c2=(9.7,8)
c2=(5.1,5.3)
b) c2=(9,8)
c2=(5,5)
c) c2=(4.7,8)
c2=(2.1,5.3)
d) none of the mentioned
View Answer
Answer: a
Explanation: In this program, We are returning the real and imaginary part of the complex
number by using function call operator.
Output:
$ g++ call3.cpp
$ a.out
c2=(9.7,8)
c2=(5.1,5.3)
Answer: b
Explanation: None.
1. #include
2. using namespace std;
3. int operate (int a, int b)
4. {
5. return (a * b);
6. }
7. float operate (float a, float b)
8. {
9. return (a / b);
10. }
11. int main ()
12. {
13. int x = 5, y = 2;
14. float n = 5.0, m = 2.0;
15. cout << operate (x, y);
16. cout << operate (n, m);
17. return 0;
18. }
a) 119
b) 102.5
c) 123.4
d) none of the mentioned
View Answer
Answer: b
Explanation: In this program, We are overloading the function and getting the output as 10 and
2.5 by division and multiplication.
Output:
$ g++ call3.cpp
$ a.out
102.5
Answer: a
Explanation: None.
This section on C question bank focuses on “Dereferencing”. One shall practice these questions
to improve their C++ programming skills needed for various interviews (campus interviews,
walkin interviews, company interviews), placements, entrance exams and other competitive
exams. These questions can be attempted by anyone focusing on learning C++ programming
language. They can be a beginner, fresher, engineering graduate or an experienced IT
professional. Our C question bank comes with detailed explanation of the answers which helps in
better understanding of C++ concepts.
Here is a listing of C question bank on “Dereferencing” along with answers, explanations and/or
solutions:
1. Which is used to tell the computer that where a pointer is pointing to?
a) dereference
b) reference
c) heap operations
d) none of the mentioned
View Answer
Answer: a
Explanation: None.
Answer: c
Explanation: Derefencing is using a pointer with asterix. For example, *(abc).
Answer: a
Explanation: None.
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int a, b;
6. int* c;
7. c = &a;
8. a = 200;
9. b = 200;
10. *c = 100;
11. b = *c;
12. cout << *c << " " << b;
13. return 0;
14. }
a) 100 200
b) 100 0
c) 200 200
d) 100 100
View Answer
Answer: d
Explanation: In this program, We are making the assignments and invoking the both b and c
values as 100 by dereference operator.
Output:
$ g++ def.cpp
$ a.out
100 100
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int x;
6. int *p;
7. x = 5;
8. p = &x;
9. cout << *p;
10. return 0;
11. }
a) 5
b) 10
c) memory address
d) none of the mentioned
View Answer
Answer: a
Explanation: In this program, we are copying the memory location of x into p and then printing
the value in the address.
Output:
$ g++ def1.cpp
$ a.out
5
1. #include <iostream>
2. using namespace std;
3. int main ()
4. {
5. int a;
6. int * ptr_b;
7. int ** ptr_c;
8. a = 1;
9. ptr_b = &a;
10. ptr_c = &ptr_b;
11. cout << a << "\n";
12. cout << *ptr_b << "\n";
13. cout << *ptr_c << "\n";
14. cout << **ptr_c << "\n";
15. return 0;
16. }
a) 1
1
0xbffc9924
1
b) 1
1
1
0xbffc9924
c) 1
0xbffc9924
1
1
d) none of the mentioned
View Answer
Answer: a
Explanation: In this program, We are printing the values and memory address
by using the pointer and derefernce operator.
Output:
$ g++ def2.cpp
$ a.out
1
1
0xbffc9924
1
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int x = 9;
6. int* p = &x;
7. cout << sizeof(p);
8. return 0;
9. }
a) 4
b) 2
c) Depends on compiler
d) None of the mentioned
View Answer
Answer: c
Explanation: The size of a datatype mainly depends on complier only.
Output:
$ g++ def3.cpp
$ a.out
4
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. double arr[] = {5.0, 6.0, 7.0, 8.0};
6. double *p = (arr+2);
7. cout << *p << endl;
8. cout << arr << endl;
9. cout << *(arr+3) << endl;
10. cout << *(arr) << endl;
11. cout << *arr+9 << endl;
12. return 0;
13. }
a) 7
0xbf99fc98
8
5
14
b) 7
8
0xbf99fc98
5
14
c) 0xbf99fc98
d) none of the mentioned
View Answer
Answer: a
Explanation: In this program, We are printing the values that are pointed by pointer and also the
dereference oerator.
Output:
$ g++ def5.cpp
$ a.out
7
0xbf99fc98
8
5
14
Answer: b
Explanation: It operates on a pointer variable, and returns an l-value equivalent to the value at
the pointer address.
Here is a listing of C++ programming questions on “Increment and Decrement” along with answers,
explanations and/or solutions:
Answer: c
Explanation: None.
Answer: b
Explanation: There are two types of increment/decrement. They are postfix and prefix.
#include <stdio.h>
int main()
int a = 21;
int c ;
c = a++;
cout << c;
return 0;
a) 21
b) 22
c) 23
d) 20
View Answer
Answer: a
Explanation: value of ‘a’ will be stored in c and then only it will be incremented.
Output:
$ g++ incre.cpp
$ a.out
21
#include <stdio.h>
int main()
int x = 5, y = 5;
return 0;
}
a) 55
b) 64
c) 46
d) 45
View Answer
Answer: b
Explanation: The values will be preincemented and predecremented, So it will print as 64.
Output:
$ g++ incre2.cpp
$ a.out
64
#include <stdio.h>
int main()
int x = 5, y = 5, z;
x = ++x; y = --y;
z = x++ + y--;
cout << z;
return 0;
a) 10
b) 11
c) 9
d) 12
View Answer
Answer: a
Explanation: In this program, the increment and decrement of evaluation of z will not be accounted
because they are post.
Output:
$ g++ incre3.cpp
$ a.out
10
#include <stdio.h>
int main()
int x = 5, y = 5, z;
x = ++x; y = --y;
z = x + ++x;
cout << z;
return 0;
a) 11
b) 12
c) 13
d) 14
View Answer
Answer: d
Explanation: In this program, we are adding the x value after preincrementing two times.
Output:
$ g++ incre4.cpp
$ a.out
14
#include <stdio.h>
int main()
int num1 = 5;
int num2 = 3;
int num3 = 2;
num1 = num2++;
num2 = --num3;
return 0;
a) 532
b) 235
c) 312
d) 311
View Answer
Answer: d
Explanation: In this program, We are preincrementing and postincrementing the operands and saving it.
Output:
$ g++ incre5.cpp
$ a.out
311
Answer: a
Explanation: Because preincrement take one byte instruction & post increment takes two byte
instruction.
Answer: b
Explanation: None.
Here is a listing of online C++ quiz on “String Class” along with answers, explanations and/or solutions:
Answer: b
Explanation: C++ provides following two types of string representations. They are C-style character
string and string class type with Standard C++.
a) #include<ios>
b) #include<str>
c) #include<string>
View Answer
Answer: c
Explanation: None.
Answer: c
Explanation: Both will return the number of characters that conform the string’s content.
4. What is the output of this program?
#include <iostream>
#include <cstring>
int main ()
char str3[10];
int len ;
len = strlen(str1);
return 0;
a) 5
b) 55
c) 11
d) 10
View Answer
Answer: d
Explanation: In the program, We are concatanating the str1 and str2 and printing
it’s total length. So the length is 10.
Output:
$ g++ stri.cpp
$ a.out
10
#include <iostream>
#include <string>
string::reverse_iterator r;
return 0;
a) microsoft
b) micro
c) tfosorcim
d) tfos
View Answer
Answer: c
Explanation: ‘rbegin’ is used to reverse the given the string.
Output:
$ g++ stri1.cpp
$ a.out
tfosorcim
#include <iostream>
#include <string>
int main ()
size_t f;
f = str.rfind(key);
if (f != string::npos)
Answer: d
Explanation: rfind is used to find the characters in the string and replace is used to replace with certain
characters.
Output:
$ g++ stri2.cpp
$ a.out
everbody does like this
#include <iostream>
#include <string>
int main ()
string::iterator it;
return 0;
a) jobs is
b) steve legend
c) steve
d) none of the mentioned
View Answer
Answer: b
Explanation: In this program, We are leaving the first 5 characters and last 7 characters and we are
erasing the remaining the characters.
Output:
$ g++ stri3.cpp
$ a.out
steve legend
#include <iostream>
#include <string>
int main ()
return 0;
a) M
b) Microsoft
c) Micro
d) runtime error
View Answer
Answer: d
Explanation: This program will terminate because the cout element is out of range.
#include <iostream>
#include <string>
int main ()
return 0;
a) 61073741820
b) 51073741820
c) 6 and max size depends on compiler
d) none of the mentioned
View Answer
Answer: c
Explanation: In this program, We are printing the capacity and max size of the string.
Output:
$ g++ stri5.cpp
$ a.out
61073741820
10. Which method do we use to append more than one character at a time?
a) append
b) operator+=
c) data
d) both append & operator+=
View Answer
Answer: d
Explanation: None.
This section on C++ programming questions and answers focuses on “Derived Classes”. One
shall practice these questions to improve their C++ programming skills needed for various
interviews (campus interviews, walkin interviews, company interviews), placements, entrance
exams and other competitive exams. These questions can be attempted by anyone focusing on
learning C++ programming language. They can be a beginner, fresher, engineering graduate or
an experienced IT professional. Our C++ programming questions come with detailed explanation
of the answers which helps in better understanding of C++ concepts.
Here is a listing of C++ programming questions on “Derived Classes” along with answers,
explanations and/or solutions:
Answer: b
Explanation: Because derived inherits functions and variables from base.
Answer: b
Explanation: Destructors are automatically invoked when a object goes out of scope or when a
dynamically allocated object is deleted. Inheritance does not change this behavior. This is the
reason a derived destructor cannot invoke its base class destructor.
Answer: c
Explanation: None.
1. #include <iostream>
2. using namespace std;
3. class A
4. {
5. public:
6. A(int n )
7. {
8. cout << n;
9. }
10. };
11. class B: public A
12. {
13. public:
14. B(int n, double d)
15. : A(n)
16. {
17. cout << d;
18. }
19. };
20. class C: public B
21. {
22. public:
23. C(int n, double d, char ch)
24. : B(n, d)
25. {
26. cout <<ch;
27. }
28. };
29. int main()
30. {
31. C c(5, 4.3, 'R');
32. return 0;
33. }
a) 54.3R
b) R4.35
c) 4.3R5
d) None of the mentioned
View Answer
Answer: a
Explanation: In this program, We are passing the value and manipulating by using the derived
class.
Output:
$ g++ der.cpp
$ a.out
54.3R
1. #include <iostream>
2. using namespace std;
3. class BaseClass
4. {
5. protected:
6. int i;
7. public:
8. BaseClass(int x)
9. {
10. i = x;
11. }
12. ~BaseClass()
13. {
14. }
15. };
16. class DerivedClass: public BaseClass
17. {
18. int j;
19. public:
20. DerivedClass(int x, int y): BaseClass(y)
21. {
22. j = x;
23. }
24. ~DerivedClass()
25. {
26. }
27. void show()
28. {
29. cout << i << " " << j << endl;
30. }
31. };
32. int main()
33. {
34. DerivedClass ob(3, 4);
35. ob.show();
36. return 0;
37. }
a) 3 4
b) 4 3
c) 4
d) 3
View Answer
Answer: b
Explanation: In this program, We are passing the values and assigning it to i and j and we are
printing it.
Output:
$ g++ der1.cpp
$ a.out
43
1. #include <iostream>
2. using namespace std;
3. class Base
4. {
5. public:
6. int m;
7. Base(int n=0)
8. : m(n)
9. {
10. cout << "Base" << endl;
11. }
12. };
13. class Derived: public Base
14. {
15. public:
16. double d;
17. Derived(double de = 0.0)
18. : d(de)
19. {
20. cout << "Derived" << endl;
21. }
22. };
23. int main()
24. {
25. cout << "Instantiating Base" << endl;
26. Base cBase;
27. cout << "Instantiating Derived" << endl;
28. Derived cDerived;
29. return 0;
30. }
a) Instantiating Base
Base
Instantiating Derived
Base
Derived
b) Instantiating Base
Instantiating Derived
Base
Derived
c) Instantiating Base
Base
Instantiating Derived
Base
d) None of the mentioned
View Answer
Answer: a
Explanation: In this program, We are printing the execution order of the program.
Output:
$ g++ der2.cpp
$ a.out
Instantiating Base
Base
Instantiating Derived
Base
Derived
1. #include <iostream>
2. using namespace std;
3. class Parent
4. {
5. public:
6. Parent (void)
7. {
8. cout << "Parent()\n";
9. }
10. Parent (int i)
11. {
12. cout << "Parent("<< i << ")\n";
13. };
14. Parent (void)
15. {
16. cout << "~Parent()\n";
17. };
18. };
19. class Child1 : public Parent { };
20. class Child2 : public Parent
21. {
22. public:
23. Child2 (void)
24. {
25. cout << "Child2()\n";
26. }
27. Child2 (int i) : Parent (i)
28. {
29. cout << "Child2(" << i << ")\n";
30. }
31. ~Child2 (void)
32. {
33. cout << "~Child2()\n";
34. }
35. };
36. int main (void)
37. {
38. Child1 a;
39. Child2 b;
40. Child2 c(42);
41. return 0;
42. }
a) Parent()
Parent()
Child2()
Parent(42)
Child2(42)
~Child2()
~Parent()
~Child2()
~Parent()
~Parent()
b) error
c) runtime error
d) none of the mentioned
View Answer
Answer: b
Explanation: In this program, We got an error in overloading because we didn’t invoke the
destructor of parent.
1. #include<iostream>
2. using namespace std;
3. class X
4. {
5. int m;
6. public:
7. X() : m(10)
8. {
9. }
10. X(int mm): m(mm)
11. {
12. }
13. int getm()
14. {
15. return m;
16. }
17. };
18. class Y : public X
19. {
20. int n;
21. public:
22. Y(int nn) : n(nn) {}
23. int getn() { return n; }
24. };
25. int main()
26. {
27. Y yobj( 100 );
28. cout << yobj.getm() << " " << yobj.getn() << endl;
29. }
a) 10 100
b) 100 10
c) 10 10
d) 100 100
View Answer
Answer: a
Explanation: In this program, We are passing the value and getting the result by derived class.
Output:
$ g++ der5.cpp
$ a.out
10 100
9. Which operator is used to declare the destructor?
a) #
b) ~
c) @
d) $
View Answer
Answer: b
Explanation: None.
10. Which constructor will initialize the base class data member?
a) derived class
b) base class
c) class
d) none of the mentioned
View Answer
Answer: b
Explanation: Because it is having the proper data set to initialize, Otherwise it will throw a error.
This section on C++ interview questions and answers focuses on “Abstract Classes”. One shall
practice these interview questions to improve their C++ programming skills needed for various
interviews (campus interviews, walkin interviews, company interviews), placements, entrance
exams and other competitive exams. These questions can be attempted by anyone focusing on
learning C++ programming language. They can be a beginner, fresher, engineering graduate or
an experienced IT professional. Our C++ interview questions come with detailed explanation of
the answers which helps in better understanding of C++ concepts.
Here is a listing of C++ interview questions on “Abstract Classes” along with answers,
explanations and/or solutions:
Answer: a
Explanation: None.
2. Which is used to create a pure virtual function ?
a) $
b) =0
c) &
d) !
View Answer
Answer: b
Explanation: For making a method as pure virtual function, We have to append ‘=0’ to the class
or method.
Answer: b
Explanation: Classes that contain at least one pure virtual function are called as abstract base
classes.
1. #include <iostream>
2. using namespace std;
3. class p
4. {
5. protected:
6. int width, height;
7. public:
8. void set_values (int a, int b)
9. {
10. width = a; height = b;
11. }
12. virtual int area (void) = 0;
13. };
14. class r: public p
15. {
16. public:
17. int area (void)
18. {
19. return (width * height);
20. }
21. };
22. class t: public p
23. {
24. public:
25. int area (void)
26. {
27. return (width * height / 2);
28. }
29. };
30. int main ()
31. {
32. r rect;
33. t trgl;
34. p * ppoly1 = ▭
35. p * ppoly2 = &trgl;
36. ppoly1->set_values (4, 5);
37. ppoly2->set_values (4, 5);
38. cout << ppoly1 -> area() ;
39. cout << ppoly2 -> area();
40. return 0;
41. }
a) 1020
b) 20
c) 10
d) 2010
View Answer
Answer: d
Explanation: In this program, We are calculating the area of rectangle and
triangle by using abstract class.
Output:
$ g++ abs.cpp
$ a.out
2010
1. #include <iostream>
2. using namespace std;
3. class MyInterface
4. {
5. public:
6. virtual void Display() = 0;
7. };
8. class Class1 : public MyInterface
9. {
10. public:
11. void Display()
12. {
13. int a = 5;
14. cout << a;
15. }
16. };
17. class Class2 : public MyInterface
18. {
19. public:
20. void Display()
21. {
22. cout <<" 5" << endl;
23. }
24. };
25. int main()
26. {
27. Class1 obj1;
28. obj1.Display();
29. Class2 obj2;
30. obj2.Display();
31. return 0;
32. }
a) 5
b) 10
c) 5 5
d) None of the mentioned
View Answer
Answer: c
Explanation: In this program, We are displaying the data from the two classes
by using abstract class.
Output:
$ g++ abs1.cpp
$ a.out
55
1. #include <iostream>
2. using namespace std;
3. class sample
4. {
5. public:
6. virtual void example() = 0;
7. };
8. class Ex1:public sample
9. {
10. public:
11. void example()
12. {
13. cout << "ubuntu";
14. }
15. };
16. class Ex2:public sample
17. {
18. public:
19. void example()
20. {
21. cout << " is awesome";
22. }
23. };
24. int main()
25. {
26. sample* arra[2];
27. Ex1 e1;
28. Ex2 e2;
29. arra[0]=&e1;
30. arra[1]=&e2;
31. arra[0]->example();
32. arra[1]->example();
33. }
a) ubuntu
b) is awesome
c) ubuntu is awesome
d) none of the mentioned
View Answer
Answer: c
Explanation: In this program, We are combining the two statements from two classes and
printing it by using abstract class.
Output:
$ g++ abs3.cpp
$ a.out
ubuntu is awesome
1. #include <iostream>
2. using namespace std;
3. class Base
4. {
5. public:
6. virtual void print() const = 0;
7. };
8. class DerivedOne : virtual public Base
9. {
10. public:
11. void print() const
12. {
13. cout << "1";
14. }
15. };
16. class DerivedTwo : virtual public Base
17. {
18. public:
19. void print() const
20. {
21. cout << "2";
22. }
23. };
24. class Multiple : public DerivedOne, DerivedTwo
25. {
26. public:
27. void print() const
28. {
29. DerivedTwo::print();
30. }
31. };
32. int main()
33. {
34. Multiple both;
35. DerivedOne one;
36. DerivedTwo two;
37. Base *array[ 3 ];
38. array[ 0 ] = &both;
39. array[ 1 ] = &one;
40. array[ 2 ] = &two;
41. for ( int i = 0; i < 3; i++ )
42. array[ i ] -> print();
43. return 0;
44. }
a) 121
b) 212
c) 12
d) none of the mentioned
View Answer
Answer: b
Explanation: In this program, We are executing these based on the condition given in array. So it
is printing as 212.
Output:
$ g++ abs4.cpp
$ a.out
212
Answer: a
Explanation: As the name itself implies, it have to depend on other class only.
Answer: a
Explanation: None.
10. Where does the abstract class is used?
a) base class only
b) derived class
c) both derived & base class
d) none of the mentioned
View Answer
Answer: a
Explanation: None.
This section on online C++ quiz focuses on “Design of Class Hierarchies”. One shall practice
these online quizzes to improve their C++ programming skills needed for various interviews
(campus interviews, walkin interviews, company interviews), placements, entrance exams and
other competitive exams. These questions can be attempted by anyone focusing on learning C++
programming language. They can be a beginner, fresher, engineering graduate or an experienced
IT professional. Our C++ quiz comes with detailed explanation of the answers which helps in
better understanding of C++ concepts.
Here is a listing of online C++ quiz on “Design of Class Hierarchies” along with answers,
explanations and/or solutions:
1. Which interface determines how your class will be used by other program?
a) public
b) private
c) protected
d) none of the mentioned
View Answer
Answer: a
Explanation: If we invoked the interface as public means, We can access the program from other
programs also.
Answer: a
Explanation: None.
3. How many ways of reusing are there in class hierarchy?
a) 1
b) 2
c) 3
d) 4
View Answer
Answer: b
Explanation: Class hierarchies promote reuse in two ways. They are code sharing and interface
sharing.
Answer: c
Explanation: There are three types of classes. They are abstract base classes, concrete derived
classes, standalone classes.
1. #include <iostream>
2. using namespace std;
3. class BaseClass
4. {
5. int i;
6. public:
7. void setInt(int n);
8. int getInt();
9. };
10. class DerivedClass : public BaseClass
11. {
12. int j;
13. public:
14. void setJ(int n);
15. int mul();
16. };
17. void BaseClass::setInt(int n)
18. {
19. i = n;
20. }
21. int BaseClass::getInt()
22. {
23. return i;
24. }
25. void DerivedClass::setJ(int n)
26. {
27. j = n;
28. }
29. int DerivedClass::mul()
30. {
31. return j * getInt();
32. }
33. int main()
34. {
35. DerivedClass ob;
36. ob.setInt(10);
37. ob.setJ(4);
38. cout << ob.mul();
39. return 0;
40. }
a) 10
b) 4
c) 40
d) None of the mentioned
View Answer
Answer: c
Explanation: In this program, We are multiplying the value 10 and 4 by using inheritance.
Output:
$ g++ des.cpp
$ a.out
40
Answer: b
Explanation: In multiple inheritance, We are able to derive a class from more than one base
class.
1. #include <iostream>
2. using namespace std;
3. class BaseClass
4. {
5. int x;
6. public:
7. void setx(int n)
8. {
9. x = n;
10. }
11. void showx()
12. {
13. cout << x ;
14. }
15. };
16. class DerivedClass : private BaseClass
17. {
18. int y;
19. public:
20. void setxy(int n, int m)
21. {
22. setx(n);
23. y = m;
24. }
25. void showxy()
26. {
27. showx();
28. cout << y << '\n';
29. }
30. };
31. int main()
32. {
33. DerivedClass ob;
34. ob.setxy(10, 20);
35. ob.showxy();
36. return 0;
37. }
a) 10
b) 20
c) 1020
d) None of the mentioned
View Answer
Answer: c
Explanation: In this program, We are passing the values from the main class and printing it on
the inherited classes.
Output:
$ g++ des2.cpp
$ a.out
1020
1. #include <iostream>
2. using namespace std;
3. class BaseClass
4. {
5. public:
6. virtual void myFunction()
7. {
8. cout << "1";
9. }
10. };
11. class DerivedClass1 : public BaseClass
12. {
13. public:
14. void myFunction()
15. {
16. cout << "2";
17. }
18. };
19. class DerivedClass2 : public DerivedClass1
20. {
21. public:
22. void myFunction()
23. {
24. cout << "3";
25. }
26. };
27. int main()
28. {
29. BaseClass *p;
30. BaseClass ob;
31. DerivedClass1 derivedObject1;
32. DerivedClass2 derivedObject2;
33. p = &ob;
34. p -> myFunction();
35. p = &derivedObject1;
36. p -> myFunction();
37. p = &derivedObject2;
38. p -> myFunction();
39. return 0;
40. }
a) 123
b) 12
c) 213
d) 321
View Answer
Answer: a
Explanation: We are passing the objects and executing them in a certain order and we are
printing the program flow.
Output:
$ g++ des3.cpp
$ a.out
123
Answer: c
Explanation: None.
This section on C++ programming questions and answers focuses on “Class Hierarchies and
Abstract Classes”. One shall practice these questions to improve their C++ programming skills
needed for various interviews (campus interviews, walkin interviews, company interviews),
placements, entrance exams and other competitive exams. These questions can be attempted by
anyone focusing on learning C++ programming language. They can be a beginner, fresher,
engineering graduate or an experienced IT professional. Our C++ programming questions come
with detailed explanation of the answers which helps in better understanding of C++ concepts.
Here is a listing of C++ programming questions on “Class Hierarchies and Abstract Classes”
along with answers, explanations and/or solutions:
Answer: b
Explanation: There are two kinds of classes in c++. They are absolute class and concrete class.
Answer: d
Explanation: There are five types of inheritance in c++. They are single, Multiple, Hierarchical,
Multilevel, Hybrid.
1. #include <iostream>
2. using namespace std;
3. class stu
4. {
5. protected:
6. int rno;
7. public:
8. void get_no(int a)
9. {
10. rno = a;
11. }
12. void put_no(void)
13. {
14. }
15. };
16. class test:public stu
17. {
18. protected:
19. float part1,part2;
20. public:
21. void get_mark(float x, float y)
22. {
23. part1 = x;
24. part2 = y;
25. }
26. void put_marks()
27. {
28. }
29. };
30. class sports
31. {
32. protected:
33. float score;
34. public:
35. void getscore(float s)
36. {
37. score = s;
38. }
39. void putscore(void)
40. {
41. }
42. };
43. class result: public test, public sports
44. {
45. float total;
46. public:
47. void display(void);
48. };
49. void result::display(void)
50. {
51. total = part1 + part2 + score;
52. put_no();
53. put_marks();
54. putscore();
55. cout << "Total Score=" << total << "\n";
56. }
57. int main()
58. {
59. result stu;
60. stu.get_no(123);
61. stu.get_mark(27.5, 33.0);
62. stu.getscore(6.0);
63. stu.display();
64. return 0;
65. }
a) 66.5
b) 64.5
c) 62.5
d) 60.5
View Answer
Answer: a
Explanation: In this program, We are passing the values by using different
methods and totaling the marks to get the result.
Output:
$ g++ class.cpp
$ a.out
Total Score=66.5
1. #include <iostream>
2. using namespace std;
3. class poly
4. {
5. protected:
6. int width, height;
7. public:
8. void set_values(int a, int b)
9. {
10. width = a; height = b;
11. }
12. };
13. class Coutput
14. {
15. public:
16. void output(int i);
17. };
18. void Coutput::output(int i)
19. {
20. cout << i;
21. }
22. class rect:public poly, public Coutput
23. {
24. public:
25. int area()
26. {
27. return(width * height);
28. }
29. };
30. class tri:public poly, public Coutput
31. {
32. public:
33. int area()
34. {
35. return(width * height / 2);
36. }
37. };
38. int main()
39. {
40. rect rect;
41. tri trgl;
42. rect.set_values(3, 4);
43. trgl.set_values(4, 5);
44. rect.output(rect.area());
45. trgl.output(trgl.area());
46. return 0;
47. }
a) 1212
b) 1210
c) 1010
d) none of the mentioned
View Answer
Answer: b
Explanation: In this program, We are calculating the area of rectangle and
triangle by using multilevel inheritance.
$ g++ class1.cpp
$ a.out
1210
6. What is meant by containership?
a) class contains objects of other class types as its members
b) class contains objects of other class types as its objects
c) class contains objects of other class types as its members 7 also objects
d) none of the mentioned
View Answer
Answer: a
Explanation: None.
Answer: c
Explanation: There are three types of constructor in C++. They are Default constructor,
Parameterized constructor, Copy constructor.
Answer: d
Explanation: There can be multiple constructors of the same class, provided they have different
signatures.
Answer: c
Explanation: None.
10. What does derived class does not inherit from the base class?
a) constructor and destructor
b) friends
c) operator = () members
d) all of the mentioned
View Answer
Answer: d
Explanation: The derived class inherit everything from the base class except the given things.
This section on C++ interview questions and answers focuses on “Simple String Template”. One
shall practice these interview questions to improve their C++ programming skills needed for
various interviews (campus interviews, walkin interviews, company interviews), placements,
entrance exams and other competitive exams. These questions can be attempted by anyone
focusing on learning C++ programming language. They can be a beginner, fresher, engineering
graduate or an experienced IT professional. Our C++ interview questions come with detailed
explanation of the answers which helps in better understanding of C++ concepts.
Here is a listing of C++ interview questions on “Simple String Template” along with answers,
explanations and/or solutions:
1. What is a template?
a) A template is a formula for creating a generic class
b) A template is used to manipulate the class
c) A template is used for creating the attributes
d) None of the mentioned
View Answer
Answer: a
Explanation: None.
Answer: b
Explanation: Every string template is used to replace the string with another string at runtime.
Answer: c
Explanation: None.
1. #include <iostream>
2. using namespace std;
3. template <class T>
4. inline T square(T x)
5. {
6. T result;
7. result = x * x;
8. return result;
9. };
10. template <>
11. string square<string>(string ss)
12. {
13. return (ss+ss);
14. };
15. int main()
16. {
17. int i = 4, ii;
18. string ww("A");
19. ii = square<int>(i);
20. cout << i << ii;
21. cout << square<string>(ww) << endl;
22. }
a) 416AA
b) 164AA
c) AA416
d) none of the mentioned
View Answer
Answer: a
Explanation: In this program, We are using two template to calculate the square and to find the
addition.
Output:
$ g++ tem.cpp
$ a.out
416AA
1. #include <iostream>
2. using namespace std;
3. template <typename T, typename U>
4. void squareAndPrint(T x, U y)
5. {
6. cout << x << x * x << endl;
7. cout << y << " " << y * y << endl;
8. };
9. int main()
10. {
11. int ii = 2;
12. float jj = 2.1;
13. squareAndPrint<int, float>(ii, jj);
14. }
a) 23
2.1 4.41
b) 24
2.1 4.41
c) 24
2.1 3.41
d) none of the mentioned
View Answer
Answer: b
Explanation: In this multiple templated types, We are passing two values of different types and
producing the result.
Output:
$ g++ tem1.cpp
$ a.out
24
2.1 4.41
1. #include <iostream>
2. #include <string>
3. using namespace std;
4. template<typename T>
5. void print_mydata(T output)
6. {
7. cout << output << endl;
8. }
9. int main()
10. {
11. double d = 5.5;
12. string s("Hello World");
13. print_mydata( d );
14. print_mydata( s );
15. return 0;
16. }
a) 5.5
Hello World
b) 5.5
c) Hello World
d) None of the mentioned
View Answer
Answer: a
Explanation: In this program, We are passing the value to the template and printing it in the
template.
Output:
$ g++ tem2.cpp
$ a.out
5.5
Hello World
Answer: b
Explanation: There are two types of templates. They are function template and class template.
Answer: a
Explanation: The compiler can determine at compile time whether the type associated with a
template definition can perform all of the functions required by that template definition.
9. What may be the name of the parameter that the template should take?
a) same as template
b) same as class
c) same as function
d) none of the mentioned
View Answer
Answer: a
Explanation: None.
Answer: d
Explanation: The following are legal for non-type template parameters: integral or enumeration
type, Pointer to object or pointer to function, Reference to object or reference to function, Pointer
to member.
This section on C++ programming interview questions and answers focuses on “Function
Templates”. One shall practice these interview questions to improve their C++ programming
skills needed for various interviews (campus interviews, walkin interviews, company
interviews), placements, entrance exams and other competitive exams. These questions can be
attempted by anyone focusing on learning C++ programming language. They can be a beginner,
fresher, engineering graduate or an experienced IT professional. Our C++ programming
interview questions come with detailed explanation of the answers which helps in better
understanding of C++ concepts.
Here is a listing of C++ programming interview questions on “Function Templates” along with
answers, explanations and/or solutions:
Answer: a
Explanation: None.
Answer: a
Explanation: Because of template type parameters, It will work with many types and saves a lot
of time.
1. #include <iostream>
2. using namespace std;
3. template<typename type>
4. type Max(type Var1, type Var2)
5. {
6. return Var1 > Var2 ? Var1:Var2;
7. }
8. int main()
9. {
10. int p;
11. p = Max(100, 200);
12. cout << p << endl;
13. return 0;
14. }
a) 100
b) 200
c) 300
d) 100200
View Answer
Answer: b
Explanation: In this program, We are returning the maximum value by using function template.
Output:
$ g++ ftemp.cpp
$ a.out
200
1. #include <iostream>
2. using namespace std;
3. template<typename type>
4. class Test
5. {
6. public:
7. Test()
8. {
9. };
10. ~Test()
11. {
12. };
13. type Funct1(type Var1)
14. {
15. return Var1;
16. }
17. type Funct2(type Var2)
18. {
19. return Var2;
20. }
21. };
22. int main()
23. {
24. Test<int> Var1;
25. Test<float> Var2;
26. cout << Var1.Funct1(200) << endl;
27. cout << Var2.Funct2(3.123) << endl;
28. return 0;
29. }
a) 200
3.123
b) 3.123
200
c) 200
d) 3.123
View Answer
Answer: a
Explanation: In this program, We are passing the values and getting it back from template. And
we are using the constructor and destructor for the function template.
Output:
$ g++ ftemp1.cpp
$ a.out
200
3.123
1. #include <iostream>
2. using namespace std;
3. template<typename type>
4. class TestVirt
5. {
6. public:
7. virtual type TestFunct(type Var1)
8. {
9. return Var1 * 2;
10. }
11. };
12. int main()
13. {
14. TestVirt<int> Var1;
15. cout << Var1.TestFunct(100) << endl;
16. return 0;
17. }
a) 100
b) 200
c) 50
d) none of the mentioned
View Answer
Answer: b
Explanation: In this program, We are using class to pass the value and then we are manipulating
it.
Output:
$ g++ ftemp3.cpp
$ a.out
200
1. #include <iostream>
2. using namespace std;
3. template<typename T>
4. inline T square(T x)
5. {
6. T result;
7. result = x * x;
8. return result;
9. };
10. int main()
11. {
12. int i, ii;
13. float x, xx;
14. double y, yy;
15. i = 2;
16. x = 2.2;
17. y = 2.2;
18. ii = square(i);
19. cout << i << " " << ii << endl;
20. yy = square(y);
21. cout << y << " " << yy << endl;
22. }
a) 2 4
2.2 4.84
b) 2 4
c) error
d) runtime error
View Answer
Answer: a
Explanation: In this program, We are passing the values and calculating the square of the value
by using the function template.
Output:
$ g++ ftemp4.cpp
$ a.out
24
2.2 4.84
1. #include <iostream>
2. using namespace std;
3. template<typename T>
4. void loopIt(T x)
5. {
6. int count = 3;
7. T val[count];
8. for (int ii=0; ii < count; ii++)
9. {
10. val[ii] = x++;
11. cout << val[ii] << endl;
12. }
13. };
14. int main()
15. {
16. float xx = 2.1;
17. loopIt(xx);
18. }
a) 2.1
b) 3.1
c) 3.2
d) 2.1
3.1
4.1
View Answer
Answer: d
Explanation: In this program, We are using the for loop to increment the value by 1 in the
function template.
Output:
$ g++ ftemp5.cpp
$ a.out
2.1
3.1
4.1
Answer: c
Explanation: Non-type template parameters provide the ability to pass a constant expression at
compile time. The constant expression may also be an address of a function, object or static class
member.
Answer: c
Explanation: None.
Here is a listing of C multiple choice questions on “Template Arguments to Specify Policy Usage” along
with answers, explanations and/or solutions:
Answer: a
Explanation: A template parameter is a special kind of parameter that can be used to pass a type as
argument.
Answer: c
Explanation: None.
Answer: a
Explanation: None.
#include <iostream>
class mysequence
T memblock [N];
public:
};
template <class T, int N>
memblock[x] = value;
return memblock[x];
int main ()
return 0;
a) 100
b) 3.1416
c) 100
3.1416
d) none of the mentioned
View Answer
Answer: c
Explanation: In this program, We are printing the integer in the first function and float in the second
function.
Output:
$ g++ farg.cpp
$ a.out
100
3.1416
#include <iostream>
return (a>b?a:b);
int main ()
int i = 5, j = 6, k;
long l = 10, m = 5, n;
k = max(i, j);
n = max(l, m);
return 0;
a) 6
b) 6
10
c) 5
10
d) 6
5
View Answer
Answer: b
Explanation: In this program, We are using the ternary operator on the template function.
Output:
$ g++ farg.cpp
$ a.out
6
10
#include <iostream>
class Test
public:
Test()
};
~Test()
};
return Var1;
return Var2;
};
int main()
Test<int> Var1;
Test<double> Var2;
return 0;
a) 100
b) 200
c) 3.123
d) 2003.123
View Answer
Answer: d
Explanation: In this program, We are passing the value and returning it from template.
Output:
$ g++ farg3.cpp
$ a.out
2003.123
#include <iostream>
void loopIt(T x)
T val[count];
val[ii] = x++;
};
int main()
float xx = 2.1;
loopIt<float, 3>(xx);
}
a) 2.1
b) 3.1
c) 4.1
d) 2.1
3.1
4.1
View Answer
Answer: d
Explanation: In this program, We are using the non-type template parameter to increment the value in
the function template.
Output:
$ g++ farg4.cpp
$ a.out
2.1
3.1
4.1
Answer: c
Explanation: It is used to adapt a policy into binary ones.
Answer: a
Explanation: The following are legal for non-type template parameters:integral or enumeration type,
Pointer to object or pointer to function, Reference to object or reference to function, Pointer to
member.
Answer: d
Explanation: The compiler does not generate definitions for functions, non virtual member functions,
class or member class because it does not require instantiation.
Here is a listing of C++ interview questions on “Specialization ” along with answers, explanations and/or
solutions:
Answer: a
Explanation: In the template specialization, it will make the template to be specific for some data types.
Answer: c
Explanation: None
Answer: b
Explanation: When you allocate memory for an array of objects, the default constructor must be called
to construct each object. If no default constructor exists, you’re stuck needing a list of pointers to
objects.
#include <iostream>
inline T square(T x)
T result;
result = x * x;
return result;
};
template <>
return (ss+ss);
};
int main()
int i = 2, ii;
string ww("A");
ii = square<int>(i);
}
a) 2:4AA
b) 2:4
c) AA
d) 2:4A
View Answer
Answer: a
Explanation: Template specialization is used when a different and specific implementation is to be used
for a specific data type. In this program, We are using integer and character.
Output:
$ g++ spec.cpp
$ a.out
2:4AA
#include <iostream>
T multIt(T x)
x = x * x;
return x;
};
int main()
float xx = 2.1;
a) 2.1
b) 378.228
c) 2.1: 378.228
d) None of the mentioned
View Answer
Answer: c
Explanation: In this program, We specifed the type in the template function. We need to compile this
program by adding -std=c++0x.
Output:
$ g++ -std=c++0x spec1.cpp
$ a.out
2.1: 378.228
#include <iostream>
class XYZ
public:
void putPri();
static T ipub;
private:
static T ipri;
};
void XYZ<T>::putPri()
int main()
XYZ<int> a;
XYZ<float> b;
a.putPri();
b.putPri();
a) 1
b) 1.2
c) 1
1.2
d) 1
1
1.2
View Answer
Answer: d
Explanation: In this program, We are passing the value of specified type and printing it by specialization.
Output:
$ g++ spec2.cpp
$ a.out
1
1
1.2
#include <iostream>
#include <string>
#include <cstring>
template <>
const char *MyMax(const char *Var1, const char *Var2)
int main()
return 0;
a) template
b) class
c) no specialization
d) none of the mentioned
View Answer
Answer: a
Explanation: In this program, We are computing the result in the specalized block of the program.
Output:
$ g++ spec3.cpp
$ a.out
template
#include <iostream>
public:
A();
int value;
};
public: A();
};
public: A();
};
A<>::A()
A<double, 10>::A()
int main()
A<int, 6> x;
A<> y;
A<double, 10> z;
a) 6
b) 10
c) 6default10
d) None of the mentioned
View Answer
Answer: c
Explanation: In this program, We are defining three templates and specializing it and passing the values
to it and printing it.
Output:
$ g++ spec5.cpp
$ a.out
6default10
Answer: b
Explanation: There are two types specialization. They are full specialization and partial specialization.
Answer: a
Explanation: None
Here is a listing of advanced C++ interview questions on “Derivation and Templates” along with answers,
explanations and/or solutions:
1. Which is dependant on template parameter?
a) base class
b) abstract class
c) method
d) none of the mentioned
View Answer
Answer: a
Explanation: None
Answer: b
Explanation: We can place the default type values in a base class and overriding some of them through
derivation.
Answer: d
Explanation: classes that contain only type members, nonvirtual function members, and static data
members do not require memory at run time.
#include <iostream>
class class0
public:
virtual ~class0(){}
protected:
char p;
public:
char getChar();
};
public:
void printChar();
};
void class1::printChar()
int main()
class1 c;
c.printChar();
return 1;
a) True
b) error
c) no output
d) runtime error
View Answer
Answer: a
Explanation: In this program, We are passing the values and inheriting it to the other class and printing
the result.
$ g++ dert.cpp
$ a.out
True
#include <iostream>
public:
T value;
clsTemplate(T i)
this->value = i;
void test()
};
public:
clsChild(): clsTemplate<char>( 0 )
void test2()
test();
};
int main()
{
clsTemplate <int> a( 42 );
clsChild b( 'A' );
a.test();
b.test();
return 0;
a) 42
b) A
c) 42
A
d) A
42
View Answer
Answer: c
Explanation: In this program, We are passing the values by using the template inheritance and printing
it.
Output:
$ g++ dert.cpp
$ a.out
42
A
#include <iostream>
class A
public:
protected:
int x;
};
public:
B(): A<char>::A(100)
};
int main()
B<char> test;
return 0;
a) 100
b) 200
c) error
d) runtime error
View Answer
Answer: b
Explanation: In this program, We are passing the values and manipulating it by using the template
inheritance.
Output:
$ g++ dert2.cpp
$ a.out
200
#include <iostream>
class Test
public:
Test();
~Test();
type Data(type);
};
return Var0;
Test<type>::Test()
Test<type>::~Test()
int main(void)
Test<char> Var3;
return 0;
a) k
b) l
c) error
d) runtime error
View Answer
Answer: a
Explanation: In this program, We are passing the values and printing it by using template inheritance.
Output:
$ g++ dert3.cpp
$ a.out
k
#include <iostream>
class Base
public:
Base ( )
~Base ( )
};
public:
Derived ( )
~Derived ( )
};
int main( )
Derived x;
a) 1234
b) 4321
c) 1423
d) 1342
View Answer
Answer: d
Explanation: In this program, We are printing the order of execution of constructor and destructor in the
class.
Output:
$ g++ dert4.cpp
$ a.out
1342
Answer: c
Explanation: C++ allows us to parameterize directly three kinds of entities through templates: types,
constants, and templates.
Answer: c
Explanation: There are three kinds of parameters are there in C++. They are type, non-type, template.
Here is a listing of C++ programming questions on “Error Handling” along with answers,
explanations and/or solutions:
Answer: c
Explanation: When we found a exception in the program, We need to throw that and we handle
that by using the catch keyword.
Answer: a
Explanation: None.
Answer: b
Explanation: finally keyword will be executed at the end of all the exception.
1. #include <iostream>
2. using namespace std;
3. double division(int a, int b)
4. {
5. if (b == 0)
6. {
7. throw "Division by zero condition!";
8. }
9. return (a / b);
10. }
11. int main ()
12. {
13. int x = 50;
14. int y = 0;
15. double z = 0;
16. try
17. {
18. z = division(x, y);
19. cout << z << endl;
20. }
21. catch (const char* msg)
22. {
23. cerr << msg << endl;
24. }
25. return 0;
26. }
a) 50
b) 0
c) Division by zero condition!
d) Error
View Answer
Answer: c
Explanation: It’s a mathematical certainty, We can’t divide by zero, So we’re arising a
exception.
Output:
$ g++ excep.cpp
$ a.out
Division by zero condition!
1. #include <iostream>
2. using namespace std;
3. int main ()
4. {
5. try
6. {
7. throw 20;
8. }
9. catch (int e)
10. {
11. cout << "An exception occurred " << e << endl;
12. }
13. return 0;
14. }
a) 20
b) An exception occurred
c) Error
d) An exception occurred 20
View Answer
Answer: d
Explanation: We are handling the exception by throwing that number. So the output is printed
with the given number.
Output:
$ g++ excep1.cpp
$ a.out
An exception occurred 20
1. #include <iostream>
2. #include <exception>
3. using namespace std;
4. class myexception: public exception
5. {
6. virtual const char* what() const throw()
7. {
8. return "My exception";
9. }
10. } myex;
11. int main ()
12. {
13. try
14. {
15. throw myex;
16. }
17. catch (exception& e)
18. {
19. cout << e.what() << endl;
20. }
21. return 0;
22. }
a) Exception
b) Error
c) My exception
d) runtime error
View Answer
Answer: c
Explanation: This is a standard exception handler used in the class.
Output:
$ g++ excep2.cpp
$ a.out
My exception
1. #include <iostream>
2. #include <exception>
3. using namespace std;
4. int main ()
5. {
6. try
7. {
8. int* myarray = new int[1000];
9. cout << "allocated";
10. }
11. catch (exception& e)
12. {
13. cout << "Standard exception: " << e.what() << endl;
14. }
15. return 0;
16. }
a) Allocated
b) Standard exception
c) Depends on the memory
d) Error
View Answer
Answer: c
Explanation: In this program, We are allocating the memory for array. If it is allocated means, no
exception will arise and if there is no size in memory means, Exception will arise.
Output:
$ g++ excep3.cpp
$ a.out
allocated
1. #include <iostream>
2. #include <exception>
3. using namespace std;
4. struct MyException : public exception
5. {
6. const char * what () const throw ()
7. {
8. return "C++ Exception";
9. }
10. };
11. int main()
12. {
13. try
14. {
15. throw MyException();
16. }
17. catch(MyException& e)
18. {
19. cout << "Exception caught" << std::endl;
20. cout << e.what() << std::endl;
21. }
22. catch(std::exception& e)
23. {
24. }
25. }
a) C++ Exception
b) Exception caught
c) Exception caught
C++ Exception
d) Error
View Answer
Answer: c
Explanation: We are defining the user-defined exception in this program.
Output:
$ g++ excep4.cpp
$ a.out
C++ Exception
Exception caught
Answer: a
Explanation: None.
Answer: a
Explanation: bad_cast exception is thrown by dynamic_cast.
C++ Programming Questions and Answers – Grouping of Exceptions
This section on C++ test focuses on “Grouping of Exceptions”. One shall practice these test questions to
improve their C++ programming skills needed for various interviews (campus interviews, walkin
interviews, company interviews), placements, entrance exams and other competitive exams. These
questions can be attempted by anyone focusing on learning C++ programming language. They can be a
beginner, fresher, engineering graduate or an experienced IT professional. Our C++ test questions come
with detailed explanation of the answers which helps in better understanding of C++ concepts.
Here is a listing of C++ test questions on “Grouping of Exceptions” along with answers, explanations
and/or solutions:
Answer: b
Explanation: There are two types of exception handling in c++. They are synchronous exception handling
and asynchronous exception handling.
Answer: b
Explanation: There are four runtime error messages associated with exceptions.They are
overflow_error, range_error, system_error and underflow_error.
Answer: a
Explanation: None.
int main()
try
if (b == 0)
res = a / b;
cout << a << " / " << b << " = " << res;
return 0;
a) 10
b) 2
c) Bad Operator
d) 10 / 5 = 2
View Answer
Answer: d
Explanation: In this program, We are dividing the two variables and printing the result. If any one of the
operator is zero means, it will arise a exception.
Output:
$ g++ gex.cpp
$ a.out
10 / 5 =2
int main()
try
throw 1;
catch (int a)
return 0;
return 0;
a) No exception
b) exception number
c) exception number: 1
d) none of the mentioned
View Answer
Answer: c
Explanation: If we caught a integer value means, there will be an exception, if it is not a integer, there
will not be a exception.
Output:
$ g++ gex1.cpp
$ a.out
exception number: 1
#include <iostream>
int main()
{
float d;
try
if ((a - b) != 0)
d = c / (a - b);
cout << d;
else
throw(a - b);
catch (int i)
a) 10
b) -3
c) 15
d) none of the mentioned
View Answer
Answer: b
Explanation: We are manipulating the values, if there is any infinite value means, it will raise an
exception.
Output:
$ g++ gex2.cpp
$ a.out
-3
7. What is the output of this program?
#include <iostream>
void test(int x)
try
if (x > 0)
throw x;
else
throw 'x';
catch(int x)
cout<<"integer:"<<x;
catch(char x)
int main()
test(10);
test(0);
a) integer:10character:x
b) integer:10
c) character:x
d) none of the mentioned
View Answer
Answer: a
Explanation: We are passing the integer and character and catching it by using multiple catch statement.
Output:
$ g++ gex3.cpp
$ a.out
integer:10character:x
#include <iostream>
int Num;
Num = 1;
while (true)
throw Num;
Num++;
int main(void)
try
PrintSequence(2);
catch(int ExNum)
{
cout << "exception: " << ExNum << endl;
return 0;
a) 1
b) exception: 2
c) 1
exception: 2
d) none of the mentioned
View Answer
Answer: c
Explanation: In this program, We are printing one and raising a exception at 2.
Output:
$ g++ gex4.cpp
$ a.out
1
exception: 2
Answer: a
Explanation: If there is many number of exceptions in the program means, We have to use multiple
catch statement and it is hard to keep track of the program.
Answer: c
Explanation: None.
Here is a listing of C++ programming interview questions on “Catching Exceptions” along with answers,
explanations and/or solutions:
Answer: a
Explanation: In c++ program, We can be able to throw only one error at a time.
Answer: b
Explanation: none
Answer: a
Explanation: The try block is used to check for errors, if there is any error means, it can throw it to catch
block.
#include <iostream>
#include <exception>
} myex;
int main ()
try
throw myex;
catch (exception& e)
return 0;
a) exception arised
b) error
c) exception
d) runtime error
View Answer
Answer: a
Explanation: In this program, We are arising a standard exception and catching that and returning a
statement.
Output:
$ g++ goe.cpp
$ a.out
exception arised
#include <iostream>
int main()
int age=5;
try
if (age < 0)
return 0;
a) 5
b) 10
c) 15
d) Positive Number Required
View Answer
Answer: a
Explanation: In this program, We are checking the age of a person, If it is zero means, We will arise a
exception.
Output:
$ g++ goe1.cpp
$ a.out
5
6. What is the output of this program?
#include <iostream>
if ( b == 0 )
return (a / b);
int main ()
int x = 50;
int y = 0;
double z = 0;
try
z = division(x, y);
return 0;
a) 50
b) 0
c) Division by zero condition!
d) None of the mentioned
View Answer
Answer: c
Explanation: We are dividing the values and if one of the values is zero means, We are arising an
exception.
Output:
$ g++ goe2.cpp
$ a.out
Division by zero condition!
#include <iostream>
#include <string>
int main()
char Op;
try
throw Op;
switch(Op)
case '+':
break;
case '-':
break;
case '*':
case '/':
break;
cout << "\n" << Op1 << " " << Op << " "<< Op2 << " = " << Res;
return 0;
a) 15
b) 5
c) 2
d) is not a valid operator
View Answer
Answer: d
Explanation: It will arise a exception because we missed a operator.
Output:
$ g++ goe3.cpp
$ a.out
is not a valid operator
#include<iostream>
#include "math.h"
double MySqrt(double d)
if (d < 0.0)
int main()
double d = 5;
a) 5
b) 2.236
c) Error
d) Cannot take sqrt of negative number
View Answer
Answer: b
Explanation: We are finding the square root of the number, if it is a positive number, it can manipulate,
Otherwise it will arise a exception.
Output:
$ g++ goe4.cpp
$ a.out
2.236
Answer: a
Explanation: As a constructor don’t have a return type, We have to throw the exception.
Answer: b
Explanation: None.
C++ Programming Questions and Answers – Resource Management
This section on advanced C++ interview questions focuses on “Resource Management”. One shall
practice these advanced C++ questions to improve their C++ programming skills needed for various
interviews (campus interviews, walkin interviews, company interviews), placements, entrance exams
and other competitive exams. These questions can be attempted by anyone focusing on learning C++
programming language. They can be a beginner, fresher, engineering graduate or an experienced IT
professional. Our advanced C++ questions come with detailed explanation of the answers which helps in
better understanding of C++ concepts.
Here is a listing of advanced C++ interview questions on “Resource Management” along with answers,
explanations and/or solutions:
Answer: d
Explanation: If there is any mishap in memory or resource management means, the problems that are
mentioned above can happen.
Answer: b
Explanation: Resource is said to be leaked when it cannot by accessed by any means of standard mean.
Answer: a
Explanation: None
#include <new>
int main ()
int i, n;
int * p;
i = 2;
if (p == 0)
else
p[n] = 5;
delete[] p;
return 0;
a) 5
b) 55
c) 555
d) Error: memory could not be allocated
View Answer
Answer: b
Explanation: As we had given i value as 2, It will print the 5 for two times.
Output:
$ g++ res.cpp
$ a.out
55
#include <iostream>
int main(void)
return 0;
a) Test
b) TestTest
c) Te
d) None of the mentioned
View Answer
Answer: b
Explanation: We are copying the values from one variable to other, So it is printing is TestTest
Output:
$ g++ res1.cpp
$ a.out
TestTest
#include <iostream>
int funcstatic(int)
int sum = 0;
int main(void)
int r = 5, s;
s = funcstatic(r);
return 0;
a) 10
b) 15
c) error
d) none of the mentioned
View Answer
Answer: a
Explanation: Eventhough we passed the value, we didn’t caught to manipulate it, So it is printing as 10.
Output:
$ g++ res2.cpp
$ a.out
10
#include <iostream>
#include<string.h>
int main()
try
char *p;
a) How r u
b) segmentation fault
c) error
d) runtime error
View Answer
Answer: b
Explanation: As we are using a pointer value to copy a string, So it will be producing a runtime error.
Output:
$ g++ res3.cpp
$ a.out
segmentation fault
Answer: b
Explanation: The garbage collectoion attempts to reclaim memory occupied by objects that are no
longer in use by the program.
Answer: d
Explanation: new and delete operators are mainly used to allocate and deallocate
during runtime.
Answer: a
Explanation: None.
Here is a listing of C multiple choice questions on “Exceptions That Are Not Errors” along with answers,
explanations and/or solutions:
Answer: c
Explanation: None.
Answer: b
Explanation: While during dynamic memory allocation, Your system may not have sufficient resources to
handle it, So it is better to use it inside the try block.
Answer: c
Explanation: This catch statement will catch all types of exceptions that arises in the program.
#include <iostream>
int main()
int x = -1;
try
if (x < 0)
throw x;
else
cout<<x;
catch (int x )
cout << "Exception occurred: Thrown value is " << x << endl;
return 0;
a) -1
b) 0
c) Exception occurred: Thrown value is -1
d) Error
View Answer
Answer: c
Explanation: As the given value is -1 and according to the condition, We are arising an exception.
Output:
$ g++ etae.cpp
$ a.out
Exception occurred: Thrown value is -1
#include <iostream>
#include <typeinfo>
int main ()
try
Polymorphic * pb = 0;
typeid(*pb);
catch (exception& e)
return 0;
#include <iostream>
#include <exception>
void myunexpected ()
throw;
throw 'x';
set_unexpected (myunexpected);
try
myfunction();
catch (int)
}
catch (bad_exception be)
catch (...)
return 0;
Answer: d
Explanation: In this program, We are calling set_unexpected and myfunction, So it is printing the output
as the given.
Output:
$ g++ etae.cpp
$ a.out
unexpected handler called
caught bad_exception
#include <iostream>
int main()
int x = -1;
char *ptr;
try
{
if (x < 0)
throw x;
if (ptr == NULL)
catch (...)
return 0;
a) -1
b) ptr is NULL
c) exception occured: exiting
d) none of the mentioned
View Answer
Answer: c
Explanation: catch(…) is used to catch all types of exceptions arising in the program.
Output:
$ g++ etea.cpp
$ a.out
Exception occured: exiting
#include <iostream>
#include <exception>
void myunexpected ()
{
throw 0;
throw 'x';
int main ()
set_unexpected (myunexpected);
try
myfunction();
catch (int)
catch (...)
return 0;
Answer: b
Explanation: It will not throw an exception from the destructor but it will the process by using
terminate() function.
Answer: b
Explanation: None.
This section on advanced C++ interview questions focuses on “Exception Specifications”. One
shall practice these advanced C++ questions to improve their C++ programming skills needed for
various interviews (campus interviews, walkin interviews, company interviews), placements,
entrance exams and other competitive exams. These questions can be attempted by anyone
focusing on learning C++ programming language. They can be a beginner, fresher, engineering
graduate or an experienced IT professional. Our advanced C++ questions come with detailed
explanation of the answers which helps in better understanding of C++ concepts.
Here is a listing of advanced C++ interview questions on “Exception Specifications” along with
answers, explanations and/or solutions:
Answer: a
Explanation: C++ provides a mechanism to ensure that a given function is limited to throwing
only a specified list of exceptions. It is called as exception specification.
Answer: b
Explanation: None.
3. What will happen when a programs throws any other type of exception other than specified?
a) terminate
b) arise an error
c) run
d) none of the mentioned
View Answer
Answer: b
Explanation: None.
1. #include <iostream>
2. using namespace std;
3. void empty() throw()
4. {
5. cout << "In empty()";
6. }
7. void with_type() throw(int)
8. {
9. cout << "Will throw an int";
10. throw(1);
11. }
12. int main()
13. {
14. try
15. {
16. empty();
17. with_type();
18. }
19. catch (int)
20. {
21. cout << "Caught an int";
22. }
23. }
a) In empty()
b) Will throw an int
c) Caught an int
d) All of the mentioned
View Answer
Answer: d
Explanation: It will print all three because we are calling all functions in the main().
Output:
$ g++ exs.cpp
$ a.out
In empty()Will throw an intCaught an int
1. #include <iostream>
2. #include <exception>
3. #include <typeinfo>
4. using namespace std;
5. class Test1
6. {
7. virtual int Funct()
8. {
9. }
10. };
11. int main ()
12. {
13. try
14. {
15. Test1 * var = NULL;
16. typeid (*var);
17. }
18. catch (std::exception& typevar)
19. {
20. cout << "Exception: " << typevar.what() << endl;
21. }
22. return 0;
23. }
a) NULL
b) Exception:bad_alloc
c) Exception:std:bad_typeid
d) None of the mentioned
View Answer
Answer: c
Explanation: As we are using a bad type on pointers, So it is arising an error.
Output:
$ g++ exs1.cpp
$ a.out
Exception:std:bad_typeid
1. #include <iostream>
2. #include <string>
3. #include<typeinfo>
4. using namespace std;
5. int main( )
6. {
7. try
8. {
9. string strg1("Test");
10. string strg2("ing");
11. strg1.append(strg2, 4, 2);
12. cout << strg1 << endl;
13. }
14. catch (exception &e)
15. {
16. cout << "Caught: " << e.what() << endl;
17. cout << "Type: " << typeid(e).name() << endl;
18. };
19. return 0;
20. }
a) out of range
b) bad type_id
c) bad allocation
d) none of the mentioned
View Answer
Answer: a
Explanation: As we are using out of bound value on strings, So it arising an exception.
Output:
$ g++ exs2.cpp
$ a.out
Caught: basic_string::append
Type: St12out_of_range
#include
Answer: c
Explanation: As we can’t able to create the dynamic instance for the triangle, So it is arising an
exception.
Output:
$ g++ exs3.cpp
$ a.out
Can’t do the dynamic_cast lor!!!
Caught: bad_cast exception. Myshape is not mytriangle.
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. char* ptr;
6. unsigned long int Test = sizeof(size_t(0) / 3);
7. cout << Test << endl;
8. try
9. {
10. ptr = new char[size_t(0) / 3];
11. delete[ ] ptr;
12. }
13. catch (bad_alloc &thebadallocation)
14. {
15. cout << thebadallocation.what() << endl;
16. };
17. return 0;
18. }
a) 4
b) 2
c) bad_alloc
d) depends on compiler
View Answer
Answer: d
Explanation: The size of unsigned long int always depends on compiler.
Output:
$ g++ exs4.cpp
$ a.out
4
Answer: b
Explanation: None.
Answer: b
Explanation: None.
C++ Programming Questions and Answers – Uncaught Exceptions
This section on C++ programming questions and answers focuses on “Uncaught Exceptions”. One shall
practice these questions to improve their C++ programming skills needed for various interviews (campus
interviews, walkin interviews, company interviews), placements, entrance exams and other competitive
exams. These questions can be attempted by anyone focusing on learning C++ programming language.
They can be a beginner, fresher, engineering graduate or an experienced IT professional. Our C++
programming questions come with detailed explanation of the answers which helps in better
understanding of C++ concepts.
Here is a listing of C++ programming questions on “Uncaught Exceptions” along with answers,
explanations and/or solutions:
Answer: a
Explanation: None.
Answer: b
Explanation: To catch all types of exceptions, we use catch-all handler.
Answer: a
Explanation: The ellipses operator can be represented as (…).
class Base
protected:
int a;
public:
Base()
a = 34;
Base(int i)
a = i;
virtual ~Base()
if (a < 0) throw a;
if (a < 0)
throw a;
};
int main()
{
try
Base b(-25);
catch (int)
a) Illegal initialization
b) Terminate called after throwing an instance of ‘int’
c) Illegal initialization & terminate called after throwing an instance
d) None of the mentioned
View Answer
Answer: b
Explanation: As we are throwing an negative number and we are using only integer, So it is arising an
error.
Output:
$ g++ uce.cpp
$ a.out
terminate called after throwing an instance of ‘int’
#include <iostream>
#include <exception>
void terminator()
class Botch
{
public:
void f()
throw Fruit();
~Botch()
throw 'c';
};
int main()
try
Botch b;
b.f();
catch(...)
a) one
b) inside catch
c) one
terminate
d) one
terminate
Aborted
View Answer
Answer: d
Explanation: This program uses set_terminate as it is having an uncaught exception.
Output:
$ g++ uce1.cpp
$ a.out
one
terminate
Aborted
#include <iostream>
#include <exception>
#include <cstdlib>
void myterminate ()
abort();
set_terminate (myterminate);
throw 0;
return 0;
Answer: c
Explanation: In this program, We are using set_terminate to abort the program.
Output:
$ g++ uce2.cpp
$ a.out
terminate handler called
Aborted
#include <iostream>
class Test1
};
void Funct();
int main()
try
Funct();
return 0;
void Funct()
throw Test2();
}
a) Caught an exception
b) NULL
c) Both Caught an exception & NULL
d) None of the mentioned
View Answer
Answer: a
Explanation: In this program, We are arising the exception by using the method in the class.
Output:
$ g++ uce3.cpp
$ a.out
Caught a exception
#include <iostream>
#include <cstdlib>
#include <exception>
void Funct()
exit(0);
int main()
try
set_terminate(Funct);
catch(int)
}
return 0;
Answer: b
Explanation: As there is no integer in this program, We are printing Funct() was called by terminate().
Output:
$ g++ uce4.cpp
$ a.out
Funct() was called by terminate().
Answer: c
Explanation: If we have an uncaught exception means, compiler will throw the control of program to
terminate function.
10. What will not be called when the terminate() is arised in constructor?
a) main()
b) class
c) destructor
d) none of the mentioned
View Answer
Answer: c
Explanation: None.
This section on C++ test focuses on “Exceptions and Efficiency”. One shall practice these test
questions to improve their C++ programming skills needed for various interviews (campus
interviews, walkin interviews, company interviews), placements, entrance exams and other
competitive exams. These questions can be attempted by anyone focusing on learning C++
programming language. They can be a beginner, fresher, engineering graduate or an experienced
IT professional. Our C++ test questions come with detailed explanation of the answers which
helps in better understanding of C++ concepts.
Here is a listing of C++ test questions on “Exceptions and Efficiency” along with answers,
explanations and/or solutions:
1. What will happen when we move try block far away from catch block?
a) Reduces the amount of code in cache
b) Increases the amount of code in cache
c) Don’t alter anything
d) None of the mentioned
View Answer
Answer: a
Explanation: compilers may try to move the catch-code far away from the try-code, which
reduces the amount of code to keep in cache normally, thus enhancing performance.
2. What will happen if an excpetion that is thrown may causes a whole load of objects to go out
of scope?
a) Terminate the program
b) Produce a runtime error
c) It will be added to the overhead
d) None of the mentioned
View Answer
Answer: c
Explanation: None.
Answer: b
Explanation: It will be used to free all the resources that are used by block of code during
execution.
1. #include <iostream>
2. #include <exception>
3. using namespace std;
4. int main ()
5. {
6. try
7. {
8. double* i= new double[1000];
9. cout << "Memory allocated";
10. }
11. catch (exception& e)
12. {
13. cout << "Exception arised: " << e.what() << endl;
14. }
15. return 0;
16. }
a) Memory allocated
b) Exception arised
c) Depends on the computer memory
d) None of the mentioned
View Answer
Answer: c
Explanation: The value will be allocated, if there is enough memory in the system.
Output:
$ g++ expef.cpp
$ a.out
Memory allocated
1. #include <iostream>
2. using namespace std;
3. void test(int x)
4. {
5. try
6. {
7. if (x > 0)
8. throw x;
9. else
10. throw 'x';
11. }
12. catch(char)
13. {
14. cout << "Catch a integer and that integer is:" << x;
15. }
16. }
17. int main()
18. {
19. cout << "Testing multiple catches\n:";
20. test(10);
21. test(0);
22. }
a) Catch a integer and that integer is:10
b) Error
c) Runtime error
d) None of the mentioned
View Answer
Answer: c
Explanation: As the catch is created with a wrong type, So it will
arise a runtime error.
Output:
$ g++ expef.cpp
$ a.out
Testing multiple catches
terminate called after throwing an instance of ‘int’
:Aborted
1. #include <stdexcept>
2. #include <limits>
3. #include <iostream>
4. using namespace std;
5. void func(int c)
6. {
7. if (c < numeric_limits<char> :: max())
8. throw invalid_argument("MyFunc argument too large.");
9. else
10. {
11. cout<<"Executed";
12. }
13. }
14. int main()
15. {
16. try
17. {
18. func(256);
19. }
20. catch(invalid_argument& e)
21. {
22. cerr << e.what() << endl;
23. return -1;
24. }
25. return 0;
26. }
a) Invalid arguments
b) Executed
c) Error
d) Runtime error
View Answer
Answer: b
Explanation: As we are throwing the function and catching it with a correct data type, So this
program will execute.
Output:
$ g++ expef.cpp
$ a.out
Executed
1. #include <iostream>
2. #include <string>
3. using namespace std;
4. int main ()
5. {
6. int num = 3;
7. string str_bad = "wrong number used";
8. try
9. {
10. if ( num == 1 )
11. {
12. throw 5;
13. }
14. if ( num == 2 )
15. {
16. throw 1.1f;
17. }
18. if ( num != 1 || num != 2 )
19. {
20. throw str_bad;
21. }
22. }
23. catch (int a)
24. {
25. cout << "Exception is: " << a << endl;
26. }
27. catch (float b)
28. {
29. cout << "Exception is: " << b << endl;
30. }
31. catch (...)
32. {
33. cout << str_bad << endl;
34. }
35. return 0;
36. }
a) Exception is 5
b) Exception is 1.1f
c) Wrong number used
d) None of the mentioned
View Answer
Answer: c
Explanation: As we are giving 3 to num, It is arising an exception named
“wrong number used”.
Output:
$ g++ expef.cpp
$ a.out
wrong number used
1. #include <iostream>
2. using namespace std;
3. double division(int a, int b)
4. {
5. if (b == 0)
6. {
7. throw "Division by zero condition!";
8. }
9. return (a / b);
10. }
11. int main ()
12. {
13. int x = 50;
14. int y = 0;
15. double z = 0;
16. try
17. {
18. z = division(x, y);
19. cout << z << endl;
20. }
21. catch (const msg)
22. {
23. cerr << msg << endl;
24. }
25. return 0;
26. }
a) 50
b) 0
c) Division by zero condition
d) Error
View Answer
Answer: d
Explanation: As we missed the data type in the catch block, It will arise an error.
Answer: c
Explanation: The purpose of a constructor is to establish the class invariant. To do that, it often
needs to acquire system resources or in general perform an operation that may fail.
Answer: a
Explanation: If an error occurs in program, then only exception object is created otherwise, It
will not be created. So it’s expensive to use in the program.
This section on C++ programming interview questions and answers focuses on “Error Handling
Alternatives”. One shall practice these interview questions to improve their C++ programming
skills needed for various interviews (campus interviews, walkin interviews, company
interviews), placements, entrance exams and other competitive exams. These questions can be
attempted by anyone focusing on learning C++ programming language. They can be a beginner,
fresher, engineering graduate or an experienced IT professional. Our C++ programming
interview questions come with detailed explanation of the answers which helps in better
understanding of C++ concepts.
Answer: c
Explanation: throw and return does the same job like return a value. So it can be replaced.
2. What are the disadvantages if use return keyword to return error codes?
a) You have to handle all exceptional cases explicitly
b) Your code size increases dramatically
c) The code becomes more difficult to read
d) All of the mentioned
View Answer
Answer: d
Explanation: As we are using return for each and every exception, It will definetly increase the
code size.
3. What is most suitable for returning the logical errors in the program?
a) Use contructor and destructor
b) Set a global error indicator
c) Use break keyword
d) None of the mentioned
View Answer
Answer: b
Explanation: None.
1. #include <iostream>
2. #include <typeinfo>
3. using namespace std;
4. class A
5. {
6. };
7. int main()
8. {
9. char c; float x;
10. if (typeid(c) != typeid(x))
11. cout << typeid(c).name() << endl;
12. cout << typeid(A).name();
13. return 0;
14. }
a) c
1A
b) x
c) Both c & x
d) None of the mentioned
View Answer
Answer: a
Explanation: We are checking the type id of char and float as they are not equal, We are printing
c.
Output:
$ g++ eal.cpp
$ a.out
c
1A
1. #include <iostream>
2. using namespace std;
3. void Division(const double a, const double b);
4. int main()
5. {
6. double op1=0, op2=10;
7. try
8. {
9. Division(op1, op2);
10. }
11. catch (const char* Str)
12. {
13. cout << "\nBad Operator: " << Str;
14. }
15. return 0;
16. }
17. void Division(const double a, const double b)
18. {
19. double res;
20. if (b == 0)
21. throw "Division by zero not allowed";
22. res = a / b;
23. cout << res;
24. }
a) 0
b) Bad operator
c) 10
d) None of the mentioned
View Answer
Answer: a
Explanation: We are dividing 0 and 10 in this program and we are using the throw statement in
the function block.
Output:
$ g++ eal.cpp
$ a.out
0
1. #include <stdexcept>
2. #include <limits>
3. #include <iostream>
4. using namespace std;
5. void MyFunc(char c)
6. {
7. if (c < numeric_limits<char>::max())
8. return invalid_argument;
9. }
10. int main()
11. {
12. try
13. {
14. MyFunc(256);
15. }
16. catch(invalid_argument& e)
17. {
18. cerr << e.what() << endl;
19. return -1;
20. }
21. return 0;
22. }
a) 256
b) Invalid argument
c) Error
d) None of the mentioned
View Answer
Answer: c
Explanation: We can’t return a statement by using the return keyword, So it is arising an error.
Answer: a
Explanation: None.
Answer: c
Explanation: The three levels of exception safety are basic, strong and nothrow.
9. Pick out the correct statement for error handling alternatives.
a) Terminate the program
b) Use the stack
c) Exit from the block
d) None of the mentioned
View Answer
Answer: b
Explanation: When an error is arised means, it will be pushed into stack and it can be corrected
later by the programmer.
Answer: a
Explanation: As in the case of not using an exception, it will remain useless in the program and
increase the code complexity.
Here is a listing of C++ problems on “Standard Exceptions” along with answers, explanations and/or
solutions:
a) #include<exception>
b) #include<except>
c) #include<error>
View Answer
Answer: a
Explanation: None.
2. Where are standard exception classes grouped?
a) namespace std
b) error
c) catch
d) none of the mentioned
View Answer
Answer: a
Explanation: As these are standard exceptions, they need to be defined in the standard block, So it is
defined under namespace std.
Answer: a
Explanation: There are nine standard exceptions in c++. They are bad_alloc, bad_cast, bad_exception,
bad_function_call, bad_typeid, bad_weak_ptr, ios_base::failure, logic_error and runtime_error.
#include <iostream>
#include <exception>
} myex;
int main ()
try
{
throw myex;
catch (exception& e)
return 0;
a) My
b) My exception
c) No exception
d) None of the mentioned
View Answer
Answer: b
Explanation: This is a type of exception arising in the class. We can call this
also as a standard exception.
Output:
$ g++ std.cpp
$ a.out
My exception
#include <iostream>
#include <exception>
int main ()
try
catch (exception& e)
{
return 0;
a) Allocated
b) Standard exception:
c) bad_alloc
d) Depends on memory
View Answer
Answer: d
Explanation: Variable will be allocated depends on the available space in the memory, If there is no
space means, It will throw an exception.
Output:
$ g++ std1.cpp
$ a.out
Allocated
#include <iostream>
int main()
char* ptr;
try
delete[ ] ptr;
catch(bad_alloc &thebadallocation)
{
cout << thebadallocation.what() << endl;
};
return 0;
a) 0
b) 2
c) bad_alloc
d) depends on compiler
View Answer
Answer: a
Explanation: As we are dividing the zero by three, it is returning 0.
Output:
$ g++ std2.cpp
$ a.out
0
#include <typeinfo>
#include <iostream>
class shape
public:
};
public:
};
};
int main()
{
shape shape_instance;
try
catch (bad_cast)
return 0;
Answer: c
Explanation: As we are not able to allocate the values by using dynamic cast,
So it is arising an exception.
Output:
$ g++ std3.cpp
$ a.out
Caught: bad_cast exception
#include <typeinfo>
#include <iostream>
class Test
public:
Test();
virtual ~Test();
};
int main()
try
catch (bad_typeid)
return 0;
a) No exception arises
b) The object is null
c) Error
d) None of the mentioned
View Answer
Answer: b
Explanation: As there is no object in the class, It is arising an exception in the program.
Output:
$ g++ std4.cpp
$ a.out
The object is null
Answer: c
Explanation: None.
This section on C++ questions and puzzles focuses on “Class Hierarchies Introduction”. One
shall practice these questions and puzzles to improve their C++ programming skills needed for
various interviews (campus interviews, walkin interviews, company interviews), placements,
entrance exams and other competitive exams. These programming puzzles can be attempted by
anyone focusing on learning C++ programming language. They can be a beginner, fresher,
engineering graduate or an experienced IT professional. Our C++ questions come with detailed
explanation of the answers which helps in better understanding of C++ concepts.
Here is a listing of C++ questions and puzzles on “Class Hierarchies Introduction” along with
answers, explanations and/or solutions:
1. What will happen when introduce the interface of classes in a run-time polymorphic
hierarchy?
a) Separation of interface from implementation
b) Merging of interface from implementation
c) Separation of interface from debugging
d) None of the mentioned
View Answer
Answer: a
Explanation: None.
Answer: b
Explanation: A class that expresses functionality rather than its primary design role is called a
mixin.
Answer: a
Explanation: clog is an object of class ostream that represents the standard logging stream. It is
associated with the cstdio stream stderr, like cerr.
1. #include <iostream>
2. #include <sstream>
3. using namespace std;
4. int main()
5. {
6. stringstream mys(ios :: in | ios :: out);
7. std :: string dat("The double value is : 74.79 .");
8. mys.str(dat);
9. mys.seekg(-7, ios :: end);
10. double val;
11. mys >> val;
12. val = val*val;
13. mys.seekp(-7,ios::end);
14. mys << val;
15. std :: string new_val = mys.str();
16. cout << new_val;
17. return 0;
18. }
a) 5593.54
b) Error
c) Runtime error
d) None of the mentioned
View Answer
Answer: a
Explanation: In this program, We have used the string hierarchicy to compute the square of the
number.
Output:
$ g++ class.cpp
$ a.out
The double value is : 5593.54 .
1. #include <iostream>
2. using namespace std;
3. class Base
4. {
5. public:
6. Base(){}
7. ~Base(){}
8. protected:
9. private:
10. };
11. class Derived:public Base
12. {
13. public:
14. Derived(){}
15. Derived(){}
16. private:
17. protected:
18. };
19. int main()
20. {
21. cout << "The program exceuted" << endl;
22. }
Answer: b
Explanation: We are not allowed to overload the constructors, So it is arising an exception.
1. #include <iostream>
2. using namespace std;
3. class MyException
4. {
5. public:
6. MyException(int value) : mValue(value)
7. {
8. }
9. int mValue;
10. };
11. class MyDerivedException : public MyException
12. {
13. public:
14. MyDerivedException(int value, int anotherValue) :
MyException(value), mAnotherValue(anotherValue)
15. {
16. }
17. int mValue;
18. int mAnotherValue;
19. };
20. void doSomething()
21. {
22. throw MyDerivedException(10,20);
23. }
24. int main()
25. {
26. try
27. {
28. doSomething();
29. }
30. catch (MyDerivedException &exception)
31. {
32. cout << "\nCaught Derived Class Exception\n";
33. }
34. catch (MyException &exception)
35. {
36. cout << "\nCaught Base Class Exception\n";
37. }
38. return 0;
39. }
Answer: b
Explanation: As we are throwing the value from the derived class, it is arising an exception in
derived class
Output:
$ g++ class1.cpp
$ a.out
Caught Derived Class Exception
1. #include <iostream>
2. #include <string>
3. using namespace std;
4. int main()
5. {
6. string s = "a long string";
7. s.insert(s.size() / 2, " * ");
8. cout << s << endl;
9. return 0;
10. }
a) a long* string
b) a long st*ring
c) Depends on compiler
d) None of the mentioned
View Answer
Answer: c
Explanation: In this program, We are placing the string based on the size of the string and it is a
string hierarchicy.
Output:
$ g++ class2.cpp
$ a.out
a long* string
8. How many types of guarantees are there in exception class can have?
a) 1
b) 2
c) 3
d) 4
View Answer
Answer: c
Explanation: There are three types of guarantees in c++. They are weak, strong and no-throw.
Answer: d
Explanation: We can make user-defined types with streams by overloading the insertion operator
(<<) to put objects into streams and the extraction operator (>>) to read objects from streams.
Answer: a
Explanation: cerr is an object of class ostream that represents the standard error stream. It is
associated with the cstdio stream stderr.
C++ Programming Questions and Answers - Multiple Inheritance -
Sanfoundry
by Manish
This section on C++ programming questions and answers focuses on “Multiple Inheritance”.
One shall practice these questions to improve their C++ programming skills needed for various
interviews (campus interviews, walkin interviews, company interviews), placements, entrance
exams and other competitive exams. These questions can be attempted by anyone focusing on
learning C++ programming language. They can be a beginner, fresher, engineering graduate or
an experienced IT professional. Our C++ programming questions come with detailed explanation
of the answers which helps in better understanding of C++ concepts.
Here is a listing of C++ programming questions on “Multiple Inheritance” along with answers,
explanations and/or solutions:
Answer: c
Explanation: Multiple inheritance enables a derived class to inherit members from more than one
parent.
Answer: b
Explanation: For using multiple inheritance, simply specify each base class (just like in single
inheritance), separated by a comma.
1. #include <iostream>
2. using namespace std;
3. class polygon
4. {
5. protected:
6. int width, height;
7. public:
8. void set_values (int a, int b)
9. {
10. width = a; height = b;}
11. };
12. class output1
13. {
14. public:
15. void output (int i);
16. };
17. void output1::output (int i)
18. {
19. cout << i << endl;
20. }
21. class rectangle: public polygon, public output1
22. {
23. public:
24. int area ()
25. {
26. return (width * height);
27. }
28. };
29. class triangle: public polygon, public output1
30. {
31. public:
32. int area ()
33. {
34. return (width * height / 2);
35. }
36. };
37. int main ()
38. {
39. rectangle rect;
40. triangle trgl;
41. rect.set_values (4, 5);
42. trgl.set_values (4, 5);
43. rect.output (rect.area());
44. trgl.output (trgl.area());
45. return 0;
46. }
a) 20
b) 10
c) 20
10
d) None of the mentioned
View Answer
Answer: c
Explanation: We are using the multiple inheritance to find the area of rectangle and triangle.
Output:
$ g++ mul.cpp
$ a.out
20
10
1. #include <iostream>
2. using namespace std;
3. class Base
4. {
5. public:
6. virtual void print() const = 0;
7. };
8. class DerivedOne : public Base
9. {
10. public:
11. void print() const
12. {
13. cout << "DerivedOne\n";
14. }
15. };
16. class DerivedTwo : public Base
17. {
18. public:
19. void print() const
20. {
21. cout << "DerivedTwo\n";
22. }
23. };
24. class Multiple : public DerivedOne, public DerivedTwo
25. {
26. public:
27. void print() const
28. {
29. DerivedTwo :: print();
30. }
31. };
32. int main()
33. {
34. int i;
35. Multiple both;
36. DerivedOne one;
37. DerivedTwo two;
38. Base *array[ 3 ];
39. array[ 0 ] = &both;
40. array[ 1 ] = &one;
41. array[ 2 ] = &two;
42. array[ i ] -> print();
43. return 0;
44. }
a) DerivedOne
b) DerivedTwo
c) Error
d) None of the mentioned
View Answer
Answer: c
Explanation: In this program, ‘Base’ is an ambiguous base of ‘Multiple’. So it is producing an
error. And this program is a virtual base class.
1. #include <iostream>
2. using namespace std;
3. class student
4. {
5. public:
6. int rno , m1 , m2 ;
7. void get()
8. {
9. rno = 15, m1 = 10, m2 = 10;
10. }
11. };
12. class sports
13. {
14. public:
15. int sm;
16. void getsm()
17. {
18. sm = 10;
19. }
20. };
21. class statement:public student,public sports
22. {
23. int tot,avg;
24. public:
25. void display()
26. {
27. tot = (m1 + m2 + sm);
28. avg = tot / 3;
29. cout << tot;
30. cout << avg;
31. }
32. };
33. int main()
34. {
35. statement obj;
36. obj.get();
37. obj.getsm();
38. obj.display();
39. }
a) 3100
b) 3010
c) 2010
d) 1010
View Answer
Answer: b
Explanation: In this program, We are calculating the total and average marks of a student by
using multiple inheritance.
Output:
$ g++ mul1.cpp
$ a.out
3010
1. #include <iostream>
2. using namespace std;
3. struct a
4. {
5. int count;
6. };
7. struct b
8. {
9. int* value;
10. };
11. struct c : public a, public b
12. {
13. };
14. int main()
15. {
16. c* p = new c;
17. p->value = 0;
18. cout << "Inherited";
19. return 0;
20. }
a) Inherited
b) Error
c) Runtime error
d) None of the mentioned
View Answer
Answer: a
Explanation: In this program, We apply the multiple inheritance to structure.
Output:
$ g++ mul2.cpp
$ a.out
Inherited
1. #include <iostream>
2. using namespace std;
3. class Base1
4. {
5. protected:
6. int SampleDataOne;
7. public:
8. Base1()
9. {
10. SampleDataOne = 100;
11. }
12. ~Base1()
13. {
14. }
15. int SampleFunctOne()
16. {
17. return SampleDataOne;
18. }
19. };
20. class Base2
21. {
22. protected:
23. int SampleDataTwo;
24. public:
25. Base2()
26. {
27. SampleDataTwo = 200;
28. }
29. ~Base2()
30. {
31. }
32. int SampleFunctTwo()
33. {
34. return SampleDataTwo;
35. }
36. };
37. class Derived1 : public Base1, public Base2
38. {
39. int MyData;
40. public:
41. Derived1()
42. {
43. MyData = 300;
44. }
45. ~Derived1()
46. {
47. }
48. int MyFunct()
49. {
50. return (MyData + SampleDataOne + SampleDataTwo);
51. }
52. };
53. int main()
54. {
55. Base1 SampleObjOne;
56. Base2 SampleObjTwo;
57. Derived1 SampleObjThree;
58. cout << SampleObjThree.Base1 :: SampleFunctOne() << endl;
59. cout << SampleObjThree.Base2 :: SampleFunctTwo() << endl;
60. return 0;
61. }
a) 100
b) 200
c) Both 100 & 200
d) None of the mentioned
View Answer
Answer: c
Explanation: In this program, We are passing the values by using multiple inheritance and
printing the derived values.
Output:
$ g++ mul4.cpp
$ a.out
100
200
Answer: a
Explanation: None.
10. What are the things are inherited from the base class?
a) Constructor and its destructor
b) Operator=() members
c) Friends
d) All of the mentioned
View Answer
Answer: d
Explanation: These things can provide necessary information for the base class to make a logical
decision.
Advanced C++ Interview Questions - Access Control - Sanfoundry
by Manish
This section on advanced C++ interview questions focuses on “Access Control”. One shall
practice these advanced C++ questions to improve their C++ programming skills needed for
various interviews (campus interviews, walkin interviews, company interviews), placements,
entrance exams and other competitive exams. These questions can be attempted by anyone
focusing on learning C++ programming language. They can be a beginner, fresher, engineering
graduate or an experienced IT professional. Our advanced C++ questions come with detailed
explanation of the answers which helps in better understanding of C++ concepts.
Here is a listing of advanced C++ interview questions on “Access Control” along with answers,
explanations and/or solutions:
Answer: c
Explanation: There are three access specifiers in c++. They are public, Private and Protected.
Answer: c
Explanation: None.
Answer: c
Explanation: The access specifiers can be applicable to the member data and functions because
they need to be accessed outside the block.
a) 3010
b) 1010
c) 2100
d) Error
View Answer
Answer: a
Explanation: None.
5. What is the output of this program?
1. #include <iostream>
2. using namespace std;
3. struct A
4. {
5. int i;
6. char j;
7. float f;
8. void func();
9. };
10. void A :: func() {}
11. struct B
12. {
13. public:
14. int i;
15. char j;
16. float f;
17. void func();
18. };
19. void B :: func() {}
20. int main()
21. {
22. A a; B b;
23. a.i = b.i = 1;
24. a.j = b.j = 'c';
25. a.f = b.f = 3.14159;
26. a.func();
27. b.func();
28. cout << "Allocated";
29. return 0;
30. }
a) Allocated
b) Error
c) 3.14159
d) None of the mentioned
View Answer
Answer: a
Explanation: In this program, We used access specifiers for structures, As we declared all
methods as public, The values can be allocated.
Output:
$ g++ acc.cpp
$ a.out
Allocated
1. #include <iostream>
2. using namespace std;
3. struct A
4. {
5. private:
6. int i, j, k;
7. public:
8. int f();
9. void g();
10. };
11. int A :: f()
12. {
13. return i + j + k;
14. }
15. void A :: g()
16. {
17. i = j = k = 0;
18. }
19. class B
20. {
21. int i, j, k;
22. public:
23. int f();
24. void g();
25. };
26. int B :: f()
27. {
28. return i + j + k;
29. }
30. void B :: g()
31. {
32. i = j = k = 0;
33. }
34. int main()
35. {
36. A a;
37. B b;
38. a.f();
39. a.g();
40. b.f();
41. b.g();
42. cout << "Identical results would be produced";
43. }
a) 50
b) Identical results would be produced
c) Error
d) Runtime error
View Answer
Answer: b
Explanation: In this program, We apply the access specifiers to both the class and the structure.
Output:
$ g++ acc1.cpp
$ a.out
Identical results would be produced
7. What is the output of this program?
1. #include <iostream>
2. using namespace std;
3. class Cat
4. {
5. public:
6. int age;
7. int weight;
8. };
9. int main()
10. {
11. Cat f;
12. f.age = 56;
13. cout << "Gates is " ;
14. cout << f.age << " years old.\n";
15. }
a) Gates is
b) Gates is 56 years old
c) Error
d) None of the mentioned
View Answer
Answer: b
Explanation: In this program, We passed the value from main function to class and returning it to
the main and then printing it.
Output:
$ g++ acc2.cpp
$ a.out
Gates is 56 years old
1. #include <iostream>
2. using namespace std;
3. struct X;
4. struct Y
5. {
6. void f(X*);
7. };
8. struct X
9. {
10. private:
11. int i;
12. public:
13. void initialize();
14. friend void g(X* , int);
15. friend void Y :: f(X*);
16. friend struct Z;
17. friend void h();
18. };
19. void X :: initialize()
20. {
21. i = 0;
22. }
23. void g(X* x, int i)
24. {
25. x -> i = i;
26. }
27. void Y :: f(X * x)
28. {
29. x -> i = 47;
30. cout << x->i;
31. }
32. struct Z
33. {
34. private:
35. int j;
36. public:
37. void initialize();
38. void g(X* x);
39. };
40. void Z::initialize()
41. {
42. j = 99;
43. }
44. void Z::g(X* x)
45. {
46. x -> i += j;
47. }
48. void h()
49. {
50. X x;
51. x.i = 100;
52. cout << x.i;
53. }
54. int main()
55. {
56. X x;
57. Z z;
58. z.g(&x);
59. cout << "Data accessed";
60. }
a) 99
b) 47
c) Data accessed
d) None of the mentioned
View Answer
Answer: c
Explanation: In this program, We are using the access specifiers to friend function to manipulate
the values.
Output:
$ g++ acc3.cpp
$ a.out
Data accessed
Answer: c
Explanation: None.
Answer: a
Explanation: Mutable keyword allows assigning values to a data member belonging to a class
defined as “Const” or constant.
This section on C++ interview questions and answers focuses on “Run Time Type Information”.
One shall practice these interview questions to improve their C++ programming skills needed for
various interviews (campus interviews, walkin interviews, company interviews), placements,
entrance exams and other competitive exams. These questions can be attempted by anyone
focusing on learning C++ programming language. They can be a beginner, fresher, engineering
graduate or an experienced IT professional. Our C++ interview questions come with detailed
explanation of the answers which helps in better understanding of C++ concepts.
Here is a listing of C++ interview questions on “Run Time Type Information” along with
answers, explanations and/or solutions:
Answer: c
Explanation: The dynamic_cast<> operation and typeid operator in C++ are part of RTTI.
Answer: b
Explanation: RTTI is available only for classes which are polymorphic, which means they have
at least one virtual method.
1. #include <iostream>
2. #include <exception>
3. using namespace std;
4. class base { virtual void dummy() {} };
5. class derived: public base { int a; };
6. int main ()
7. {
8. try
9. {
10. base * pba = new derived;
11. base * pbb = new base;
12. derived * pd;
13. pd = dynamic_cast<derived*>(pba);
14. if (pd == 0)
15. cout << "Null pointer on first type-cast" << endl;
16. pd = dynamic_cast<derived*>(pbb);
17. if (pd == 0)
18. cout << "Null pointer on second type-cast" << endl;
19. }
20. catch (exception& e)
21. {
22. cout << "Exception: " << e.what();
23. }
24. return 0;
25. }
Answer: b
Explanation: In this program, We apply the dynamic cast to pd. Based on the value in the pd, it
produces the output.
Output:
$ g++ rtti.cpp
$ a.out
Null pointer on second type-cast
1. #include <iostream>
2. #include <typeinfo>
3. using namespace std;
4. int main ()
5. {
6. int * a;
7. int b;
8. a = 0; b = 0;
9. if (typeid(a) != typeid(b))
10. {
11. cout << typeid(a).name();
12. cout << typeid(b).name();
13. }
14. return 0;
15. }
a) Pi
b) i
c) Both pi & i
d) f
View Answer
Answer: c
Explanation: In this program, We are finding the typeid of the given variables.
Output:
$ g++ rtti1.cpp
$ a.out
Pii
a) base*
b) derived*
c) 4base and 7derived
d) none of the mentioned
View Answer
Answer: c
Explanation: In this program, We apply the typeid to the polymorphic class.
Output:
$ g++ rtti2.cpp
$ a.out
4base 7derived
1. #include <typeinfo>
2. #include <iostream>
3. using namespace std;
4. class A
5. {
6. public:
7. virtual ~A();
8. };
9. int main()
10. {
11. A* a = NULL;
12. try
13. {
14. cout << typeid(*a).name() << endl;
15. }
16. catch (bad_typeid)
17. {
18. cout << "Object is NULL" << endl;
19. }
20. }
a) int
b) float
c) double
d) object is NULL
View Answer
Answer: d
Explanation: In this program, We are using the bad typeid() for a. So it is arising an exception.
Output:
$ g++ rtti3.cpp
$ a.out
object is NULL
1. #include <iostream>
2. using namespace std;
3. struct A
4. {
5. virtual void f()
6. {
7. cout << "Class A" << endl;
8. }
9. };
10. struct B : A
11. {
12. virtual void f()
13. {
14. cout << "Class B" << endl;
15. }
16. };
17. struct C : A
18. {
19. virtual void f()
20. {
21. cout << "Class C" << endl;
22. }
23. };
24. void f(A* arg)
25. {
26. B* bp = dynamic_cast<B*>(arg);
27. C* cp = dynamic_cast<C*>(arg);
28. if (bp)
29. bp -> f();
30. else if (cp)
31. cp -> f();
32. else
33. arg -> f();
34. };
35. int main()
36. {
37. A aobj;
38. C cobj;
39. A* ap = &cobj;
40. A* ap2 = &aobj;
41. f(ap);
42. f(ap2);
43. }
a) Class C
b) Class A
c) Both Class C & A
d) None of the mentioned
View Answer
Answer: c
Explanation: In this program, We applied the dynamic casting to structure and produced the
output.
Output:
$ g++ rtti4.cpp
$ a.out
Class C
Class A
Answer: a
Explanation: None.
Answer: a
Explanation: Static_cast can be applied to only compile-time construct and not during run time
construct.
C++ Language Interview Questions - Pointers to Members - Sanfoundry
by Manish
This section on C++ language interview questions and answers focuses on “Pointers to
Members”. One shall practice these interview questions to improve their C++ programming
skills needed for various interviews (campus interviews, walkin interviews, company
interviews), placements, entrance exams and other competitive exams. These questions can be
attempted by anyone focusing on learning C++ programming language. They can be a beginner,
fresher, engineering graduate or an experienced IT professional. Our C++ language interview
questions come with detailed explanation of the answers which helps in better understanding of
C++ concepts.
Here is a listing of C++ language interview questions on “Pointers to Members” along with
answers, explanations and/or solutions:
Answer: b
Explanation: We cannot use a pointer to member to point to a static class member because the
address of a static member is not associated with any particular object.
Answer: c
Explanation: None.
Answer: c
Explanation: The pointer to member operators .* and ->* are used to bind a pointer to a member
of a specific class object.
4. What is the output of this program?
1. #include <iostream>
2. using namespace std;
3. class X
4. {
5. public:
6. int a;
7. void f(int b)
8. {
9. cout<< b << endl;
10. }
11. };
12. int main()
13. {
14. int X :: *ptiptr = &X :: a;
15. void (X :: * ptfptr) (int) = &X :: f;
16. X xobject;
17. xobject.*ptiptr = 10;
18. cout << xobject.*ptiptr << endl;
19. (xobject.*ptfptr) (20);
20. }
a) 10
20
b) 20
10
c) 20
d) 10
View Answer
Answer: a
Explanation: In this program, We are assigning 10 and printing it in the
main function and then for value 20, We are passing the value to class and
printing it.
Output:
$ g++ ptm.cpp
$ a.out
10
20
1. #include <iostream>
2. using namespace std;
3. class Testpm
4. {
5. public:
6. void m_func1()
7. {
8. cout << "func1\n";
9. }
10. int m_num;
11. };
12. void (Testpm :: *pmfn)() = &Testpm :: m_func1;
13. int Testpm :: *pmd = &Testpm :: m_num;
14. int main()
15. {
16. Testpm ATestpm;
17. Testpm *pTestpm = new Testpm;
18. (ATestpm.*pmfn)();
19. (pTestpm ->* pmfn)();
20. ATestpm.*pmd = 1;
21. pTestpm ->* pmd = 2;
22. cout << ATestpm.*pmd << endl
23. << pTestpm ->* pmd << endl;
24. }
a) func1
b) func1
func1
c) 1
2
d) func1
func1
1
2
View Answer
Answer: d
Explanation: In this program, As we are passing the value twice to the method
in the class, It is printing the func1 twice and then it is printing the given
value.
Output:
$ g++ ptm1.cpp
$ a.out
func1
func1
1
2
1. #include <iostream>
2. using namespace std;
3. class Car
4. {
5. public:
6. int speed;
7. };
8. int main()
9. {
10. int Car :: *pSpeed = &Car :: speed;
11. Car c1;
12. c1.speed = 1;
13. cout << c1.speed << endl;
14. c1.*pSpeed = 2;
15. cout << c1.speed << endl;
16. return 0;
17. }
a) 1
b) 2
c) Both 1 & 2
d) None of the mentioned
View Answer
Answer: c
Explanation: In this program, We are printing the value by direct access and another one by
using pointer to member.
Output:
$ g++ ptm2.cpp
$ a.out
1
2
1. #include <iostream>
2. using namespace std;
3. class bowl
4. {
5. public:
6. int apples;
7. int oranges;
8. };
9. int count_fruit(bowl * begin, bowl * end, int bowl :: *fruit)
10. {
11. int count = 0;
12. for (bowl * iterator = begin; iterator != end; ++ iterator)
13. count += iterator ->* fruit;
14. return count;
15. }
16. int main()
17. {
18. bowl bowls[2] = {{ 1, 2 },{ 3, 5 }};
19. cout << "I have " << count_fruit(bowls, bowls + 2, & bowl ::
apples) << " apples\n";
20. cout << "I have " << count_fruit(bowls, bowls + 2, & bowl ::
oranges) << " oranges\n";
21. return 0;
22. }
a) I have 4 apples
I have 7 oranges
b) I have 3 apples
I have 5 oranges
c) I have 1 apples
I have 5 oranges
d) None of the mentioned
View Answer
Answer: a
Explanation: In this program, We are passing the value to the class and adding the values and
printing it in the main.
Output:
$ g++ ptm3.cpp
$ a.out
I have 4 apples
I have 7 oranges
1. #include <iostream>
2. using namespace std;
3. class Foo
4. {
5. public:
6. Foo(int i = 0){ _i = i;}
7. void f()
8. {
9. cout << "Executed"<<endl;
10. }
11. private:
12. int _i;
13. };
14. int main()
15. {
16. Foo *p = 0;
17. p -> f();
18. }
a) Executed
b) Error
c) Runtime error
d) None of the mentioned
View Answer
Answer: a
Explanation: In this program, We passes the value to the class and printing it.
Output:
$ g++ ptm4.cpp
$ a.out
Executed
9. Which is the best design choice for using pointer to member function?
a) Interface
b) Class
c) Structure
d) None of the mentioned
View Answer
Answer: a
Explanation: None.
Answer: a
Explanation: The binary operator .* combines its first operand, which must be an object of class
type, with its second operand, which must be a pointer-to-member type.
Here is a listing of C++ language programming interview questions on “Free Store” along with answers,
explanations and/or solutions:
1. Which is used to allocate and deallocate storage for objects during the execution?
a) Stack
b) Heap
c) Freestore
d) None of the mentioned
View Answer
Answer: c
Explanation: Free store is a pool of memory available for you to allocate and deallocate storage for
objects during the execution of your program.
2. Which operators are used in the free store?
a) new
b) delete
c) both new & delete
d) none of the mentioned
View Answer
Answer: c
Explanation: new and delete operators is used to allocate and deallocate the memory for the program.
Answer: a
Explanation: None.
#include <new>
#include <iostream>
struct A
virtual ~A() { };
};
struct B : A
{
cout << "B :: operator delete" << endl;
};
int main()
A* ap = new B;
delete ap;
a) A::operator delete
b) B::operator delete
c) Both A::operator delete & B::operator delete
d) None of the mentioned
View Answer
Answer: b
Explanation: In this program, We are passing the value to the B, So we are printing B::operator delete.
Output:
$ g++ free.cpp
$ a.out
B::operator delete
#include <iostream>
struct A
virtual ~A()
delete [] p;
}
};
struct B : A
delete [] p;
};
int main()
A* bp = new B[3];
delete[] bp;
};
a) ~A()
b) A :: operator delete[].
c) B :: operator delete[].
d) Warning
View Answer
Answer: d
Explanation: In this program, the behavior of the statement delete[] bp is undefined.
$ g++ a.cpp
a.cpp: In static member function ‘static void A::operator delete [](void*, size_t)’:
a.cpp:12: warning: deleting ‘void*’ is undefined
a.cpp: In static member function ‘static void B::operator delete [](void*, size_t)’:
a.cpp:20: warning: deleting ‘void*’ is undefined
$ a.out
~A()
~A()
~A()
A :: operator delete[].
#include <iostream>
class X
public:
void* p = malloc(sz);
if (p == 0)
return p;
free(p);
};
class Y
int filler[100];
public:
cout << "Freeing " << sz << " bytes" << endl;
free(p);
};
};
int main()
X* ptr = new X;
delete ptr;
Y* yptr = new Y;
delete yptr;
a) X::operator delete(void*)
b) Freeing 400 bytes
c) Depends on the compiler
d) Both X::operator delete(void*) & Depends on the compiler
View Answer
Answer: d
Explanation: The memory value allocated for the program depends on compiler ony.
$ g++ free2.cpp
$ a.out
X :: operator delete(void*)
Freeing 400 bytes
#include <new>
#include<cstdlib>
#include <iostream>
class X;
struct Node
X* data;
bool filled;
Node() : filled(false) { }
};
class X
{
static Node buffer[];
public:
int number;
void* p = malloc(sz);
if (sz == 0)
return p;
cout << "X :: operator new(size_t, " << location << ")" << endl;
void* p = 0;
else
p = malloc(sizeof(X));
if (p == 0)
buffer[location].filled = true;
buffer[location].data = (X*) p;
return p;
}
};
Node X::buffer[size];
int main()
try
X* ptr1 = new X;
X* ptr2 = new(0) X;
X* ptr3 = new(1) X;
X* ptr4 = new(2) X;
ptr2->number = 10000;
ptr3->number = 10001;
ptr4->number = 10002;
X :: printbuffer();
X* ptr5 = new(0) X;
}
a) X::operator new(size_t)
b) Error
c) Runtime error
d) None of the mentioned
View Answer
Answer: c
Explanation: In this program, We are giving a location to two variables in the program, So it is arising an
exception.
Output:
$ g++ free3.cpp
$ a.out
X::operator new(size_t)
X::operator new(size_t, 0)
X::operator new(size_t, 1)
X::operator new(size_t, 2)
10000
10001
10002
X::operator new(size_t, 0)
Error: buffer location occupied
#include <iostream>
#include <new>
#include <cstdlib>
int *pa;
void get_memory()
delete [] pa;
allocate = false;
}
void eat_memory(int size)
if (allocate)
eat_memory(size);
else
int main()
set_new_handler(get_memory);
pa = new int[bsize];
eat_memory(bsize);
return 0;
Answer: c
Explanation: In this program, The memory will go beyond the limit, So there will be exhaustion in
memory.
Output:
$ g++ free4.cpp
$ a.out
free store addr = 0x80a8008
Segmentation fault
Answer: a
Explanation: The operand of delete must be a pointer returned by new.
Answer: c
Explanation: None.
This section on C++ interview questions and answers focuses on “Standard Library Design”.
One shall practice these interview questions to improve their C++ programming skills needed for
various interviews (campus interviews, walkin interviews, company interviews), placements,
entrance exams and other competitive exams. These questions can be attempted by anyone
focusing on learning C++ programming language. They can be a beginner, fresher, engineering
graduate or an experienced IT professional. Our C++ interview questions come with detailed
explanation of the answers which helps in better understanding of C++ concepts.
Here is a listing of C++ interview questions on “Standard Library Design” along with answers,
explanations and/or solutions:
Answer: c
Explanation: The standard header files for string is string and regex. So the wrong one presented
here is ios.
Answer: d
Explanation: None.
Answer: a
Explanation: vector in the container library contains sequence container that manipulates and
encapsulates dynamic size arrays.
1. #include <iostream>
2. #include <vector>
3. using namespace std;
4. int main()
5. {
6. vector<int> v;
7. v.assign( 10, 42 );
8. for (int i = 0; i < v.size(); i++)
9. {
10. cout << v[i] << " ";
11. }
12. }
a) 42
b) 42 42
c) 424
d) 42 for 10 times
View Answer
Answer: d
Explanation: In this program, We used the vector to print the 42 for 10 times.
Output:
$ g++ std.cpp
$ a.out
42 42 42 42 42 42 42 42 42 42
a) ab
b) abc
c) a
d) error
View Answer
Answer: b
Explanation: In this program, We used the queue to process the given input.
Output:
$ g++ std1.cpp
$ a.out
abc
1. #include <list>
2. #include <string>
3. #include <iostream>
4. using namespace std ;
5. typedef list<string> LISTSTR;
6. int main()
7. {
8. LISTSTR :: iterator i;
9. LISTSTR test;
10. test.insert(test.end(), "one");
11. test.insert(test.end(), "two");
12. LISTSTR test2(test);
13. LISTSTR test3(3, "three");
14. LISTSTR test4(++test3.begin(),
15. test3.end());
16. cout << "test:";
17. for (i = test.begin(); i != test.end(); ++i)
18. cout << " " << *i << endl;
19. cout << "test:";
20. for (i = test2.begin(); i != test2.end(); ++i)
21. cout << " " << *i << endl;
22. cout << "test:";
23. for (i = test3.begin(); i != test3.end(); ++i)
24. cout << " " << *i << endl;
25. cout << "test:";
26. for (i = test4.begin(); i != test4.end(); ++i)
27. cout << " " << *i << endl;
28. }
a) test
b) test one
c) test two
d) none of the mentioned
View Answer
Answer: d
Explanation: In this program, We used the list to manipulate the given value.
Output:
$ g++ std3.cpp
$ a.out
test: one
two
test: one
two
test: three
three
three
test: three
three
Answer: d
Explanation: None.
Answer: a
Explanation: count is used to return the new number of buckets.
Answer: a
Explanation: None.
Here is a listing of advanced C++ programming questions on “Container Design” along with answers,
explanations and/or solutions:
Answer: b
Explanation: None.
Answer: d
Explanation: The basic interface of an allocator class consists of a set of typedefs, a pair of allocation
functions, allocate() and deallocate() and a pair of construction/destruction members, construct() and
destroy().
#include <iostream>
#include <vector>
class Component
public:
};
int value;
public:
Leaf(int val)
value = val;
void traverse()
};
public:
children.push_back(ele);
void traverse()
children[i]->traverse();
};
int main()
Composite containers[4];
containers[0].add(&(containers[k]));
containers[p].traverse();
a) 345
b) 678
c) 901
d) None of the mentioned
View Answer
Answer: d
Explanation: In this program, We are choosing and printing the numbers based on the certain limit and
this is a composite design pattern.
Output:
$ g++ cont.cpp
$ a.out
0 1 2 3 4 5 6 7 8 9 10 11
345
678
9 10 11
Answer: d
Explanation: None.
#include <iostream>
#include <vector>
#include <iterator>
#include <stddef.h>
template<class myType>
class SimpleContainer
public:
, xSize(xDim)
, ySize(yDim)
int getSize()
return objectData.size();
objectData.swap(inputVector);
}
void printContainer(ostream& stream)
copy(objectData.begin(), objectData.end(),
private:
vector<myType> objectData;
size_t xSize;
size_t ySize;
};
template<class myType>
object.printContainer(stream);
return stream;
void sampleContainerInterfacing();
int main()
sampleContainerInterfacing();
return 0;
void sampleContainerInterfacing()
mySimpleContainer(0, 0) = 5;
a) 2000
b) No Space
c) Error
d) Depends on the compiler
View Answer
Answer: d
Explanation: In this program, We formed a simple container and got the size of it and printing it.
Output:
$ g++ cont1.cpp
$ a.out
200
Answer: a
Explanation: None.
Answer: a
Explanation: The container manages the storage space for its elements and provides member functions
to access them, either directly or through iterators which reference objects with similar properties to
pointers.
Answer: a
Explanation: Every container must define an iterator type. Iterators allow algorithms to iterate over the
container’s contents.
10. Which are the parameters for the content of the buffer?
a) start
b) finish
c) both start & finish
d) none of the mentioned
View Answer
Answer: c
Explanation: The contents of the buffer are initialized using the values from the iterator range supplied
to the constructor by the start and finish parameters.
Here is a listing of C++ interview questions on “Vector” along with answers, explanations and/or
solutions:
Answer: b
Explanation: Vectors are sequence containers representing arrays that can change in size.
Answer: a
Explanation: Vectors use contiguous storage locations for their elements, which means that their
elements can also be accessed using offsets on regular pointers to its elements
Answer: c
Explanation: There are three container properties in c++. They are sequence, Dynamic array and
allocator-aware.
#include <iostream>
#include <vector>
int main ()
unsigned int i;
vector<int> first;
return 0;
}
a) 16
b) 16 2
c) 16 2 77
d) 16 2 77 29
View Answer
Answer: d
Explanation: In this program, We got the values and printing it by using the vector and we are
contructing vectors.
Output:
$ g++ vect.cpp
$ a.out
16 2 77 29
#include <iostream>
#include <vector>
int main ()
vector<int> myvector;
myvector.push_back (100);
myvector.push_back (200);
myvector.push_back (300);
while (!myvector.empty())
sum += myvector.back();
myvector.pop_back();
return 0;
}
a) 500
b) 600
c) 700
d) Error
View Answer
Answer: b
Explanation: In this program, We are forming a stack and adding the elements and We are finding the
total number of elements that are in stack.
Output:
$ g++ vect1.cpp
$ a.out
600
#include <iostream>
#include <vector>
int main ()
b = a;
a = vector<int>();
return 0;
a) Size of a 0
Size of b 3
b) Size of a 3
Size of b 5
c) Error
d) None of the mentioned
View Answer
Answer: a
Explanation: In this program, We are finding the size of the vector elements.
Output:
$ g++ vect2.cpp
$ a.out
Size of a 0
Size of b 3
#include <iostream>
#include <vector>
int main ()
vector<int> first;
first.assign (7,100);
vector<int>::iterator it;
it=first.begin()+1;
return 0;
a) 10
b) 9
c) 8
d) 7
View Answer
Answer: d
Explanation: In this program, We are finding the size of the vector elements and resizing it.
Output:
$ g++ vect3.cpp
$ a.out
7
#include <vector>
int main ()
int* p = myvector.data();
*p = 10;
++p;
*p = 20;
p[2] = 100;
return 0;
a) 10 20 0 100 0
b) 10 20 0 100
c) 10 20 0
d) 10 20
View Answer
Answer: a
Explanation: In this program, We are allocating the values to the vector and unallocated values are left
as zero.
Output:
$ g++ vect4.cpp
$ a.out
10 20 0 100 0
Answer: d
Explanation: The number of elements is optional. An empty vector means, A vector that contains zero
elements.
Here is a listing of online C++ test questions on “Sequences” along with answers, explanations and/or
solutions:
Answer: d
Explanation: There are five items in sequence container. They are array, vector, list, forward_list and
dequeue.
3. Which of the following will return the new element at the end of container?
a) front
b) back
c) push_back
d) pop_back
View Answer
Answer: b
Explanation: None.
#include <iostream>
#include <deque>
int main ()
int i = 0;
*rit = ++i;
it != mydeque.end(); ++it)
return 0;
a) 12345
b) 1234
c) 54321
d) 43210
View Answer
Answer: c
Explanation: In this program, We used the operation of rbegin and rend on dequeue and produced the
result.
Output:
$ g++ seq.cpp
$ a.out
54321
#include <iostream>
#include <deque>
int main ()
unsigned int i;
deque<int> a (3,100);
deque<int> b (5,200);
a.swap(b);
return 0;
a) a contains: 200 200 200 200 200b contains: 100 100 100
b) a contains: 100 100 100 100 100b contains: 200 200 200
c) a contains: 200 200 200 200 200b contains: 200 200 200
d) none of the mentioned
View Answer
Answer: a
Explanation: In this program, We swapped the values of both dequeues and printing the dequeues.
Output:
$ g++ seq1.cpp
$ a.out
a contains: 200 200 200 200 200b contains: 100 100 100
#include <iostream>
#include <deque>
int main ()
unsigned int i;
deque<int> mydeque;
mydeque.push_back (100);
mydeque.push_back (200);
mydeque.push_back (300);
mydeque.clear();
mydeque.push_back (110);
mydeque.push_back (220);
return 0;
a) 110
b) 220
c) Both 110 & 220
d) None of the mentioned
View Answer
Answer: c
Explanation: In this program, We cleared the old values presented in the dequeue with the new values.
Output:
$ g++ seq2.cpp
$ a.out
110 220
#include <iostream>
#include <vector>
int main ()
vector<int> myvector;
int * p;
unsigned int i;
p = myvector.get_allocator().allocate(5);
myvector.get_allocator().construct(&p[i], i);
myvector.get_allocator().destroy(&p[i]);
myvector.get_allocator().deallocate(p, 5);
return 0;
a) 1 2 3 4 5
b) 0 1 2 3 4
c) 1 2 3 4
d) 5 4 3 2 1
View Answer
Answer: b
Explanation: In this program, We allocated the values to the vector by using get allocater and then we
are destroying it.
Output:
$ g++ seq3.cpp
$ a.out
01234
#include <iostream>
#include <cmath>
#include <list>
struct is_near
};
int main ()
double mydoubles[] = { 12.15, 2.72, 73.0, 12.77, 3.14, 12.77, 73.35, 72.25, 15.3,
72.25 };
mylist.sort();
mylist.unique();
mylist.unique (same_integral_part);
mylist.unique (is_near());
return 0;
Answer: a
Explanation: In this program, We are eliminating the values by using the unique operation in the list.
Output:
$ g++ seq4.cpp
$ a.out
2.72 12.15 72.25
Answer: a
Explanation: List containers are implemented as doubly-linked lists. Doubly linked lists can store each of
the elements they contain in different and unrelated storage locations.
10. Which of the following does not support any insertion or deletion?
a) Array
b) Vector
c) Dequeue
d) List
View Answer
Answer: a
Explanation: Because array is not dynamic in nature, So they can’t be manipulated.
Here is a listing of C++ language programming interview questions on “Sequence Adapters” along with
answers, explanations and/or solutions:
Answer: a
Explanation: A container adapter provides a restricted interface to a container.In particular, adapters do
not provide iterators; they are intended to be used only through their specialized interfaces.
Answer: c
Explanation: None.
Answer: d
Explanation: These mentioned things are presented in container adapters.
#include <iostream>
#include <queue>
using namespace std;
int main ()
queue<int> myqueue;
myqueue.push(12);
myqueue.push(75);
myqueue.back() -= myqueue.front();
return 0;
a) 12
b) 75
c) 63
d) None of the mentioned
View Answer
Answer: c
Explanation: In this program, We used the queue operation and performed the back operation. Because
of that operation, We got the output as 63.
Output:
$ g++ sca.cpp
$ a.out
63
#include <iostream>
#include <queue>
int main ()
queue<int> myqueue;
myqueue.push(i);
while (!myqueue.empty())
sum += myqueue.front();
myqueue.pop();
return 0;
a) 51
b) 52
c) 54
d) 55
View Answer
Answer: d
Explanation: In this program, We used the push and pop operation of quueue to find out the total of all
the number from 1 to 10.
Output:
$ g++ sca1.cpp
$ a.out
55
#include <iostream>
#include <queue>
int main ()
priority_queue<int> mypq;
mypq.push(30);
mypq.push(100);
mypq.push(25);
mypq.push(40);
while (!mypq.empty())
{
mypq.pop();
return 0;
a) 100 40 30 25
b) 100 40 30
c) 100 40
d) None of the mentioned
View Answer
Answer: a
Explanation: In this program, We used priority_queue and with that we are pushing and popping out the
elements.
Output:
$ g++ sca2.cpp
$ a.out
100 40 30 25
#include <iostream>
#include <stack>
int main ()
stack<int> myints;
return 0;
}
a) 05
b) 15
c) 24
d) 102
View Answer
Answer: a
Explanation: In this program, We declared myints and not initialized in first option, So it’s value is 0 and
on another, We are pushing 5 values, So it’s size is 5.
Output:
$ g++ sca3.cpp
$ a.out
05
#include <iostream>
#include <stack>
int main ()
stack<int> mystack;
mystack.push(10);
mystack.push(20);
mystack.top() -= 5;
return 0;
a) 10
b) 20
c) 13
d) 15
View Answer
Answer: d
Explanation: In this program, We used top option and this will return the reference to the next element.
Output:
$ g++ sca4.cpp
$ a.out
15
Answer: b
Explanation: A stack is a container where elements operate in a LIFO context, where elements are
inserted (pushed) and removed (popped) from the end of the container.
Answer: a
Explanation: None.
This section on C++ aptitude questions and answers focuses on “Associative Containers”. One
shall practice these aptitude questions to improve their C++ programming skills needed for
various interviews (campus interviews, walkin interviews, company interviews), placements,
entrance exams, aptitude tests and other competitive exams. These questions can be attempted by
anyone focusing on learning C++ programming language. They can be a beginner, fresher,
engineering graduate or an experienced IT professional. Our C++ questions come with detailed
explanation of the answers which helps in better understanding of C++ concepts.
Here is a listing of C++ aptitude questions on “Associative Containers” along with answers,
explanations and/or solutions:
2. By using which of the following the elements in the associate container can
be efficiently accessed?
a) Key
b) Position
c) Both Key & Position
d) None of the mentioned
View Answer
Answer: a
Explanation: Associative containers are designed to be especially efficient in accessing its
elements by their key, as opposed to sequence containers which are more efficient in accessing
elements by their position.
Answer: c
Explanation: There are 4 items presented in the associate container. They are set, multiset, map
and multimap.
1. #include <iostream>
2. #include <string>
3. #include <bitset>
4. using namespace std;
5. int main ()
6. {
7. string mystring;
8. bitset<4> mybits;
9. mybits.set();
10. mystring = mybits.to_string<char, char_traits<char>,
11. allocator<char> >();
12. cout << mystring << endl;
13. return 0;
14. }
a) 0000
b) 0001
c) 0011
d) 1111
View Answer
Answer: d
Explanation: In this program, We converted the bitset values to string and printing it.
Output:
$ g++ asc.cpp
$ a.out
1111
1. #include <iostream>
2. #include <algorithm>
3. #include <vector>
4. using namespace std;
5. int main ()
6. {
7. vector<int> first (5, 10);
8. vector<int> second (5, 33);
9. vector<int>::iterator it;
10. swap_ranges(first.begin() + 1, first.end() - 1,
second.begin());
11. cout << " first contains:";
12. for (it = first.begin(); it != first.end(); ++it)
13. cout << " " << *it;
14. cout << "\nsecond contains:";
15. for (it = second.begin(); it != second.end(); ++it)
16. cout << " " << *it;
17. return 0;
18. }
a) first contains: 10 33 33 33 10
second contains: 10 10 10 33 33
b) first contains: 10 33 33 33 10
second contains: 10 10 10 33 10
c) first contains: 10 33 33 33 30
second contains: 10 10 10 33 10
d) none of the mentioned
View Answer
Answer: a
Explanation: In this program, We swapped the values according to their position.
Output:
$ g++ asc1.cpp
$ a.out
first contains: 10 33 33 33 10
second contains: 10 10 10 33 33
a) a => 200
c => 300
b) a => 200
b => 100
c) a => 200
b => 100
c => 300
d) None of the mentioned
View Answer
Answer: c
Explanation: In this program, We used the map template and the we used the begin operation and
then we are printing the elements.
Output:
$ g++ asc2.cpp
$ a.out
a => 200
b => 100
c => 300
1. #include <iostream>
2. #include <set>
3. using namespace std;
4. int main ()
5. {
6. set<int> myset;
7. myset.insert(20);
8. myset.insert(30);
9. myset.insert(10);
10. while (!myset.empty())
11. {
12. cout << ' ' << *myset.begin();
13. myset.erase(myset.begin());
14. }
15. cout << '\n';
16. return 0;
17. }
a) 10
b) 20
c) 30
d) All of the mentioned
View Answer
Answer: d
Explanation: In this program, We used the set template and then we are initializing the values
and then we are erasing it.
Output:
$ g++ asc3.cpp
$ a.out
10 20 30
1. #include <iostream>
2. #include <set>
3. using namespace std;
4. int main ()
5. {
6. multiset<int> mymultiset;
7. for (int i = 0; i < 5; i++) mymultiset.insert(i);
8. multiset<int> :: key_compare mycomp = mymultiset.key_comp();
9. int highest = *mymultiset.rbegin();
10. multiset<int> :: iterator it = mymultiset.begin();
11. do
12. {
13. cout << ' ' << *it;
14. } while (mycomp(*it++, highest));
15. return 0;
16. }
a) 12345
b) 01234
c) 1234
d) 0123
View Answer
Answer: b
Explanation: In this program, We used the set template and then we compared the keys and
printing the result.
Output:
$ g++ asc4.cpp
$ a.out
01234
9. How many instance are allowed by map and set while inserting a element into container?
a) 1
b) 2
c) 3
d) Multiple
View Answer
Answer: a
Explanation: Both map and set only allow one instance of a key or element to be inserted into the
container.
Answer: b
Explanation: None.
Here is a listing of C++ interview questions on “Almost Containers” along with answers, explanations
and/or solutions:
Answer: b
Explanation: The STL is a generic library, meaning that its components are heavily parameterized.
2. To what type of object does the container can be instantiated?
a) int
b) float
c) double
d) any type of object
View Answer
Answer: d
Explanation: None.
Answer: b
Explanation: It is node-based because it allows efficient insertion anywhere on the program.
Answer: c
Explanation: Because they can manipulate the values on anywhere in the program, So it is providing
randoma access.
Answer: a
Explanation: None.
Answer: c
Explanation: Container adaptors are not full container classes, but classes that provide a specific
interface relying on an object of one of the container classes such as deque or list to handle the
elements.
Answer: d
Explanation: A Container “owns” its elements: the lifetime of an element stored in a container cannot
exceed that of the Container itself.
#include <iostream>
#include <map>
int main ()
mymultimap.insert(make_pair('x', 100));
mymultimap.insert(make_pair('y', 200));
mymultimap.insert(make_pair('y', 350));
mymultimap.insert(make_pair('z', 500));
return 0;
a) 1
b) 2
c) 4
d) 3
View Answer
Answer: c
Explanation: In this program, We are counting the number of elements in the map.
Output:
$ g++ alc.cpp
$ a.out
4
#include <iostream>
#include <queue>
int main ()
priority_queue<int> mypq;
mypq.push(10);
mypq.push(20);
mypq.push(15);
return 0;
a) 15
b) 20
c) 10
d) Error
View Answer
Answer: b
Explanation: In this program, We used the queue template and the top method is used to retain the last
but before element.
Output:
$ g++ alc1.cpp
$ a.out
20
10. What is the output of this program?
#include <iostream>
#include <map>
int main ()
mymultimap.insert(make_pair('y', 202));
mymultimap.insert(make_pair('y', 252));
do
cout << (*it).first << " => " << (*it).second << '\n';
return 0;
a) y => 202
b) y => 252
c) y => 202 & y => 252
d) None of the mentioned
View Answer
Answer: a
Explanation: In this program, the method rbegin is used to return the first element in the map.
Output:
$ g++ alc2.cpp
$ a.out
y = > 202
Here is a listing of C++ language interview questions on “Defining a New Container” along with
answers, explanations and/or solutions:
Answer: d
Explanation: All the STL containers define the iterator types for that container, e.g., iterator and
const_iterator, e.g., vector::iterator and the begin/end methods for that container, e.g., begin()
and end().
Answer: b
Explanation: Pointers are legal iterators, so if your internal container is a simple C array, then all
you need to do is return the pointers.
Answer: b
Explanation: None.
4. What are the design requirements for building a container from the sratch?
a) Container interface requirements
b) Allocator interface requirements
c) Iterator requirements
d) All of the mentioned
View Answer
Answer: d
Explanation: These are the design specific requirements for building a container from the
scratch.
5. How many iterators are needed for the defining a new container?
a) 1
b) 2
c) 3
d) 4
View Answer
Answer: c
Explanation: There are three main iterators needed for designing a container. They are const
iterator, Reverse iterator and Iterator traits.
Answer: a
Explanation: None.
Answer: b
Explanation: There are two type of container classes in c++. They are value containers and
reference containers.
8. What is the name of the container which contains group of multiple objects?
a) Heterogeneous container
b) Homogeneous container
c) Both Homogeneous & Heterogeneous container
d) None of the mentioned
View Answer
Answer: a
Explanation: None.
1. #include <iostream>
2. #include <string>
3. #include <algorithm>
4. using namespace std;
5. int main()
6. {
7. string s = "spaces in text";
8. s.erase(remove(s.begin(), s.end(), ' ' ), s.end() ) ;
9. cout << s << endl;
10. }
a) spaces
b) spaces in
c) spaces in text
d) spacesintext
View Answer
Answer: d
Explanation: In this program, We formed a alogorithm to remove spaces in the string.
Output:
$ g++ dan.cpp
$ a.out
spacesintext
1. #include <vector>
2. #include <algorithm>
3. #include <iostream>
4. #include <iterator>
5. using namespace std;
6. int square(int i) { return i * i; }
7. int main()
8. {
9. vector<int> V, V2;
10. V.push_back(0);
11. V.push_back(1);
12. V.push_back(2);
13. transform(V.begin(), V.end(), back_inserter(V2), square);
14. copy(V2.begin(), V2.end(), ostream_iterator<int>(cout, " "));
15. cout << endl;
16. }
a) 0
b) 1
c) 2
d) 0 1 4
View Answer
Answer: d
Explanation: In this program, We formed an algorithm to find the square of the given number.
Output:
$ g++ dan1.cpp
$ a.out
014
Here is a listing of online C++ test questions on “Standard Library Algorithms” along with answers,
explanations and/or solutions:
1. What is the header file used for declaring the standard library algorithms?
a) container
b) algorithm
c) library
d) none of the mentioned
View Answer
Answer: b
Explanation: C++ Standard Library, algorithms are components that perform algorithmic operations on
containers and other sequences. For this operation, We have to use header file.
2. Pick out the correct method in the c++ standard library algorithm.
a) mismatch
b) maximum
c) minimum
d) none of the mentioned
View Answer
Answer: a
Explanation: It is a method in the search opertion in standard library algorithms.
Answer: c
Explanation: It is used to rearranges a range so that it becomes a heap.
#include <iostream>
#include <algorithm>
#include <vector>
int main ()
vector<int> v(10);
return 0;
}
a) 6
b) 7
c) 8
d) 9
View Answer
Answer: c
Explanation: In this program, We used the union function to find the number of elements.
Output:
$ g++ sla.cpp
$ a.out
8
#include <iostream>
#include <algorithm>
#include <vector>
int main ()
return 0;
a) 3 4
b) 3 4 4
c) 3 4 & 3 4 4
d) 3 4 4 0
View Answer
Answer: d
Explanation: In this program, We filled out the vector values by using criteria in the for loop.
Output:
$ g++ sla1.cpp
$ a.out
3440
#include <iostream>
#include <algorithm>
#include <vector>
int main ()
vector<int> myvector;
myvector.push_back(i);
reverse(myvector.begin(), myvector.end());
return 0;
a) 1 2 3 4 5
b) 5 4 3 2 1
c) 0 1 2 3 4
d) None of the mentioned
View Answer
Answer: b
Explanation: In this program, We reversed the vector values by using the reverse function.
Output:
$ g++ sla2.cpp
$ a.out
54321
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main ()
int myints[] = {10, 20, 30, 30, 20, 10, 10, 20};
cout << "10 appears " << mycount << " times.\n";
cout << "20 appears " << mycount << " times.\n";
return 0;
a) 3 3
b) 3 1
c) 8
d) None of the mentioned
View Answer
Answer: a
Explanation: In this program, We are counting the number of 10’s and 20’s in the myints.
Output:
$ g++ sla3.cpp
$ a.out
10 appears 3 times
20 appears 3 times
#include <iostream>
#include <algorithm>
int main ()
int myints[] = {10, 20, 30, 30, 20, 10, 10, 20};
return 0;
Answer: b
Explanation: In this program, We are removing all the 20’s and then we are
printing the remaining.
Output:
$ g++ sla4.cpp
$ a.out
10, 30, 30, 10, 10
Answer: a
Explanation: None.
Answer: d
Explanation: These are the available libraries in C++.
C++ Interview Questions Experienced - Sequences and Containers -
Sanfoundry
by Manish
This section on C++ interview questions and answers focuses on “Sequences and Containers”.
One shall practice these interview questions to improve their C++ programming skills needed for
various interviews (campus interviews, walkin interviews, company interviews), placements,
entrance exams and other competitive exams. These questions can be attempted by anyone
focusing on learning C++ programming language. They can be a beginner, fresher, engineering
graduate or an experienced IT professional. Our C++ interview questions come with detailed
explanation of the answers which helps in better understanding of C++ concepts.
Here is a listing of C++ interview questions on “Sequences and Containers” along with answers,
explanations and/or solutions:
Answer: a
Explanation: In the forward_list, the container provides insertion and removal at anywhere in the
program.
Answer: c
Explanation: None.
3. Subsequent elements are moved in terms of _____ when an element in inserted in vector?
a) Assignment Operator
b) Copy constructor
c) Both assignment operator and copy constructor
d) None of the mentioned
View Answer
Answer: c
Explanation: The vector maintains a certain order of its elements, so that when a new element is
inserted at the beginning or in the middle of the vector, Subsequent elements are moved
backwards in terms of their assignment operator or copy constructor.
1. #include <iostream>
2. #include <vector>
3. using namespace std;
4. int main ()
5. {
6. vector<int> myvector (3);
7. for (unsigned i = 0; i < myvector.size(); i++)
8. myvector.at(i) = i;
9. for (unsigned i = 0; i < myvector.size(); i++)
10. cout << ' ' << myvector.at(i);
11. return 0;
12. }
a) 1 2 3
b) 0 1 2
c) 1 2 3 4
d) None of the mentioned
View Answer
Answer: b
Explanation: In this program, We are pushing the values into the vector from 0 to 3 by using for
loop.
Output:
$ g++ seqc.cpp
$ a.out
012
1. #include <iostream>
2. #include <vector>
3. using namespace std;
4. int main ()
5. {
6. vector<int> myvector;
7. myvector.push_back(78);
8. myvector.push_back(16);
9. myvector.front() += myvector.back();
10. cout << myvector.front() << '\n';
11. return 0;
12. }
a) 78
b) 16
c) 94
d) None of the mentioned
View Answer
Answer: c
Explanation: In this program, We added all the values in the vector by using front and back
operation.
Output:
$ g++ seqc1.cpp
$ a.out
94
1. #include <iostream>
2. #include <list>
3. using namespace std;
4. int main ()
5. {
6. list<int> mylist;
7. list<int> :: iterator it1, it2;
8. for (int i = 1; i < 10; ++i) mylist.push_back(i * 1);
9. it1 = it2 = mylist.begin();
10. advance (it2, 6);
11. ++it1;
12. it1 = mylist.erase (it1);
13. it2 = mylist.erase (it2);
14. ++it1;
15. --it2;
16. mylist.erase (it1, it2);
17. for (it1 = mylist.begin(); it1 != mylist.end(); ++it1)
18. cout << ' ' << *it1;
19. return 0;
20. }
a) 1 3 6
b) 8 9
c) 1 3 6 8 9
d) None of the mentioned
View Answer
Answer: c
Explanation: In this program, We are comparing the values in both lists and erasing it according
to certain condition.
Output:
$ g++ seqc2.cpp
$ a.out
13689
a) 100
b) 200
c) 300
d) None of the mentioned
View Answer
Answer: d
Explanation: Errors will arise because we are clearing all the queue values before printing it.
1. #include <iostream>
2. #include <deque>
3. using namespace std;
4. int main ()
5. {
6. deque<int> mydeque;
7. int sum (0);
8. mydeque.push_back ( 10 );
9. mydeque.push_back ( 20 );
10. mydeque.push_back ( 30 );
11. while (!mydeque.empty())
12. {
13. sum += mydeque.back();
14. mydeque.pop_back();
15. }
16. cout << sum << '\n';
17. return 0;
18. }
a) 10
b) 20
c) 30
d) 60
View Answer
Answer: d
Explanation: In this program, We are adding all the values in the queue.
Output:
$ g++ seqc3.cpp
$ a.out
60
Answer: a
Explanation: Adapters are data types from STL that adapt a container to provide specific
interface.
Answer: a
Explanation: None.
Here is a listing of C++ language programming questions on “Function Objects” along with answers,
explanations and/or solutions:
Answer: b
Explanation: Function objects are objects specifically designed to be used with a syntax similar to that of
functions.
2. What are the two advantage of function objects than the function call?
a) It contains a state
b) It is a type
c) It contains a state & It is a type
d) None of the mentioned
View Answer
Answer: c
Explanation: A function object can contain state. The second is that a function object is a type and
therefore can be used as a template parameter.
a) <function>
b) <functional>
c) <funct>
d) <functionstream>
View Answer
Answer: b
Explanation: None.
#include <iostream>
#include <functional>
#include <algorithm>
int main ()
int results[5];
return 0;
a) 10 20
b) 20 30
c) 10 20 30
d) All of the mentioned
View Answer
Answer: c
Explanation: In this program, We are dividing the first with the second by using function objects.
Output:
$ g++ funo.cpp
$ a.out
10 20 30
#include <iostream>
#include <functional>
#include <algorithm>
int main ()
a) -3
b) 3 4 5
c) 3 -4 5
d) -3 4 5
View Answer
Answer: d
Explanation: In this program, We negated the given value by using the functional objects, So it is
producing this output.
Output:
$ g++ funo1.cpp
$ a.out
-3 4 5
#include <iostream>
#include <functional>
#include <vector>
#include <algorithm>
#include <string>
int main ()
mem_fun(&string :: length));
return 0;
}
a) 335
b) 225
c) 334
d) 224
View Answer
Answer: a
Explanation: In this program, We calculated the number of letters in every string by using function
objects.
Output:
$ g++ funo2.cpp
$ a.out
335
#include <iostream>
#include <functional>
#include <algorithm>
int main ()
int remainders[5];
bind2nd(modulus<int>(), 2) );
return 0;
a) odd
even
b) even
c) odd
odd
d) odd
even
odd
odd
even
View Answer
Answer: d
Explanation: Running the program will show above behaviour because we have given the value in for
loop as 5 instead of 3.
#include <iostream>
#include <functional>
#include <algorithm>
int main ()
int cx;
return 0;
a) 1
b) 2
c) 3
d) 4
View Answer
Answer: c
Explanation: In this program, We are calculating the number of negative elements present in the
program by using function objects.
Output:
$ g++ funo3.cpp
$ a.out
3
Answer: a
Explanation: Function objects are instances of a class with member function operator() defined. This
member function allows the object to be used with the same syntax as a regular function call.
10. How many parameters does a operator() in a function object shoud take?
a) 1
b) 2
c) 3
d) 4
View Answer
Answer: b
Explanation: In the case of binary function objects, this operator() member function will take two
parameters.
Here is a listing of C++ interview questions on “Nonmodifying Sequence Algorithms” along with answers,
explanations and/or solutions:
Answer: c
Explanation: A range is any sequence of objects that can be accessed through iterators or pointers, such
as an array or an instance of some of the STL containers.
2. How many parameters are present in mismatch method in non-sequence modifying algorithm?
a) 1
b) 2
c) 3
d) 3 or 4
View Answer
Answer: d
Explanation: There are two definitions of mismatch with either three or four parameters. They are first1,
last1, first2 and optional predicate.
Answer: a
Explanation: Returns true if pred returns true for all the elements in the range [first,last) or if the range
is empty, and false otherwise.
#include <iostream>
#include <algorithm>
#include <vector>
#include <utility>
return (i == j);
int main ()
{
vector<int> myvector;
++mypair.first; ++mypair.second;
return 0;
a) 40
1024
b) 50
1024
c) 20
1024
d) None of the mentioned
View Answer
Answer: b
Explanation: In this program, We are finding the elements which are mismatching in both the variables.
Output:
$ g++ non.cpp
$ a.out
50
1024
#include <iostream>
#include <algorithm>
#include <vector>
{
return ((i % 2) == 1);
int main ()
vector<int> myvector;
myvector.push_back(10);
myvector.push_back(25);
myvector.push_back(40);
myvector.push_back(55);
myvector.end(), IsOdd);
return 0;
a) 10
b) 25
c) 40
d) 55
View Answer
Answer: b
Explanation: In this program, We used find_if method and returned the first odd value in the vector.
Output:
$ g++ non1.cpp
$ a.out
25
#include <iostream>
#include <algorithm>
#include <vector>
int main ()
{
vector<int> myvector;
myvector.push_back(i);
it != myvector.end(); ++it)
return 0;
a) 1 2 3 4
b) 4 3 2 1
c) 3 4 2 1
d) 4 1 2 3
View Answer
Answer: d
Explanation: In this program, We are rotating the vector values by 3, So it is printing this option.
Output:
$ g++ non2.cpp
$ a.out
4123
#include <iostream>
#include <algorithm>
#include <vector>
return (i==j);
int main ()
int myints[] = {10, 20, 20, 20, 30, 30, 20, 20, 10};
vector<int> myvector (myints, myints + 9);
return 0;
a) 10 20 30 20 10
b) 10 20 30
c) 30 20 10
d) None of the mentioned
View Answer
Answer: a
Explanation: In this program, We are printing only the unique values by comparing every value.
Output:
$ g++ non3.cpp
$ a.out
10 20 30 20 10
#include <iostream>
#include <algorithm>
#include <vector>
int main ()
int myints[] = {10, 20, 30, 30, 20, 10, 10, 20};
return 0;
a) 33
b) 44
c) 22
d) None of the mentioned
View Answer
Answer: a
Explanation: In this program, We are counting the number of 10’s and 20’s in the program.
Output:
$ g++ non4.cpp
$ a.out
33
Answer: a
Explanation: Non-modifying sequence algorithm can be applied to list and vector for example the “find”
function can be applied to list and vector.
Answer: d
Explanation: None
Here is a listing of C++ language interview questions on “Modifying Sequence Algorithms” along with
answers, explanations and/or solutions:
Answer: c
Explanation: Forward iterator pointing to the element within the range and that can be moved to the
first position in the range.
Answer: a
Explanation: It is a group of functions and implemented under algorithm header file.
Answer: c
Explanation: A range is any sequence of objects that can be accessed through iterators or pointers, such
as an array or an instance of some of the STL containers.
#include <iostream>
#include <algorithm>
#include <vector>
int main ()
it != myvector.end(); ++it)
return 0;
a) 5 5 5 5 0
b) 8 8 8 8 0
c) 5 8 5 8 0
d) 5 5 5 5 5
View Answer
Answer: a
Explanation: In this program, We filled up all the vector values by using fill method.
Output:
$ g++ msa.cpp
$ a.out
55550
#include <iostream>
#include <algorithm>
#include <vector>
int main ()
it != myvector.end(); ++it)
return 0;
a) 10
b) 10 40
c) 10 99 40 99
d) None of the mentioned
View Answer
Answer: c
Explanation: In this program, We are swapping the certain values in two vectors by using iter_swap.
Output:
$ g++ msa1.cpp
$ a.out
10 99 40 99
#include <iostream>
#include <algorithm>
#include <vector>
#include <functional>
return ++i;
int main ()
vector<int> a;
vector<int> b;
for (int i = 1; i < 4; i++)
a.push_back (i * 10);
b.resize(a.size());
return 0;
a) 21
b) 41
c) 61
d) All of the mentioned
View Answer
Answer: d
Explanation: In this program, We allocated the values to the vector and then by using transform
function, We increased the values.
Output:
$ g++ msa2.cpp
$ a.out
21 41 61
#include <iostream>
#include <algorithm>
int main ()
return 0;
a) 10 20 30
b) 10 30 30 10 10
c) 10 20 30 30
d) None of the mentioned
View Answer
Answer: b
Explanation: In this program, We removed the values in the vector by using the remove method.
Output:
$ g++ msa3.cpp
$ a.out
10 30 30 10 10
#include <iostream>
#include <algorithm>
#include <vector>
int main ()
int * p;
--p;
return 0;
a) 10
b) 20
c) 30
d) 40
View Answer
Answer: b
Explanation: In this program, We used the find method to find the value before 20.
Output:
$ g++ msa4.cpp
$ a.out
20
Answer: b
Explanation: There are two kinds of operations. They are unary and binary operation.
Answer: d
Explanation: The function uses operator== to compare the pairs of elements.
This section on online C++ test focuses on “Stored Sequences”. One shall practice these test
questions to improve their C++ programming skills needed for various interviews (campus
interviews, walkin interviews, company interviews), placements, entrance exams and other
competitive exams. These questions can be attempted by anyone focusing on learning C++
programming language. They can be a beginner, fresher, engineering graduate or an experienced
IT professional. Our online C++ test questions come with detailed explanation of the answers
which helps in better understanding of C++ concepts.
Here is a listing of online C++ test questions on “Stored Sequences” along with answers,
explanations and/or solutions:
Answer: a
Explanation: A sequence point defines any point in a computer program’s execution at which it
is guaranteed that all side effects of previous evaluations have been performed.
Answer: b
Explanation: Sequence point is a point in time at which the dust has settled and all side effects
which have been seen so far are guaranteed to be complete.
Answer: a
Explanation: None.
Answer: c
Explanation: cin and cout support null-terminated sequences as valid containers for sequences of
characters.
1. #include <iostream>
2. #include <string>
3. using namespace std;
4. int main ()
5. {
6. string mys;
7. char mya[20]= "Hello world";
8. mys = mya;
9. cout << mys << '\n';
10. return 0;
11. }
a) Hello world
b) Hello
c) Error
d) Runtime error
View Answer
Answer: a
Explanation: In this program, We converted the char values into the string.
Output:
$ g++ sts.cpp
$ a.out
Hello world
1. #include <iostream>
2. #include <algorithm>
3. #include <vector>
4. using namespace std;
5. bool IsOdd (int i)
6. {
7. return (i % 2) == 1;
8. }
9. int main ()
10. {
11. vector<int> myvector;
12. for (int i = 1; i < 10; ++i) myvector.push_back(i);
13. vector<int> :: iterator bound;
14. bound = partition (myvector.begin(), myvector.end(), IsOdd);
15. for (vector<int> :: iterator it = myvector.begin(); it !=
bound; ++it)
16. cout << ' ' << *it;
17. return 0;
18. }
a) 1 3 5
b) 1 3 9
c) 1 9 3 7
d) 1 9 3 7 5
View Answer
Answer: d
Explanation: In this program, We are finding the odd values in the sequence.
Output:
$ g++ sts1.cpp
$ a.out
19375
Answer: b
Explanation: None.
Here is a listing of C++ interview questions on “Heaps” along with answers, explanations and/or
solutions:
Answer: b
Explanation: The element with the highest value is always pointed by first.
Answer: d
Explanation: The elements in the heap are compared using operator< (for the first version), or comp (for
the second version).
#include <iostream>
#include <algorithm>
#include <vector>
int main ()
return 0;
a) 5 10
b) 5 10 15 20
c) 5 10 15 20 99
d) None of the mentioned
View Answer
Answer: c
Explanation: In this program, We popped out 30 and pushed 99 and then we are sorting that value, So it
is printing it.
Output:
$ g++ heap.cpp
$ a.out
5 10 15 20 99
#include <iostream>
#include <algorithm>
#include <vector>
int main ()
v.push_back(33);
push_heap (v.begin(),v.end());
sort_heap (v.begin(),v.end());
return 0;
}
a) 1
b) 33
c) 3
d) 44
View Answer
Answer: b
Explanation: In this program, We are pushing a new value into heap and printing it.
Output:
$ g++ heap1.cpp
$ a.out
33
#include <iostream>
#include <algorithm>
#include <vector>
int main ()
make_heap (v.begin(),v.end());
return 0;
a) 10
b) 20
c) 4
d) 8
View Answer
Answer: a
Explanation: In this program, We are printing the maximum value in the heap.
Output:
$ g++ heap2.cpp
$ a.out
10
#include <iostream>
#include <algorithm>
#include <vector>
int main ()
myfunction);
return 0;
a) 5 6 7
b) 5 6 7 9 8
c) 9 8 7 6 5
d) None of the mentioned
View Answer
Answer: b
Explanation: In this program, We are partitioning the value by using the partial_sort method.
Output:
$ g++ heap3.cpp
$ a.out
56798
Answer: d
Explanation: None.
Answer: d
Explanation: STL does provide a heap in the form of a std::priority_queue.
Answer: b
Explanation: There are two types of heaps. They are min and max heap.
Here is a listing of tough C++ programming questions on “Min and Max” along with answers,
explanations and/or solutions:
Answer: c
Explanation: Algorithm header file contain the supporting files needed for the execution of these
functions.
Answer: a
Explanation: The min/max functions are type specific but they will not force everything to be converted
to/from floating point. The functions that will force everything to be converted to/from floating point
are fmin/fmax.
Answer: d
Explanation: The “minmax” function can take the following:
1 parameter: An initializer_list object.
2 parameters: Values to compare.
2 parameters: An initializer_list object.and comparaison function
3 parameters: Values to compare.and comparaison function
#include <iostream>
#include <algorithm>
int main ()
cout << "max('a', 'z') == " << max('a', 'z') << '\n';
return 0;
a) 2z
b) 2a
c) Error
d) None of the mentioned
View Answer
Answer: a
Explanation: In this program, We found the max value in the given value by using max function.
Output:
$ g++ max.cpp
$ a.out
max(1, 2) == 2
max(‘a’, ‘z’) == z
#include <iostream>
#include <algorithm>
return i < j;
int main ()
return 0;
a) 2 9
b) 2 7
c) 3 9
d) 3 5
View Answer
Answer: a
Explanation: In this program, We found out the minimum value and maximum value
of a range.
Output:
$ g++ max1.cpp
$ a.out
2
9
#include <iostream>
#include <algorithm>
#include <vector>
int main ()
int myints[] = {10, 20, 30, 30, 20, 10, 10, 20};
return 0;
a) 3 6
b) 2 5
c) 2 6
d) 2 4
View Answer
Answer: a
Explanation: In this program, We are finding the upper bound and lower bound values by using
lower_bound and upper_bound methods.
Output:
$ g++ max2.cpp
$ a.out
36
#include <iostream>
#include <algorithm>
int main ()
return 0;
a) Error
b) Runtime error
c) 1 m
d) None of the mentioned
View Answer
Answer: c
Explanation: In this program, We are finding the minimum value by using min method.
Output:
$ g++ max3.cpp
$ a.out
1m
#include <iostream>
#include <algorithm>
#include <vector>
int main ()
int myints[] = {10, 20, 30, 30, 20, 10, 10, 20};
cout << " and " << (bounds.second - v.begin()) << '\n';
return 0;
a) 3 and 6
b) 2 and 5
c) 3 and 5
d) 2 and 4
View Answer
Answer: a
Explanation: In this program, We are finding out the equal range in the vector.
Output:
$ g++ max4.cpp
$ a.out
3 and 6
10. Which operator is used to compare the values to find min and max?
a) <
b) >
c) <<
d) >>
View Answer
Answer: a
Explanation: None.
This section on tough C++ programming questions focuses on “Permutations”. One shall
practice these questions to improve their C++ programming skills needed for various interviews
(campus interviews, walkin interviews, company interviews), placements, entrance exams and
other competitive exams. These questions can be attempted by anyone focusing on learning C++
programming language. They can be a beginner, fresher, engineering graduate or an experienced
IT professional. Our C++ programming questions come with detailed explanation of the answers
which helps in better understanding of C++ concepts.
Here is a listing of tough C++ programming questions on “Permutations” along with answers,
explanations and/or solutions:
Answer: b
Explanation: The permutation is used to find all the combination of numbers in the range.
Answer: b
Explanation: If the function can determine the next higher permutation, it rearranges the
elements as such and returns true.
1. #include <string>
2. #include <iostream>
3. using namespace std;
4. void string_permutation( string& orig, string& perm )
5. {
6. if (orig.empty())
7. {
8. cout<<perm<<endl;
9. return;
10. }
11. for (int i = 0; i < orig.size(); ++i)
12. {
13. string orig2 = orig;
14. orig2.erase(i, 1);
15. string perm2 = perm;
16. perm2 += orig.at(i);
17. string_permutation(orig2, perm2);
18. }
19. }
20. int main()
21. {
22. string orig = "ter";
23. string perm;
24. string_permutation(orig, perm);
25. return 0;
26. }
a) ter
b) ert
c) ret
d) returns all the combination of ter
View Answer
Answer: d
Explanation: In the program, We used string permutation to find out all the combination.
Output:
$ g++ perm.cpp
$ a.out
ter
tre
etr
ert
rte
ret
1. #include <iostream>
2. #include <algorithm>
3. using namespace std;
4. int main ()
5. {
6. int myints[] = {1, 2, 3};
7. sort (myints, myints + 3);
8. do
9. {
10. } while ( next_permutation(myints, myints + 3) );
11. cout << myints[0] << ' ' << myints[1] << ' ' << myints[2] <<
'\n';
12. return 0;
13. }
a) 1 2 3
b) 3 2 1
c) 2 1 3
d) 1 3 2
View Answer
Answer: a
Explanation: In this program, We are doing the permutation in the do while loop and then
printing last permuted value.
Output:
$ g++ perm1.cpp
$ a.out
123
1. #include <iostream>
2. using namespace std;
3. int array[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
4. void swap(int x, int y)
5. {
6. int temp = array[x];
7. array[x] = array[y];
8. array[y] = temp;
9. return;
10. }
11. void printArray(int size)
12. {
13. int i;
14. for (i = 0; i < size; i++)
15. cout << array[i] << " ";
16. cout << endl;
17. return;
18. }
19. void permute(int k, int size)
20. {
21. int i;
22. if (k == 0)
23. printArray(size);
24. else
25. {
26. for (i = k - 1;i >= 0;i--)
27. {
28. swap(i, k - 1);
29. permute(k - 1, size);
30. swap(i, k - 1);
31. }
32. }
33. return;
34. }
35. int main()
36. {
37. permute(3, 3);
38. return 0;
39. }
a) 0 1 2
102
b) 0 2 1
201
c) 2 1 0
120
d) All of the mentioned
View Answer
Answer: d
Explanation: In this program, We are finding the permutation without using the permutation
function.
Output:
$ g++ perm2.cpp
$ a.out
012
102
021
201
210
120
1. #include <iostream>
2. #include <vector>
3. #include <algorithm>
4. using namespace std;
5. void Display(const vector<int>& vi)
6. {
7. for (size_t i = 0; i < vi.size(); ++i)
8. cout << vi[i];
9. cout<<endl;
10. }
11. int main()
12. {
13. vector<int> vi;
14. vi.push_back(3);
15. vi.push_back(5);
16. sort(vi.begin(), vi.end());
17. Display(vi);
18. while(next_permutation(vi.begin(), vi.end()))
19. Display(vi);
20. return 0;
21. }
a) 3 5
b) 5 3
c) 5 3
35
d) None of the mentioned
View Answer
Answer: c
Explanation: In this program, We find out the permutation of two numbers by using sort.
Output:
$ g++ perm3.cpp
$ a.out
53
35
1. #include <iostream>
2. #include <vector>
3. #include <algorithm>
4. using namespace std;
5. void show(const vector<int>& vi)
6. {
7. for (size_t i = 0; i < vi.size(); ++i)
8. cout << vi[i];
9. cout << endl;
10. }
11. int main()
12. {
13. vector<int> vi;
14. vi.push_back(3);
15. vi.push_back(5);
16. vi.push_back(5);
17. sort(vi.begin(), vi.end());
18. show(vi);
19. while(next_permutation(vi.begin(), vi.end()))
20. show(vi);
21. return 0;
22. }
a) 355
b) 535
c) 553
d) All of the mentioned
View Answer
Answer: d
Explanation: In this program, We are finding the permutation for the given value.
Output:
$ g++ perm4.cpp
$ a.out
355
535
553
Answer: c
Explanation: To use permutation on a vector we can use the “next_permutation” function defined
in the header.
Here is a listing of C++ interview questions on “C Style Algorithms” along with answers, explanations
and/or solutions:
Answer: d
Explanation: First three type of options are available in header file.
2. What type of algorithm is not available in creating our own STL style algorithms?
a) copy_if()
b) remove_copy_if()
c) sort
d) none of the mentioned
View Answer
Answer: a
Explanation: None.
#include <iostream>
#include <algorithm>
#include <vector>
int main ()
v.pop_back();
return 0;
a) 10
b) 20
c) 30
d) 5
View Answer
Answer: b
Explanation: In this program, We are forming a heap with the vector and then we are popping one
element and finding the maximum element in the heap.
Output:
$ g++ style.cpp
$ a.out
20
#include <iostream>
#include <algorithm>
#include <vector>
int main ()
vector<int> v(10);
v.resize(it-v.begin());
return 0;
a) 5 10 15
b) 20 25 30
c) 40 50
d) All of the mentioned
View Answer
Answer: d
Explanation: In this kind of style algorithm, We are finding the elements in the both the vector by using
set_union function.
Output:
$ g++ style1.cpp
$ a.out
5 10 15 20 25 30 40 50
#include <iostream>
#include <algorithm>
#include <vector>
struct myclass {
} myobject;
int main ()
return 0;
a) 8 9 10
b) 10 8 9
c) 9 8 10
d) None of the mentioned
View Answer
Answer: a
Explanation: In this style algorithm, We have sorted the elements in the vector by using the sort
method.
Output:
$ g++ style2.cpp
$ a.out
8 9 10
#include <iostream>
#include <algorithm>
#include <vector>
int main ()
myfunction);
return 0;
a) 6 7 8 9
b) 9 8 6 7
c) 6 7 9 8
d) None of the mentioned
View Answer
Answer: c
Explanation: In this program, We are partial sorting the vector by using the partial sort method.
Output:
$ g++ style3.cpp
$ a.out
6798
#include <iostream>
#include <algorithm>
#include <vector>
int main ()
vector<int> v(4);
v.begin());
v.resize(it - v.begin());
return 0;
a) 5 10
b) 30 40
c) 50 40
d) 5 10 30 40
View Answer
Answer: d
Explanation: In this style algorithm, We are finding the symmetric difference between the vectors and
printing it.
Output:
$ g++ style4.cpp
$ a.out
5 10 30 40
Answer: b
Explanation: Returns true if the first sorted range contains all the elements in the second sorted range.
Answer: c
Explanation: There are three parameters required for sort_heap. There are first element in heap and last
element in heap and an optional compare.
This section on C++ language interview questions and answers focuses on “Iterators and Sequences”.
One shall practice these interview questions to improve their C++ programming skills needed for various
interviews (campus interviews, walkin interviews, company interviews), placements, entrance exams
and other competitive exams. These questions can be attempted by anyone focusing on learning C++
programming language. They can be a beginner, fresher, engineering graduate or an experienced IT
professional. Our C++ language interview questions come with detailed explanation of the answers
which helps in better understanding of C++ concepts.
Here is a listing of C++ language interview questions on “Iterators and Sequences” along with answers,
explanations and/or solutions:
Answer: b
Explanation: Because of this, It can serve as any category of iterator.
Answer: a
Explanation: Iterator pattern is a design pattern in which an iterator is used to traverse a container and
access the container’s elements.
#include <iostream>
#include <set>
int main()
set<int> tst;
tst.insert(12);
tst.insert(21);
tst.insert(32);
tst.insert(31);
return 0;
a) 12 21 32 31
b) 12 21 31 32
c) 12 21 32
d) 12 21 31
View Answer
Answer: b
Explanation: In this program, We are using const_iterator to sort the data
in the set.
Output:
$ g++ itr.cpp
$ a.out
12 21 31 32
#include <iostream>
#include <vector>
#include<iterator>
int main ()
vector<int> myvector;
myvector.push_back(i);
return 0;
}
a) 5 6 7 8 9
b) 5 6 8 9 10
c) 6 7 8 9 10
d) None of the mentioned
View Answer
Answer: b
Explanation: In this program, We are erasing the values in the vector based on the given condition.
Output:
$ g++ itr1.cpp
$ a.out
5 6 8 9 10
#include <iostream>
#include <iterator>
#include <list>
int main ()
list<int> mylist;
mylist.push_back (i * 10);
return 0;
a) 30
b) 40
c) 50
d) 60
View Answer
Answer: c
Explanation: In this program, We are printing the sixth element in the list.
Output:
$ g++ itr2.cpp
$ a.out
50
#include <iostream>
#include <iterator>
#include <list>
int main ()
firstlist.push_back(i);
secondlist.push_back(i * 10);
it = firstlist.begin();
return 0;
a) 10 20 1 2
b) 10 20
c) 1 2
d) 1 10
View Answer
Answer: a
Explanation: In this iterator, We are copying the first list into second and printing it.
Output:
$ g++ itr3.cpp
$ a.out
10 20 1 2
#include <iostream>
#include <iterator>
#include <list>
int main ()
list<int> mylist;
mylist.push_back (i * 20);
return 0;
a) 20
b) 100
c) 5
d) None of the mentioned
View Answer
Answer: c
Explanation: In this program, We are printing the number of elements in the list by using distance
method.
Output:
$ g++ itr4.cpp
$ a.out
5
9. In which type of semantics does c++ implements iterator?
a) Memory
b) Size
c) Pointer
d) None of the mentioned
View Answer
Answer: c
Explanation: None.
Answer: a
Explanation: ‘++’ operator is used to represent the next element in the iterator.
This section on C++ questions and puzzles focuses on “Checked Iterators”. One shall practice
these questions and puzzles to improve their C++ programming skills needed for various
interviews (campus interviews, walkin interviews, company interviews), placements, entrance
exams and other competitive exams. These programming puzzles can be attempted by anyone
focusing on learning C++ programming language. They can be a beginner, fresher, engineering
graduate or an experienced IT professional. Our C++ questions come with detailed explanation
of the answers which helps in better understanding of C++ concepts.
Here is a listing of C++ questions and puzzles on “Checked Iterators” along with answers,
explanations and/or solutions:
Answer: b
Explanation: Checked iterators ensure that you do not overwrite the bounds of your container.
2. What will happen if the iterator is unchecked?
a) Arising of compiler warnings
b) Unchecked behavior on program
c) Nothing will execute
d) Arising of compiler warnings & Unchecked behavior on program
View Answer
Answer: d
Explanation: We will get unchecked behavior on calls to an unchecked function and Calls to the
standard function will result in compiler warnings.
Answer: b
Explanation: There are two adaptors that support checked iterators. They are
checked_array_iterator class, Checked_iterator class.
1. #include <vector>
2. #include <iostream>
3. #include <typeinfo>
4. #include <stdexcept>
5. using namespace std;
6. int main()
7. {
8. vector<int> vec;
9. vec.push_back(10);
10. int i = vec[100];
11. try {
12. i = vec[0];
13. cout << i << endl;
14. }
15. catch (exception &e)
16. {
17. cout << "Caught: " << e.what( ) << endl;
18. cout << "Type: " << typeid( e ).name( ) << endl;
19. }
20. catch (...)
21. {
22. cout << "Unknown exception: " << endl;
23. }
24. return 0;
25. }
a) 10
b) 100
c) Exception
d) Error
View Answer
Answer: a
Explanation: In this program, We are pushing the 10th element and printing it.
Output:
$ g++ chei.cpp
$ a.out
10
1. #include <iostream>
2. #include <map>
3. using namespace std;
4. int main ()
5. {
6. try {
7. map<char, int> mymap;
8. map<char, int> :: iterator it;
9. mymap['a'] = 50;
10. mymap['b'] = 100;
11. mymap['c'] = 150;
12. mymap['d'] = 200;
13. it = mymap.find('b');
14. mymap.erase (it);
15. mymap.erase (mymap.find('d'));
16. cout << mymap.find('a') -> second << '\n';
17. }
18. catch (...)
19. {
20. cout << "Unknown exception: " << endl;
21. }
22. return 0;
23. }
a) 50
b) 100
c) 150
d) Exception
View Answer
Answer: a
Explanation: In this program ,We are finding the element a and printing it.
Output:
$ g++ chei1.cpp
$ a.out
50
6. What is the output of this program?
1. #include <iostream>
2. #include <iterator>
3. using namespace std;
4. int main ()
5. {
6. try {
7. double value1, value2;
8. istream_iterator<double> eos;
9. istream_iterator<double> iit (cin);
10. if (iit != eos)
11. value1 = *iit;
12. iit++;
13. if (iit != eos)
14. value2 = *iit;
15. cout << (value1 * value2) << endl;
16. }
17. catch (...) {
18. cout << "Unknown exception: " << endl;
19. }
20. return 0;
21. }
a) 10
b) 45
c) It will print the multiplied value of the input
d) Exception
View Answer
Answer: c
Explanation: In this program, We got the input by using istream iterator and we are manipulating
in.
Output:
$ g++ chei2.cpp
$ a.out
3
4
12
1. #include <iostream>
2. #include <iterator>
3. #include <vector>
4. using namespace std;
5. int main ()
6. {
7. vector<int> myvector;
8. for (int i = 1; i < 4; ++i)
9. myvector.push_back(i*10);
10. ostream_iterator<int> out_it (cout,", ");
11. copy ( myvector.begin(), myvector.end(), out_it );
12. return 0;
13. }
a) 10, 20, 30
b) 10, 20
c) 10, 20, 30,
d) None of the mentioned
View Answer
Answer: c
Explanation: In this program, We are producing the values by vector and printing it by using
ostream iterator.
Output:
$ g++ chei3.cpp
$ a.out
10, 20, 30,
1. #include <iostream>
2. #include <iterator>
3. #include <vector>
4. using namespace std;
5. int main ()
6. {
7. vector<int> myvector;
8. for (int i = 0; i < 10; i++)
9. myvector.push_back(i);
10. typedef vector<int> :: iterator iter_int;
11. reverse_iterator<iter_int> rev_iterator;
12. rev_iterator = myvector.rend() - 4;
13. cout << *rev_iterator << endl;
14. return 0;
15. }
a) 2
b) 3
c) 4
d) 5
View Answer
Answer: b
Explanation: In this program, We are using the referencing operator and it can print the value
currently pointing it.
Output:
$ g++ chei4.cpp
$ a.out
3
9. What does the checked iterator allow you to find?
a) Warnings
b) Compile time error
c) Run time error
d) None of the mentioned
View Answer
Answer: c
Explanation: None.
Answer: d
Explanation: Checked iterators can easily detect the errors in Uninitialized iterators as well as
Range of access.
Here is a listing of C++ Programming quiz on “Allocators” along with answers, explanations and/or
solutions:
Answer: d
Explanation: Allocators handle all the request for allocation and deallocation of memory for the
container.
2. Where are allocators implemented?
a) Template library
b) Standard library
c) C++ code library
d) None of the mentioned
View Answer
Answer: b
Explanation: Allocators are implemented in C++ standard library but it is used for C++ template library.
Answer: c
Explanation: The default allocator uses operator new to allocate memory.
#include <iostream>
#include <memory>
#include <algorithm>
int main ()
if (result.second > 0)
return_temporary_buffer (result.first);
}
return 0;
a) 1 5 5 4
b) 5 5 4 1
c) 1 4 5 5
d) 1 4 5 2
View Answer
Answer: c
Explanation: In this program, We are sorting the array by using the allocator.
Output:
$ g++ all.cpp
$ a.out
1455
#include <iostream>
#include <memory>
#include <string>
int main ()
if (result.second>0)
return_temporary_buffer(result.first);
return 0;
}
a) steve
b) jobs
c) jobs steve
d) steve jobs
View Answer
Answer: d
Explanation: In this program, We are storing the string and retrieving the string by using
get_temporary_method.
Output:
$ g++ all1.cpp
$ a.out
steve jobs
#include <iostream>
#include <memory>
#include <string>
int main ()
result = get_temporary_buffer<string>(3);
if (result.second > 0)
"Hai" );
return_temporary_buffer(result.first);
return 0;
}
a) Hai
b) HaiHai
c) HaiHaiHai
d) None of the mentioned
View Answer
Answer: c
Explanation: In this program, We storing the string in the string buffer and then we are printing it.
Output:
$ g++ all2.cpp
$ a.out
HaiHaiHai
Answer: b
Explanation: None.
Answer: b
Explanation: Because all the memory allocation and deallocation libraries are declared in .
Answer: c
Explanation: None
Answer: a
Explanation: It is a type of syntax for declaring the allocater.
Here is a listing of C++ questions and puzzles on “String Characters” along with answers, explanations
and/or solutions:
Answer: b
Explanation: The string class is an instantiation of the basic_string class template.
Answer: b
Explanation: A string of characters is stored in successive elements of a character array are terminated
by the NULL character.
3. How does the strings are stored in the memory?
a) Contiguous
b) Non-contiguous
c) Null
d) All of the mentioned
View Answer
Answer: a
Explanation: The characters of a string are stored contiguously in the memory.
#include <iostream>
#include <string>
int main ()
string str;
str.append(str2);
str.append(str3, 6, 3);
str.append(str3.begin() + 6, str3.end());
str.append<int>(5, 0x2E);
return 0;
a) Steve jobs
b) He founded apple
c) Steve
d) None of the mentioned
View Answer
Answer: d
Explanation: In this program, We are characters to the string, So the output will as follows.
Output:
$ g++ str.cpp
$ a.out
Steve jobsndended apple…..
#include <iostream>
#include <string>
int main ()
return 0;
a) Test
b) string
c) Test string
d) Error
View Answer
Answer: d
Explanation: In the for loop, We are not allowed to give a numeric value in string, So it is arising an error.
#include <iostream>
#include <string>
int main ()
name += family;
name += '\n';
return 0;
a) Steve Jobs
b) Apple
c) Jobs Apple Steve
d) None of the mentioned
View Answer
Answer: c
Explanation: In this program, We are adding the characters at the end of the current value.
Output:
$ g++ str1.cpp
$ a.out
Jobs Apple Steve
#include <iostream>
#include <string>
int main ()
cout << str2 << ' ' << str3 << '\n';
return 0;
#include <iostream>
#include <string>
int main ()
return 0;
a) 8
b) 10
c) 12
d) 9
View Answer
Answer: b
Explanation: In this program, We are finding the length of the string.
Output:
$ g++ str3.cpp
$ a.out
10
Answer: c
Explanation: None.
10. What will happen if a string is empty?
a) It can’t be created
b) Raises an error
c) It can be used
d) None of the mentioned
View Answer
Answer: c
Explanation: An empty string is a character array with the NULL character in the zeroth index position.
Here is a listing of C++ interview questions on “Basic String” along with answers, explanations and/or
solutions:
Answer: c
Explanation: To use the string class, We have to use #include header file.
2. How many maximum number of parameters does a string constructor can take?
a) 1
b) 2
c) 3
d) 4
View Answer
Answer: c
Explanation: string( other_string, position, count ). It is a type of constructor for the string.
Answer: a
Explanation: Because bool empty is a constant member function, So it can’t be modified.
#include <iostream>
#include <string>
int main ()
unsigned sz = str.size();
str.resize (14);
return 0;
a) I like to code in c
b) I like to code
c) I like to code in c++
d) None of the mentioned
View Answer
Answer: b
Explanation: In this program, We are resizing the string by adding + and then we are resizing it to 14.
Output:
$ g++ basicst.cpp
$ a.out
I like to code
#include <iostream>
#include <string>
int main ()
return 0;
a) 9
b) 10
c) 11
d) 12
View Answer
Answer: b
Explanation: In this program, We are finding the capacity that the str can hold.
Output:
$ g++ basicst1.cpp
$ a.out
10
#include <iostream>
#include <string>
int main ()
return 0;
}
a) apple
b) 12
c) 23
d) Steve jobs founded the
View Answer
Answer: c
Explanation: In this program, We are finding a string by using the find method.
Output:
$ g++ basicst2.cpp
$ a.out
23
#include <iostream>
#include <string>
int main ()
str[found] = '*';
return 0;
a) Steve
b) jobs
c) St*v* j*bs
d) St*v*
View Answer
Answer: c
Explanation: In this program, We are replacing the vowels with a asterisk by using find_first_of method.
Output:
$ g++ basicst3.cpp
$ a.out
St*v* j*bs
#include <iostream>
#include <cstring>
#include <string>
int main ()
while (p != 0)
p = strtok(NULL," ");
delete[] cstr;
return 0;
a) Steve jo
b) Steve jobs
c) Steve
jobs
d) None of the mentioned
View Answer
Answer: c
Explanation: In this program, We are breaking up the strings into the form of tokens.
Output:
$ g++ basicst4.cpp
$ a.out
Steve
jobs
9. What is the difference between unsigned int length() and unsigned int size()?
a) Returns a different value
b) They are same
c) Returns a different value but they are same
d) None of the mentioned
View Answer
Answer: b
Explanation: Both of them will return the length of strings in same notations.
Answer: c
Explanation: There can be one or two parameters in resize method. They are string length and an
optional new character to be inserted.
Here is a listing of C++ quiz on “C Standard Library” along with answers, explanations and/or solutions:
Answer: b
Explanation: Every element of the c library is defined within the std namespace.
2. Which of the following have their changes in their declaration related to constness of parameter?
a) strchr
b) string
c) memory
d) none of the mentioned
View Answer
Answer: a
Explanation: These are the items which will have their change in declaration related to constness of
parameter. They are strchr, strpbrk, strrchr, strstr, memchr.
Answer: d
Explanation: The floating point number composed of four elements. They are sign, Base, Significand and
Exponent.
#include <stdio.h>
#include <stdlib.h>
int main ()
char* p;
a) 12
b) 12.37
c) 13
d) None of the mentioned
View Answer
Answer: b
Explanation: In this program, We are calculating the double value by using the floating point number
and we are using the function strtod.
Output:
$ g++ cinc.cpp
$ a.out
12.37
#include <stdio.h>
#include <stdlib.h>
int main ()
int * p;
if (p != NULL)
printf ("%d\n",*p);
return 0;
}
a) 10
b) 20
c) 40
d) 30
View Answer
Answer: c
Explanation: In this program, We are searching for the element and then we are printing it.
Output:
$ g++ cinc1.cpp
$ a.out
40
#include <stdio.h>
#include <stdlib.h>
int main ()
int n, m;
n = abs(23);
m = abs(-11);
return 0;
a) 23-11
b) 1123
c) 2311
d) None of the mentioned
View Answer
Answer: c
Explanation: In this program, We are finding the absolute value of the n.
Output:
$ g++ cinc2.cpp
$ a.out
2311
7. What is the output of this program?
#include <stdio.h>
#include <math.h>
int main ()
return 0;
a) 3.1416
b) -3.1416
c) -3.141600
d) 3.141600
View Answer
Answer: d
Explanation: In this program, We are finding the absolute value of a floating point value.
Output:
$ g++ cinc3.cpp
$ a.out
3.141600
#include <stdio.h>
#include <stdlib.h>
int main ()
div_t divresult;
return 0;
a) 7
b) 3
c) 4
d) None of the mentioned
View Answer
Answer: b
Explanation: In this program, We are finding the remainder of a number by using div function.
Output:
$ g++ cinc4.cpp
$ a.out
3
Answer: c
Explanation: None.
10. Pick out the correct syntax of the header file that can be used with C++.
a) #include <float>
b) #include <float.h>
c) Both #include <float> & #include <float.h>
d) None of the mentioned
View Answer
Answer: b
Explanation: The C header file that is ending with h can only be used in C++.
Here is a listing of C++ questions and puzzles on “Output Stream” along with answers, explanations
and/or solutions:
1. How many groups of output of operation are there in c++?
a) 1
b) 2
c) 3
d) 4
View Answer
Answer: b
Explanation: There are two groups of output operation in c++. They are formatted output and
unformatted output.
2. Pick out the correct objects about the instantiation of output stream.
a) cout
b) cerr
c) clog
d) all of the mentioned
View Answer
Answer: d
Explanation: cout, cerr and clog are the standard objects for the instantiation of output stream class.
Answer: a
Explanation: ofstream is a stream class to write on files.
#include <iostream>
int main ()
char ch = 'A';
cout.width (5);
cout << right;
return 0;
a) Steve jobs
b) A
c) 65
d) 65
View Answer
Answer: d
Explanation: In this program, We are printing the five spaces and then we are printing the value of 65.
Output:
$ g++ ous
.cpp
$ a.out
65
#include <iostream>
int main ()
int n;
n = 43;
return 0;
a) 2c
b) 2b
c) 20
d) 50
View Answer
Answer: b
Explanation: In this program, We are printing the hexadecimal value of the given decimal number by
using hex function.
Output:
$ g++ ous1.cpp
$ a.out
2b
#include <fstream>
int main ()
long pos;
ofstream outfile;
outfile.open ("test.txt");
pos = outfile.tellp();
outfile.close();
return 0;
a) This is an apple
b) apple
c) sample
d) This is a sample
View Answer
Answer: d
Explanation: In this program, We are changing the ap to sam by using the pos function.
Output:
$ g++ ous2.cpp
$ a.out
This is a sample
#include <iostream>
using namespace std;
int main ()
int n;
n = -77;
cout.width(4);
return 0;
a) 77
b) -77
c) – 77
d) None of the mentioned
View Answer
Answer: c
Explanation: In this program, We are using the internal function and moving the 77 to one position.
Output:
$ g++ ous3.cpp
$ a.out
– 77
#include <iostream>
#include <locale>
int main()
locale mylocale("");
cout.imbue( mylocale );
return 0;
}
a) 3.14
b) 3.14159
c) Error
d) None of the mentioned
View Answer
Answer: b
Explanation: In this program, We are using the locale and then assigning the type to the value.
Output:
$ g++ ous4.cpp
$ a.out
3.14159
Answer: c
Explanation: There are three output stream classes in c++. They are ostream, ofstream and ostrstream.
Answer: b
Explanation: If you construct an object of class ostream, you must specify a streambuf object to the
constructor.
Answer: b
Explanation: There are two groups of output operation in c++. They are formatted output and
unformatted output.
2. Pick out the correct objects about the instantiation of output stream.
a) cout
b) cerr
c) clog
d) all of the mentioned
View Answer
Answer: d
Explanation: cout, cerr and clog are the standard objects for the instantiation of output stream class.
Answer: a
Explanation: ofstream is a stream class to write on files.
#include <iostream>
int main ()
cout.width (5);
return 0;
a) Steve jobs
b) A
c) 65
d) 65
View Answer
Answer: d
Explanation: In this program, We are printing the five spaces and then we are printing the value of 65.
Output:
$ g++ ous
.cpp
$ a.out
65
#include <iostream>
int main ()
int n;
n = 43;
return 0;
a) 2c
b) 2b
c) 20
d) 50
View Answer
Answer: b
Explanation: In this program, We are printing the hexadecimal value of the given decimal number by
using hex function.
Output:
$ g++ ous1.cpp
$ a.out
2b
#include <fstream>
int main ()
long pos;
ofstream outfile;
outfile.open ("test.txt");
pos = outfile.tellp();
outfile.close();
return 0;
a) This is an apple
b) apple
c) sample
d) This is a sample
View Answer
Answer: d
Explanation: In this program, We are changing the ap to sam by using the pos function.
Output:
$ g++ ous2.cpp
$ a.out
This is a sample
7. What is the output of this program?
#include <iostream>
int main ()
int n;
n = -77;
cout.width(4);
return 0;
a) 77
b) -77
c) – 77
d) None of the mentioned
View Answer
Answer: c
Explanation: In this program, We are using the internal function and moving the 77 to one position.
Output:
$ g++ ous3.cpp
$ a.out
– 77
#include <iostream>
#include <locale>
int main()
locale mylocale("");
cout.imbue( mylocale );
return 0;
}
a) 3.14
b) 3.14159
c) Error
d) None of the mentioned
View Answer
Answer: b
Explanation: In this program, We are using the locale and then assigning the type to the value.
Output:
$ g++ ous4.cpp
$ a.out
3.14159
Answer: c
Explanation: There are three output stream classes in c++. They are ostream, ofstream and ostrstream.
Answer: b
Explanation: If you construct an object of class ostream, you must specify a streambuf object to the
constructor.
Answer: b
Explanation: The operator of extraction is >> and it is used on the standard input stream.
Answer: a
Explanation: cin will stop its extraction when it encounters a blank space.
Answer: b
Explanation: cin is mainly used to get the input during the runtime.
#include <iostream>
int main ()
int i;
cin >> i + 4;
return 0;
a) 73
b) your value + 4
c) Error
d) None of the mentioned
View Answer
Answer: c
Explanation: We are not allowed to do addition operation on cin.
#include <iostream>
#include <string>
#include <sstream>
int main ()
string mystr;
float price = 0;
int quantity = 0;
cout << "Total price: " << price * quantity << endl;
return 0;
a) 50
b) Depends on value you enter
c) Error
d) None of the mentioned
View Answer
Answer: b
Explanation: In this program, We are getting the input on runtime and manipulating the value.
Output:
$ g++ inp.cpp
$ a.out
Enter price: 3
Enter quantity: 4
Total price: 12
#include <iostream>
#include <ios>
#include <istream>
#include <limits>
int main()
cin.get();
cin.clear();
ignore_line ( cin );
a) First input
b) Clearing cin
c) Error
d) None of the mentioned
View Answer
Answer: d
Explanation: In this program, We are getting the input and clearing all the values.
Output:
$ g++ inp1.cpp
$ a.out
First input: 4
Clearing cin.
All done.
#include <iostream>
int main( )
char line[100];
return 0;
a) 100
b) t
c) It will print what we enter till character t is encountered in the input data
d) None of the mentioned
View Answer
Answer: c
Explanation: The program will store all strings entered and will print them only when the character ‘t’ is
encountered.
Answer: c
Explanation: There are two or three parameters in getline() function. They are a pointer to an array of
characters and maximum number of characters and an optional delimiter.
Answer: b
Explanation: If a user wants to input a sentence with blankspaces, then he may use the function getline.
Answer: a
Explanation: None.
Answer: a
Explanation: Whitespace is a term that refers to characters like spaces, tabs, and newlines that are used
for formatting purposes.
Answer: d
Explanation: The default number of spaces is 4 in programming.
Answer: c
Explanation: By formatting your code, the user can easily understand it and can upgrade it without any
complexity.
Answer: a
Explanation: Variable initalization should be done with one space on left and right of equal operator.
Answer: b
Explanation: The braces that tell where a function begins and ends should be aligned with the function
name and be on their own lines.
7. Which function allows you to set minimum width for the next input?
a) setfill
b) setw
c) setwidth
d) none of the mentioned
View Answer
Answer: b
Explanation: setw function of iomanip header file allows you to set minimum width for the next input.
#include <iostream>
#include <iomanip>
int main()
showDate(1, 1, 2013);
return 0;
a) 1,1,2013
b) 2013
c) 01/01/2013
d) None of the mentioned
View Answer
Answer: c
Explanation: In this program, We are using the setw function to print the date in correct format.
Output:
$ g++ form.cpp
$ a.out
01/01/2013
#include <iostream>
int main()
a) 64100
b) 48
c) 345
d) None of the mentioned
View Answer
Answer: a
Explanation: In this program, We are finding the octal number of given number by using oct function.
Output:
$ g++ form1.cpp
$ a.out
64100
Answer: a
Explanation: None.
Here is a listing of C++ interview questions on “File Streams and String Streams” along with answers,
explanations and/or solutions:
Answer: b
Explanation: You can write information to a file from your program using the stream insertion operator
<<.
2. Which function is used to position back from the end of file object?
a) seekg
b) seekp
c) both seekg & seekp
d) none of the mentioned
View Answer
Answer: a
Explanation: The member function seekg is used to position back from the end of file object.
3. How many objects are used for input and output to a string?
a) 1
b) 2
c) 3
d) 4
View Answer
Answer: c
Explanation: The stringstream, ostringstream, and istringstream objects are used for input and output to
a string.
#include <iostream>
#include <fstream>
int main ()
int length;
char * buffer;
ifstream is;
is.close();
delete[] buffer;
return 0;
a) This is sample
b) sample
c) Error
d) Runtime error
View Answer
Answer: d
Explanation: In this program, if the file exist, it will read the file. Otherwise it will throw an exception. A
runtime error will occur because the value of the length variable will be “-1” if file doesn’t exist and in
line 13 we are trying to allocate an array of size “-1”.
#include <iostream>
int main ()
first = cin.get();
cin.sync();
second = cin.get();
return 0;
}
a) first
b) second
c) Returns first 2 letter or number from the entered word
d) None of the mentioned
View Answer
Answer: c
Explanation: In this program, We are using the sync function to return the first two letters of the
entered word.
Output:
$ g++ stream.cpp
$ a.out
Enter a word: steve
s
t
#include<iostream>
#include <fstream>
int main ()
outfile << n;
outfile.flush();
outfile.close();
return 0;
a) Done
b) Error
c) Runtime error
d) None of the mentioned
View Answer
Answer: a
Explanation: In this program, We are using the flush function to update the contents in a file.
Output:
$ g++ stream1.cpp
$ a.out
Done
#include <iostream>
int main ()
int a = 100;
double b = 3.14;
cout << a;
endl (cout);
return 0;
a) 100
b) 3.14
c) 314
d) All of the mentioned
View Answer
Answer: d
Explanation: In this program, We are printing the given value and manipulating the given value by using
endl.
Output:
$ g++ stream2.cpp
$ a.out
100
3.14
314
8. By seeing which operator thus this program stops getting the input?
#include <iostream>
#include <fstream>
int main ()
char ch;
streambuf * p;
ofstream os ("test.txt");
pbuf = os.rdbuf();
do {
ch = cin.get();
p -> sputc(ch);
os.close();
return 0;
a) dot operator
b) insertion operator
c) $ symbol
d) none of the mentioned
View Answer
Answer: a
Explanation: This program will stop getting the input, When it occurs the dot(.) operator.
Output:
$ g++ stream3.cpp
$ a.out
Steve.
9. Which member function is used to determine whether the stream object is currently associated with
a file?
a) is_open
b) buf
c) string
d) none of the mentioned
View Answer
Answer: a
Explanation: The member function is_open can be used to determine whether the stream object is
currently associated with a file.
10. Which header file is used for reading and writing to a file?
a) #include<iostream>
b) #include<fstream>
c) #include<file>
d) None of the mentioned
View Answer
Answer: b
Explanation: None.
Here is a listing of C++ quiz on “Buffering” along with answers, explanations and/or solutions:
Answer: b
Explanation: For the stand of file operations, writing to memory (RAM) is always faster than writing to
the file on the disk directly.
Answer: b
Explanation: There are two types of read and write tests. They are throughput in random reads and
throughput in contiguous reads.
3. What will act as a intermediate between i/o operations and physical file?
a) Memory
b) Ram
c) Stream buffer
d) None of the mentioned
View Answer
Answer: c
Explanation: A stream buffer is a block of data that acts as intermediary between the i/o operations and
the physical file associated to the stream.
#include <stdio.h>
int main ()
char buffer[BUFSIZ];
setbuf ( p1 , buffer );
fflush (p1);
setbuf ( p2 , NULL );
fclose (p1);
fclose (p2);
return 0;
}
a) Buffered stream
b) Unbuffered stream
c) Error
d) Buffered & Unbuffered stream
View Answer
Answer: d
Explanation: In this program, the fopen will create the file and send the text to both of the files.
Output:
$ g++ buf.cpp
$ a.out
“Buffered stream” in myfile.txt
“Unbuffered stream” in myfile2.txt
#include <stdio.h>
int main ()
FILE * p;
long size;
if (p == NULL)
else
fclose (p);
return 0;
a) 10
b) 20
c) 5
d) Depends upon the file
View Answer
Answer: d
Explanation: This program will return the size of the file in bytes.
Output:
$ g++ buf1.cpp
$ a.out
20
#include <stdio.h>
int main ()
fclose (stdout);
return 0;
a) This sentence
b) This sentence is redirected
c) This sentence is redirected to a file
d) None of the mentioned
View Answer
Answer: c
Explanation: In this program, We are sending the text to the file by opening the file using the function
freopen.
Output:
$ g++ buf2.cpp
$ a.out
This sentence is redirected to a file
#include <stdio.h>
int main ()
{
int n;
FILE * p;
fputc ( n, p);
rewind (p);
fclose (p);
buffer[3] = '\0';
puts (buffer);
return 0;
a) ABCD
b) ABC
c) ABCDE
d) None of the mentioned
View Answer
Answer: b
Explanation: In this program, We are setting the buffer size upto 3 only, So it is printing ABC.
Output:
$ g++ buf3.cpp
$ a.out
ABC
#include <stdio.h>
int main ()
FILE * p;
return 0;
a) xyz
b) zyx
c) yxz
d) none of the mentioned
View Answer
Answer: a
Explanation: In this program, We are writing into the file by using the function fwrite.
Output:
$ g++ buf4.cpp
$ a.out
xyz
Answer: d
Explanation: None.
Answer: b
Explanation: There are two parameters that are used in setbuf. They are stream and buffer.
Here is a listing of C multiple choice questions on “Locale” along with answers, explanations and/or
solutions:
Answer: b
Explanation: A locale is a set of features that are culture-specific, which can be used by programs to be
more portable internationally.
Answer: a
Explanation: A locale object contains information about which facet objects constitute a locale, and is
each one of these facet objects that implements specific features as member functions.
Answer: c
Explanation: There are 6 categories of facet in c++. They are collate, ctype, monetary, numeric, time and
messages.
#include <stdio.h>
#include <ctype.h>
int main ()
{
int i = 0;
char c;
while (str[i])
c = str[i];
if (islower(c))
c = toupper(c);
putchar (c);
i++;
return 0;
a) Steve jobs
b) STEVE JOBS
c) Steve
d) None of the mentioned
View Answer
Answer: b
Explanation: In this program, We have converted the lower case letters to uppercase letters by using
toupper function.
Output:
$ g++ loc.cpp
$ a.out
STEVE JOBS
#include <stdio.h>
#include <ctype.h>
int main ()
int i = 0;
char str[] = "C";
while (str[i])
if (isalpha(str[i]))
printf ("alphabetic");
else
i++;
return 0;
a) alphabetic
b) not alphabetic
c) Error
d) None of the mentioned
View Answer
Answer: a
Explanation: In this program, We are checking whether the character is alphabetic or not alphabetic by
using the function isalpha.
Output:
$ g++ loc1.cpp
$ a.out
alphabetic
#include <stdio.h>
#include <ctype.h>
int main ()
int i;
i = 0;
while ( isalnum(str[i] ))
i++;
return 0;
a) 1
b) 2
c) 3
d) 4
View Answer
Answer: d
Explanation: In this program, We are counting the number of alphanumeric values by using the function
isalnum.
Output:
$ g++ loc2.cpp
$ a.out
4
#include <stdio.h>
#include <ctype.h>
int main ()
int i = 0;
int cx = 0;
while (str[i])
if (ispunct(str[i])) cx++;
i++;
return 0;
}
a) 1
b) 2
c) 3
d) 4
View Answer
Answer: b
Explanation: In this program, We are counting the number of special characters in the program by using
the function ispunct.
Output:
$ g++ loc3.cpp
$ a.out
2
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main ()
if (isxdigit(str[0]))
return 0;
a) 64345
b) 21312
c) 65535
d) Error
View Answer
Answer: c
Explanation: In this program, We are converting the hexadecimal number to decimal number.
Output:
$ g++ loc4.cpp
$ a.out
65535
Answer: b
Explanation: Every program has a single locale object which is its global locale.
Answer: a
Explanation: None.
Here is a listing of C++ quiz on “C Input Output” along with answers, explanations and/or solutions:
1. Which header file is used with input and output operations of C in C++?
a) stdio.h
b) cstdio
c) iostream
d) none of the mentioned
View Answer
Answer: b
Explanation: Input and Output operations of c can be performed in C++ using the C Standard Input and
Output Library.
2. Which will be used with physical devices to interact from C++ program?
a) Programs
b) Library
c) Streams
d) None of the mentioned
View Answer
Answer: c
Explanation: C++ library uses streams to operate with physical devices such as Keyboards, Printers,
Terminals or with any other type of files supported by the system.
Answer: c
Explanation: There are streams that are automatically created when executing a program. They are
stdin, stdout and stderr.
#include <stdio.h>
int main ()
if (remove( "myfile.txt" ) != 0 )
perror( "Error" );
else
puts( "Success" );
return 0;
a) Error
b) Success
c) Runtime Error
d) Can’t say
View Answer
Answer: d
Explanation: If myfile.txt exists, then it will delete the file. Else it will print an error message.
Output:
$ g++ out.cpp
$ a.out
Success
#include <stdio.h>
int main ()
FILE * p;
int c;
int n = 0;
if (p == NULL)
else
do {
c = getc (p);
if (c == '$')
n++;
} while (c != EOF);
fclose (p);
return 0;
}
a) Count of ‘$’ symbol
b) Error opening file
c) Any of the mentioned
d) None of the mentioned
View Answer
Answer: c
Explanation: Any one is possible – Either the file doesn’t exist or If exist, it will print the total number of
‘$’ character.
#include <stdio.h>
int main ()
FILE * pFile;
char c;
fclose (pFile);
return 0;
a) ABCD
b) ABC
c) ABCDE
d) None of the mentioned
View Answer
Answer: c
Explanation: In this program, We are printing from A to E by using the putc function.
Output:
$ g++ out2.cpp
$ a.out
ABCDE
7. What is the name of the myfile2 file after executing this program?
#include <stdio.h>
int main ()
int result;
if (result == 0)
puts ( "success" );
else
perror( "Error" );
return 0;
a) name
b) new
c) newname
d) none of the mentioned
View Answer
Answer: c
Explanation: In this program, We are renaming the myfile2 to newname by using the function rename.
Output:
myfile2.txt is renamed to newname.txt
#include <stdio.h>
int main ()
FILE * p;
int n = 0;
if (p == NULL)
perror ("Error opening file");
else
++n;
if (feof(p))
else
fclose (p);
return 0;
a) 10
b) 15
c) Depends on the text file
d) None of the mentioned
View Answer
Answer: c
Explanation: In this program, We are reading the number of characters in the program by using the
function feof.
Output:
$ g++ out4.cpp
$ a.out
162
Answer: b
Explanation: There are three indicators are available in C++. They are Error indicator, End-Of-File
indicator and Position indicator.
10. What is the benefit of c++ input and output over c input and output?
a) Type safety
b) Exception
c) Both Type safety & Exception
d) None of the mentioned
View Answer
Answer: a
Explanation: None.
Here is a listing of C++ questions and puzzles on “Numeric Limits” along with answers, explanations
and/or solutions:
Answer: c
Explanation: Numeric limits provides the information about the properties of arithemetic types.
Answer: a
Explanation: The member shall still be defined in a name-space scope if it is used in the program.
3. What will the max function in the numeric limit will return for type float?
a) Maximum finite value for a float type
b) Maximum finite value
c) Minimum finite value
d) None of the mentioned
View Answer
Answer: a
Explanation: Max function in the numeric limit will return the maximum finite value for a float type.
#include <iostream>
#include <limits>
int main ()
return 0;
a) 53234
b) false
c) true
d) none of the mentioned
View Answer
Answer: b
Explanation: In this program, We are checking whether the integer has limit or not by using has_infinity
function.
Output:
$ g++ num.cpp
$ a.out
false
5. What is the output of this program?
#include <iostream>
#include <limits>
int main( )
a) 53723
b) 32423
c) 32767
d) None of the mentioned
View Answer
Answer: c
Explanation: In this program, We are finding the max range for short int by using max function.
Output:
$ g++ num1.cpp
$ a.out
32767
#include <iostream>
#include <limits>
int main( )
a) 0010
b) 0012
c) 1100
d) 0011
View Answer
Answer: d
Explanation: In this program, We are finding whether the types are free of rounding errors by using the
function is_exact.
Output:
$ g++ num2.cpp
$ a.out
0011
#include <iostream>
#include <limits>
int main( )
float f = 99999999;
cout.precision ( 10 );
a) 6
b) 15
c) 100000000
d) All of the mentioned
View Answer
Answer: d
Explanation: In this program, We are finding the number of decimal points that the type can represent
without loss of precision.
Output:
$ g++ num3.cpp
$ a.out
6
15
100000000
#include <iostream>
#include <limits>
int main( )
a) 125
b) -125
c) 123
d) None of the mentioned
View Answer
Answer: b
Explanation: In this program, We are finding the minimum radix of a type by using min_exponent
function.
Output:
$ g++ num4.cpp
$ a.out
-125
Answer: b
Explanation: <limits> header file will be used for numeric limits in C++.
10. Pick out the incorrect static function member in numeric limits.
a) denorm_min
b) digits
c) infinity
d) max_finite
View Answer
Answer: d
Explanation: None.
Here is a listing of C++ interview questions on “Standard Mathematical Functions” along with answers,
explanations and/or solutions:
1. With which does the trigonometric functions work with angles in c++?
a) Degrees
b) Radians
c) Both Degrees & Radians
d) None of the mentioned
View Answer
Answer: b
Explanation: The trigonometric functions work with angles in radians rather than degrees.
Answer: a
Explanation: #include is a header file required for manipulation of math functions.
3. How many macros are used by mathematical functions in the header file
?
a) 1
b) 2
c) 3
d) 4
View Answer
Answer: c
Explanation: There are three macros used in mathematical functions. They are HUGE_VAL, EDOM,
ERANGE.
#include <stdio.h>
#include <math.h>
int main ()
int n;
param = 8.0;
return 0;
a) 6
b) 7
c) 8
d) 9
View Answer
Answer: c
Explanation: In this program, We are breaking out the number by using the frexp function.
Output:
$ g++ math.cpp
$ a.out
8
#include <stdio.h>
#include <math.h>
int main ()
param = 5.5;
return 0;
a) 5.5
b) 3.14
c) 1.704
d) None of the mentioned
View Answer
Answer: c
Explanation: In this program, We are finding out the log value of param by using param function.
Output:
$ g++ math1.cpp
$ a.out
1.704748
#include <stdio.h>
#include <math.h>
int main ()
return 0;
a) 343
b) 343.00
c) 334
d) None of the mentioned
View Answer
Answer: b
Explanation: In this program, We are calculating the 7 power of 3 by using the powfunction. As we are
using 7.0, it is producing the result in 343.00
Output:
$ g++ math2.cpp
$ a.out
343.000000
#include <stdio.h>
#include <math.h>
int main ()
return 0;
a) 1.300
b) 1.700
c) 1.300
1.700
d) None of the mentioned
View Answer
Answer: c
Explanation: In this program, We are finding the remainder of the given values by using fmod function.
Output:
$ g++ math3.cpp
$ a.out
1.300000
1.700000
#include <stdio.h>
#include <math.h>
int main ()
{
printf ("%lf", fabs (-10.6) );
return 0;
a) 10
b) -10
c) 10.600000
d) None of the mentioned
View Answer
Answer: c
Explanation: In this program, We are finding the absolute value of -10.6 by using abs function.
Output:
$ g++ math4.cpp
$ a.out
10.600000
Answer: b
Explanation: None.
Answer: b
Explanation: There are two parameters that are used in frexp function. They are floating point value to
be computed and pointer to an int object.
Here is a listing of C++ quiz on “Vector Arithmetic” along with answers, explanations and/or solutions:
Answer: a
Explanation: Boost package has a linear algebra package that may well suits for vector arithmetic.
Answer: c
Explanation: vmath is set of C++ classes for Vector and Matrix algebra used in the programs.
Answer: b
Explanation: As we are using the vector and it will give accurate result if we use const reference.
#include <iostream>
class vec
public:
vec(float f1, float f2)
x = f1;
y = f2;
vec()
float x;
float y;
};
int main()
cout << v3.x << ", " << v3.y << endl;
vec result;
return result;
};
a) 4, 5
b) 4, 4
c) 5, 4
d) 5, 5
View Answer
Answer: c
Explanation: In this program, We are adding two vectors by using standalone function and printing it.
Output:
$ g++ vecar.cpp
$ a.out
5, 4
#include <iostream>
#include <vector>
int main ()
vector<bool> mask;
mask.push_back(true);
mask.flip();
return 0;
a) false
b) true
c) false & true
d) none of the mentioned
View Answer
Answer: a
Explanation: In this program, We are fliping the vector values by using flip function.
Output:
$ g++ vecar1.cpp
$ a.out
false
6. What will be the type of output of vector cross product?
a) Scaler
b) Vector
c) Both Scaler & Vector
d) None of the mentioned
View Answer
Answer: b
Explanation: None.
Answer: b
Explanation: This is a specialized version of vector, which is used for elements of type bool and optimizes
for space.
Answer: a
Explanation: None.
Here is a listing of C++ quiz on “Generalized Numeric Algorithms” along with answers, explanations
and/or solutions:
1. Which header file is used to operate on numeric sequences?
a) number
b) numeric
c) algorithm
d) none of the mentioned
View Answer
Answer: b
Explanation: header file is used to operate on numeric sequences that support certain operations.
Answer: c
Explanation: Blitz++ is a high-performance vector mathematics library written in C++.
Answer: b
Explanation: Returns the result of accumulating all the values in the range from first to last.
#include <iostream>
#include <functional>
#include <numeric>
return x + y;
int main ()
{
int result[7];
return 0;
a) 1 1 1 2
b) 1 2 3 1
c) 1 2 3 5
d) None of the mentioned
View Answer
Answer: a
Explanation: In this program, We are calculating the adjacent difference of the given range by using
function adjacent_difference.
Output:
$ g++ gnl.cpp
$ a.out
1112
#include <iostream>
#include <functional>
#include <numeric>
return x + 2 * y;
struct myclass
return x + 3 * y;
} myobject;
int main ()
a) 100
b) 140
c) 160
d) 180
View Answer
Answer: c
Explanation: In this program, We are calculating the product of every number in the given range by
using accumulate function.
Output:
$ g++ gnl1.cpp
$ a.out
160
#include <iostream>
#include <functional>
#include <numeric>
return x + y + 1;
}
int main ()
int result[5];
return 0;
a) 1 3 6
b) 1 3 6 10 15
c) 1 3 6 10 16
d) None of the mentioned
View Answer
Answer: b
Explanation: In this program, We are calculating the sum of the given range by using partial_sum
function.
Output:
$ g++ gnl2.cpp
$ a.out
1 3 6 10 15
#include <iostream>
#include <functional>
#include <numeric>
return x + 2 * y;
struct myclass
{
int operator()(int x, int y)
return x + 3 * y;
} myobject;
int main ()
return 0;
a) 40
b) 100
c) 140
d) None of the mentioned
View Answer
Answer: a
Explanation: In this program, We are finding the difference between the init and the total of numbers
range.
Output:
$ g++ gnl3.cpp
$ a.out
40
#include <iostream>
#include <functional>
#include <numeric>
{
return x - y;
return x + y;
int main ()
int a = 100;
myproduct);
return 0;
a) 40
b) 34
c) 32
d) 20
View Answer
Answer: b
Explanation: In this program, We are forming the custom function from two ranges by using
inner_product function.
Output:
$ g++ gnl4.cpp
$ a.out
34
Answer: a
Explanation: The default operation is to calculate the difference, but some other operation can be
specified as binary operator instead.
Here is a listing of online C++ test questions on “Random Numbers” along with answers, explanations
and/or solutions:
Answer: d
Explanation: cstdlib header file is used to create pseudo random number. C++11 standard added
random header file as well to generate random numbers.
Answer: a
Explanation: There is one parameter available in srand function. That is an integer value to be used as
seed by the pseudo-random number generator algorithm.
#include <cstdlib>
#include <iostream>
int main()
a) Any number
b) 89
c) 0 to RAND_MAX
d) None of the mentioned
View Answer
Answer: c
Explanation: As the declared number is integer, It will produce the random number from 0 to
RAND_MAX. The value of RAND_MAX is library-dependent, but is guaranteed to be at least 32767 on
any standard library implementation.
Output:
$ g++ rand.cpp
$ a.out
574
5. What is the output of this program?
#include <cstdlib>
#include <iostream>
int main()
a) 4385234
b) 12321412
c) Depends on the compiler
d) None of the mentioned
View Answer
Answer: c
Explanation: RAND_MAX is a function used by the compiler to create a maximum random number.
Output:
$ g++ rand1.cpp
$ a.out
2147483647
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main ()
srand (time(NULL));
srand (1);
return 0;
a) 12
b) 23
c) 33
d) Any number from 0 to 99
View Answer
Answer: d
Explanation: This program will create a random number based on time function using srand function.
Output:
$ g++ rand2.cpp
$ a.out
23
#include <cstdlib>
#include <ctime>
#include <iostream>
int main()
srand((unsigned)time(0));
int ran;
a) 2 4
b) 10 20
c) Any two number from 1 to 10
d) None of the mentioned
View Answer
Answer: c
Explanation: In this program, It will produce two numbers from 1 to 10 by using srand function.
Output:
$ g++ rand3.cpp
$ a.out
45
#include <iostream>
#include <ctime>
#include <cstdlib>
int main()
srand((unsigned)time(0));
int ran;
a) 1
b) 2
c) 3
d) 4
View Answer
Answer: a
Explanation: In this program, We have generated a certain random number by using the above formula.
Output:
$ g++ rand4.cpp
$ a.out
1
Answer: d
Explanation: In C++, modulo operator is denoted by %.
Answer: b
Explanation: None.