Copy Constructor Basic Example in C++


This code defines a class Constructor that has an integer x as a data member and two constructors. The first constructor takes an integer argument a and initializes x to it. The second constructor takes a reference to an object of the same class type and initializes x to the value of x in the object being passed as argument. In the main function, an object a1 is created using the first constructor with the argument 20. Another object a2 is created using the second constructor with the argument a1, which makes a copy of a1 and initializes a2 with its value. Finally, the value of x in a2 is printed to the console. When the program is executed, it will print the value 20 to the console, which is the value of x in a2.

Source Code

#include<iostream>
using namespace std;
class Constructor
{
   public:
    int x;
    Constructor(int a)
    {
       x=a;
    }
    Constructor(Constructor &i)
    {
       x=i.x;
    }
};
int main()
{
  Constructor a1(20);
  Constructor a2(a1);
  cout<<a2.x;
  return 0;
}
To download raw file Click Here

Output

20

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