Constructor Deep Copy Example in C++


This program defines a class Example which has three member variables: a, b, and p. The constructor of the class initializes the pointer variable p to point to a dynamically allocated integer. The setExample() method sets the values of a, b, and *p to the passed arguments. The showExample() method displays the values of a, b, and *p.

The program creates an instance of Example named e1, sets its member variables, and then creates a second instance named e2 by copying e1. The values of e1 are then displayed using the showExample() method of e2.

Note that when the copy constructor is called, it performs a deep copy of the dynamically allocated integer pointed to by p by creating a new integer and copying the value of the original integer to it. This is necessary to ensure that each instance of the class has its own separate copy of the integer.

Source Code

#include<iostream>
using namespace std;
class Example
{
  public:
  int a;
  int b;
  int *p;
  Example()
  {
    p=new int;
  }
  Example(Example &d)
  {
    a = d.a;
    b = d.b;
    p = new int;
    *p = *(d.p);
  }
  void setExample(int x,int y,int z)
  {
    a=x;
    b=y;
    *p=z;
  }
  void showExample()
  {
    std::cout<<"value of a is : "<<a<<std::endl;
    std::cout<<"value of b is : "<<b<<std::endl;
    std::cout<<"value of *p is : "<<*p<<std::endl;
  }
};
int main()
{
  Example e1;
  e1.setExample(4,5,7);
  Example e2=e1;
  e2.showExample();
  return 0;
}
To download raw file Click Here

Output

value of a is : 4
value of b is : 5
value of *p is : 7

Program List


Flow Control

IF Statement Examples


Switch Case


Goto Statement


Break and Continue


While Loop


Do While Loop


For Loop


Friend Function in C++


String Examples


Array Examples


Structure Examples


Structure & Pointer Examples


Structure & Functions Examples


Enumeration Examples


Template Examples


Functions


Inheritance Examples

Hierarchical Inheritance


Hybrid Inheritance


Multilevel Inheritance


Multiple Inheritance


Single Level Inheritance


Class and Objects

Constructor Example


Destructor Example


Operator Overloading Example


Operator and Function Example


List of Programs


Pointer Examples


Memory Management Examples


Pointers and Arrays


Virtual Function Examples