Copy Constructor in C++

C++ProgrammingServer Side Programming

The copy constructor is a type of constructor. It creates an object and initializes it with an object of the same class. If the copy constructor is not defined in the class, the compiler itself defines one. A copy constructor is a must for a class that has pointer variables or dynamic memory allocations.

A program that demonstrates a copy constructor is as follows.

Example

 Live Demo

#include<iostream>
using namespace std;
class Demo {
   private:
   int num1, num2;
   public:
   Demo(int n1, int n2) {
      num1 = n1;
      num2 = n2;
   }
   Demo(const Demo &n) {
      num1 = n.num1;
      num2 = n.num2;
   }
   void display() {
      cout<<"num1 = "<< num1 <<endl;
      cout<<"num2 = "<< num2 <<endl;
   }
};
int main() {
   Demo obj1(10, 20);
   Demo obj2 = obj1;
   obj1.display();
   obj2.display();
   return 0;
}

Output

num1 = 10
num2 = 20

num1 = 10
num2 = 20

In the above program, the class Demo contains a normal parameterized constructor and a copy constructor. In addition to these, there is a function that displays the values of num1 and num2. These are given as follows.

class Demo {
   private:
   int num1, num2;
   public:
   Demo(int n1, int n2) {
      num1 = n1;
      num2 = n2;
   }
   Demo(const Demo &n) {
      num1 = n.num1;
      num2 = n.num2;
   }
   void display() {
      cout<<"num1 = "<< num1 <<endl;
      cout<<"num2 = "<< num2 <<endl;
   }
};

In the function main(), the class object obj1 is initialized using a parameterized constructor. The object obj2 is initialized using a copy constructor and the values of obj1 are copied into obj2. Finally the values of obj1 and obj2 are displayed. This is given below.

Demo obj1(10, 20);
Demo obj2 = obj1;
obj1.display();
obj2.display();
raja
Published on 09-Oct-2018 10:03:37
Advertisements