Find factorial of a number using copy constructor

Q. Write a C++ program to find the factorial of a number using copy constructor.

Answer:

Constructor is a special type of member function which initializes an object automatically when it is created. It has same name as class name. Constructor does not have return type.

Copy constructor is a special type of constructor which takes an object as an argument. It is used for creating the second object.

Following program is calculating the factorial of a number using copy constructor.

#include<iostream>
using namespace std;
class fact
{
        int n, i, facti;
        public:
        fact(int x)  //copy constructor
        {
                n=x;
                facti=1;
        }
        fact(fact &x)
        {
                n=x.n;
                facti=1;
        }
        void calculate()
        {
                for(i=1; i<=n; i++)
                {
                        facti=facti*i;
                }
        }
        void display()
        {
                cout<<"\n Factorial : "<<facti;
        }
};
int main()
{
        int x;
        cout<<"\n Enter Value : ";
        cin>>x;
        fact f1(x);  
        f1.calculate();
        f1.display();

        fact f2(f1);  //copy constructor takes an object as an argument.
        f2.calculate();
        f2.display();

        return 0;
}


Output:

copy constructor factorial