- 2070 Chaitra · 3 marks
Default arguments in class template
Short answer
Class templates can specify default types for parameters (e.g., template<class T1=int, class T2=float>). If omitted, defaults are used; empty angle brackets <> must be written. Once a parameter has a default, subsequent parameters must also have defaults.
How can default arguments be used in class template?
A class template can give a default type to its type parameters, in the same way functions give default argument values. If the user does not supply a type while creating an object, the default is used.
Syntax:
template <class T1 = int, class T2 = float>
class Test { ... };
Rules:
- Defaults are written in the template header (only once, in the class declaration, not in out-of-class member definitions).
- Once a parameter has a default, the parameters after it must also have defaults.
- Empty angle brackets
<>must still be written when all defaults are used. - A non-type parameter can also have a default value, e.g.
int size = 10.
Example
#include <iostream>
using namespace std;
template <class T = int, int size = 5>
class Array {
T a[size];
public:
void set(int i, T v) { a[i] = v; }
T get(int i) { return a[i]; }
int length() { return size; }
};
int main() {
Array<> x; // int, size 5 (both defaults)
Array<float> y; // float, size 5
Array<char, 20> z; // char, size 20
x.set(0, 7);
cout << x.get(0) << " " << x.length() << endl; // 7 5
cout << y.length() << " " << z.length() << endl; // 5 20
return 0;
}
✓ Answer checked by Claude Opus 5.5 (high effort)
Related questions
- Default arguments and function overloading · Object Oriented Programming, chapter 3 · asked 5×
- Default arguments and their syntax · Object Oriented Programming, chapter 3 · asked 2×
- Display N characters using default arguments · Object Oriented Programming, chapter 3
- Class and function template with syntax · Object Oriented Programming, chapter 9 · asked 4×
- Class template with multiple template types · Object Oriented Programming, chapter 9
- Class template with suitable example · Object Oriented Programming, chapter 9