Write a c++ program using constructor and destructor to find factorial of a given number?
Write a c++ program using constructor and destructor to find factorial of a given number?
Best answer
a c++ program using constructor and destructor to find factorial of a given number
The constructor receives the number and computes its factorial when the object is created; the destructor runs automatically when the object goes out of scope.
#include <iostream>
using namespace std;
class Factorial {
int n;
long long fact;
public:
Factorial(int x) { // constructor
n = x;
fact = 1;
for (int i = 1; i <= n; i++)
fact = fact * i;
}
void display() {
cout << "Factorial of " << n << " = " << fact << endl;
}
~Factorial() { // destructor
cout << "Destructor called: object destroyed" << endl;
}
};
int main() {
int num;
cout << "Enter a number: ";
cin >> num;
Factorial f(num); // constructor is called here
f.display();
return 0; // destructor is called here
}Sample output (input 5):
Factorial of 5 = 120
Destructor called: object destroyed
A constructor has the same name as the class and no return type; it initialises the object. The destructor has the class name preceded by ~, takes no arguments and is called automatically when f is destroyed at the end of main().
Log in or create a free account to answer this question.