Copy Constructor Shallow Copy Example in C++


This program defines a class Example with three private member variables a, b, and p, and three public member functions setExample(), showExample(), and the default constructor. The default constructor initializes the pointer p to a new integer on the heap. The setExample() function takes three integer arguments and assigns them to the member variables a, b, and *p. The showExample() function displays the values of a, b, and *p to the console.

In main(), an instance of Example class e1 is created using the default constructor. Then, the setExample() function is called on e1 with the values 4, 5, and 7 as arguments. Another instance of Example class e2 is created and initialized with e1 using the copy constructor. Finally, the showExample() function is called on e2, which displays the values of a, b, and *p of e2. Therefore, this program demonstrates the use of a copy constructor to create a deep copy of an object.

Source Code

#include<iostream>
using namespace std;
class Example
{
  int a;
  int b;
  int *p;
  public:
    Example()
    {
       p=new int;
    }
    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