Simple Copy Constructor Example Program For Find Factorial In C++

Definition Copy Constructor:

A copy constructor is a like a normal parameterized Constructor, but which parameter is the same class object.  Copy constructor uses to initialize an object using another object of the same class. 

To calculate factorial of a given number using the copy constructor.

for better Understanding,

Syntax: Copy Constructor Declaration

// In Main Function
class_name object1(params);

Method 1 - Copy Constrcutor
class_name object2(object1); 

Method 2 - Copy Constrcutor
class_name object3 = object1; 

Definition of Factorial

In mathematics, the factorial of a non-negative integer n, denoted by n!, is the product of all positive integers less than or equal to n.

For example,

6! = 6 x 5 x 4 x 3 x 2 x 1 = 720

The value of 0! is 1, according to the convention for an empty product.

Simple Program Copy Constructor Algorithm/Steps:

  • STEP 1:  Start the program.
  • STEP 2:  Declare the class name as CopyConstructor with data members and member functions.
  • STEP 3:  The constructor CopyConstructor() with the argument to assign the value.
  • STEP 4:  To call the function factorial_calculate() do the following steps (5 to 8).
  • STEP 5:  For i=1 to var
  • STEP 6:  Calculate fact*i to assign to fact.
  • STEP 7:  Increment the value as 1.
  • STEP 8:  Return the value fact.
  • STEP 9:  Create objects for CopyConstructor class in the main Function
  • STEP 10: Pass arguments using Constructor and Copy Constructor
  • STEP 11: Print the result.
  • STEP 12: Stop the program.

Simple Copy Constructor For Find Factorial Example Program

/*  Simple Copy Constructor For Find Factorial Example Program In C++ 
    Understanding Class and Constructors            */


using namespace std;

// CopyConstructor Class Declaration

class CopyConstructor {
   //Member Variable Declaration
   int var, fact;
   // Constructor definition

   CopyConstructor(int temp) {
      var = temp;

   //Member Function for calculate factorial value and return result

   int factorial_calculate() {
      fact = 1;
      for (int i = 1; i <= var; i++) {
         fact = fact * i;
      return fact;

//Main Function

int main() {
   int n;
   cout << "Simple Copy Constructor For Find Factorial Example Program In C++\n";

   cout << "\nEnter the Number : ";

   // Object Creation For Class and Initiate Value from the user input
   CopyConstructor obj(n);

   // Object Creation For Class with Copy Constructor
   CopyConstructor cpy = obj;

   // Calculate Factorial and Display results for Objects
   cout << "\n" << n << " Factorial is:" << obj.factorial_calculate();
   cout << "\n" << n << " Factorial is:" << cpy.factorial_calculate();

   // Wait For Output Screen
   return 0;

Sample Output

Simple Copy Constructor For Find Factorial Example Program In C++

Enter the Number : 5

5 Factorial is:120
5 Factorial is:120