Q11. Demonstrate Class Templates in C++
Question:
Write a program to demonstrate use of class templates.
My Approach
C++ me class templates generic programming ke liye use hote hain.
Agar hame ek aisi class design karni ho jo different data types ke sath kaam kare (int, float, string, etc.), to hame har type ke liye alag class banane ki zarurat nahi hai.
Bas ek hi template class banani hoti hai aur wo sabhi types ke liye kaam karegi.
Program Code
File Name: class_template_demo.cpp
#include <iostream>
using namespace std;
// Template Class
template <typename T>
class Calculator {
private:
T num1, num2;
public:
// Constructor
Calculator(T a, T b) : num1(a), num2(b) {}
T add() { return num1 + num2; }
T subtract() { return num1 - num2; }
T multiply() { return num1 * num2; }
T divide() {
if (num2 != 0)
return num1 / num2;
else {
cout << "Error: Division by zero!" << endl;
return 0;
}
}
};
int main() {
// Integer calculator
Calculator<int> intCalc(20, 10);
cout << "Integer Addition: " << intCalc.add() << endl;
cout << "Integer Subtraction: " << intCalc.subtract() << endl;
cout << "Integer Multiplication: " << intCalc.multiply() << endl;
cout << "Integer Division: " << intCalc.divide() << endl;
// Float calculator
Calculator<float> floatCalc(5.5, 2.2);
cout << "\nFloat Addition: " << floatCalc.add() << endl;
cout << "Float Subtraction: " << floatCalc.subtract() << endl;
cout << "Float Multiplication: " << floatCalc.multiply() << endl;
cout << "Float Division: " << floatCalc.divide() << endl;
return 0;
}Sample Output
Integer Addition: 30
Integer Subtraction: 10
Integer Multiplication: 200
Integer Division: 2
Float Addition: 7.7
Float Subtraction: 3.3
Float Multiplication: 12.1
Float Division: 2.5Explanation
template <typename T>→ compiler ko batata hai ki ye generic class hai.- Ek hi class
Calculatorintegers aur floats dono ke liye kaam kar rahi hai. - Humne constructor, basic arithmetic methods (add, subtract, multiply, divide) define kiye.
- Division me
num2 != 0check karke runtime error handling bhi dikhaya.
Real-Life Scenario
- Agar tum MCA students ke marks integer me store karke calculation karte ho.
- Ya phir lab performance percentage float me calculate karna ho.
- Dono ke liye ek hi class template
Calculatorka use ho sakta hai.
Conclusion
- Class templates ek hi class ko multiple data types ke liye reusable banate hain.
- Ye programming ko modular, flexible aur efficient banata hai.
Submitted by:
Intesab Ansari
MCA Student, NMU University
Portfolio: intesab.live
Last updated on