Constructor :

    The constructor is used to initialize the member variable of the class. 

It is of three types :

  • Default constructor
  • Parameterized constructor
  • Copy constructor

Copy Constructor :


    It can be known as an special type of constructor that is called to copy an object. It is used to initialize and declare one object from another object.

Problem : C++ program to find factorial of a number using copy constructor

Solution : program using copy constructor.


#include<iostream>

using namespace std;

class factorial

{

        int i,n, fact;

        public:

        factorial(int x)  // constructor

        {

                n=x;

                fact=1;

        }

        factorial(factorial &x)

        {

                n=x.n;

                fact=1;

        }

        void compute()

        {

                for(i=1; i<=n; i++)

                {

                        fact=fact*i;

                }

        }

        void display()

        {

                cout<<"\n Factorial of the given no. is : "<<fact;

        }

};

int main()

{

        int x;

        cout<<"\n Enter the value : ";

        cin>>x;

        fact ob1(x);  // object is created

        ob1.compute();

        ob1.display();


        fact ob2(ob1); // object is passed in copy constructor

        ob2.compute();

       ob2.display();


        return 0;

}