Class Template in C++ - Explanation (10 Marks)
Class Template in C++ - Explanation (10 Marks)
Definition:
A class template in C++ allows you to create a generic class that works with different data types
using template parameters.
It is part of generic programming and supports code reusability and type flexibility.
Key Features:
- Defined using the 'template' keyword.
- Allows a single class definition to work with multiple data types.
- Promotes type safety, code reuse, and flexibility.
- Avoids code duplication for similar classes handling different data types.
Syntax:
template <class T>
class ClassName {
T var;
public:
void setData(T value);
T getData();
};
Program Example:
#include <iostream>
using namespace std;
// Class Template
template <class T>
class Box {
T value;
public:
void setData(T val) {
value = val;
T getData() {
return value;
};
int main() {
Box<int> intBox;
Box<float> floatBox;
intBox.setData(100);
floatBox.setData(25.75f);
cout << "Integer Value: " << intBox.getData() << endl;
cout << "Float Value: " << floatBox.getData() << endl;
return 0;
}
Output:
Integer Value: 100
Float Value: 25.75
Explanation:
- 'Box' is a class template that can store values of any type 'T'.
- Two objects are created: 'intBox' for int and 'floatBox' for float.
- The same class definition works for both data types.
- This saves the need to define separate classes for each data type.
Advantages:
- Eliminates redundancy.
- Promotes reusable, maintainable, and type-safe code.
- Supports Generic Programming.