Here is a listing of C++ interview questions on “Subscripting” along with answers, explanations and/or solutions:
1. subscript operator is used to access which elements?
a) string
b) char
c) array
d) float
Answer: c
Clarification: To access any element of an array we use following syntax array[i], where i is called subscript representing the ith element of an array, whereas no such cases in char and strings.
2. How many arguments will the subscript operator will take for overloading?
a) 1
b) 2
c) 0
d) as many as possible
Answer: a
Clarification: The subscript operator overload takes only one argument, but it can be of any type.
3. Pick out the correct statement.
a) subscript operator has a higher precedence than the assignment operator
b) subscript operator has a lower precedence than the assignment operator
c) subscript operator is used with string elements
d) subscript operator is used with char elements
Answer: a
Clarification: Subscription operator has more precedence otherwise if that is not the case then the statement var = arr[i] will be meaningless and will have no effect.
4. What will be the output of the following C++ code?
-
#include
-
using namespace std;
-
const int SIZE = 10;
-
class safe
-
{
-
private:
-
int arr[SIZE];
-
public:
-
safe()
-
{
-
register int i;
-
for (i = 0; i < SIZE; i++)
-
{
-
arr[i] = i;
-
}
-
}
-
int &operator[](int i)
-
{
-
if (i > SIZE)
-
{
-
cout << "Index out of bounds" <<endl;
-
return arr[0];
-
}
-
return arr[i];
-
}
-
};
-
int main()
-
{
-
safe A;
-
cout << A[5];
-
cout << A[12];
-
return 0;
-
}
a)
5Index out of bounds 0
b) 40
c) 50
d) 51
Answer: a
Clarification: 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
5. What will be the output of the following C++ code?
-
#include
-
using namespace std;
-
class numbers
-
{
-
private:
-
int m_nValues[10];
-
public:
-
int& operator[] (const int nValue);
-
};
-
int& numbers::operator[](const int nValue)
-
{
-
return m_nValues[nValue];
-
}
-
int main()
-
{
-
numbers N;
-
N[5] = 4;
-
cout << N[5];
-
return 0;
-
}
a) 5
b) 4
c) 3
d) 6
Answer: b
Clarification: In this program, We are getting the values and returning it by overloading the subscript operator.
Output: