This section contains carefully selected MCQs and Previous Year Questions with explanations to help students understand concepts and prepare effectively for examinations, interviews, and competitive tests.
Q: 1The keyword ‘template’ can be used for?
Option C
In programming, we often need to write the same logic again and again for different data types. For example, a function to add two integers and another function to add two floating-point numbers. Writing separate functions for each data type leads to code duplication.
To solve this problem, C++ provides the concept of generic programming using the template keyword.
A template allows us to write one function or one class that can work with any data type. The actual data type is decided at compile time when the program is compiled.
Thus, the template keyword is mainly used for developing generic programming, which helps in:
#include<iostream>
using namespace std;
template<class T>
T add(T a,T b)
{
return a+b;
}
int main()
{
cout<<add(2,5)<<endl;
cout<<add(2.5,6.3)<<endl;
return 0;
}
OUTPUT
7
8.8
Q: 2Complete the code for overloaded template by replacing the ABCD:
#include<iostream>
using namespace std;
template <class X>
void f (X a)
{
cout<<”Inside ”;
}
ABCD
{
cout<<”Outside ”;
}
int main()
{
f (10);
f (10,20);
return 0;
}
Option D
The original function template is declared for one argument as:
template <class X>
void f(X a) {
cout << "Inside ";
}
In main(), the code calls:
f(10); // Calls the first template function.
f(10, 20); // Needs a new template function for two arguments.
The second call f(10, 20) cannot use the first template because it only takes one argument. Therefore, we need to overload the template for two arguments of possibly different types as:
template <class X, class Y>
void f(X a, Y b) {
cout << "Outside ";
}
You have reached the end of this topic. Continue learning with the next topic below.
Thank you so much for taking the time to read my Computer Science MCQs section carefully. Your support and interest mean a lot, and I truly appreciate you being part of this journey. Stay connected for more insights and updates! If you'd like to explore more tutorials and insights, check out my YouTube channel.
Don’t forget to subscribe and stay connected for future updates.