Site icon T4Tutorials.com

C++ program for factorial using Constructor Destructor

Let us see the C++ program for factorial using class constructor and destructor. The factorial program in C++ object-oriented programming is a very important question asked in papers of object-oriented programming.

C++ program for factorial using constructor 

#include<iostream>
using namespace std;
class factorial
{
	public:
	unsigned long long fact=1;
	int num;
	int input();
	void fact_function();
	void display();
	factorial(int);	
};

	//parametrized constructor  
	factorial::factorial(int a)
	{
		num=a;
	}

	void factorial::fact_function()
	{
	
	for(int i=1;i<=num;i++)
	{
	fact=fact*i;
	
	}
	}

	void factorial::display()
	{
	cout<<"Factorial of entered number is: "<<fact;
	}

int main()
{
	int num;
	cout<<"Please enter a number: ";
	cin>>num;
	
	//calling parametrized constructor
	factorial object(num);
	
	object.fact_function();
	object.display();
}

Output


C++ program for factorial using the destructor

#include<iostream>
using namespace std;
class factorial
{
	public:
	unsigned long long fact=1;
	int num;
	int input();
	void fact_function();
	void display();
	factorial(int);
	~factorial();
	
};
	//parametrized constructor 
	factorial::factorial(int a)
	{
		num=a;
	}
	
	//Destructor will destroy the values of variables
	factorial::~factorial()
	{	
	cout<<"Memory occupied by variable's values has been cleared by destructor"<<endl;
	system("pause");
	}
	
	void factorial::fact_function()
	{
	for(int i=1;i<=num;i++)
	{
	fact=fact*i;
	}
	}

	void factorial::display()
	{
	cout<<"Factorial of entered number is: "<<fact;
	}

int main()
{
	for(int i=2; i>1; i++)
	{
			system("cls"); //clears the screen
	int num;
	cout<<"Please enter a number: ";
	cin>>num;
	
	//calling parametrized constructor
	factorial object(num);
	
	object.fact_function();
	object.display();
	cout<<endl;	
	}
	return 0;
}

Output

More Practice on Factorial problem in C++

  1. Factorial Program in C++
  2. factorial using single inheritance
  3. Factorial Program in C++ using Class Objects
  4. factorial using Multiple inheritances
  5. C++ program for factorial using Constructor DestructorFactorial Of A Number By Using The Recursion
  6. Factorial Program with structures and pointers C++
  7. Factorial Program with Nested Structure C++
  8. factorial of a no. by defining the member functions outside the class
Exit mobile version