Copy Constructor Example in C++


Description:

The copy constructor is a constructor which creates an object by initializing it with an object of the same class, which has been created previously. The copy constructor is used to −

  • Initialize one object from another of the same type.
  • Copy an object to pass it as an argument to a function.
  • Copy an object to return it from a function.

If a copy constructor is not defined in a class, the compiler itself defines one.If the class has pointer variables and has some dynamic memory allocations, then it is a must to have a copy constructor

Example Program:

Find out the area of rectangle using copy constructor in C++

Source Code

#include<iostream>
using namespace std;
class Rectangle
{
private:
    int a;
    int *p;
public :
    Rectangle(int l) //Parameterized Constructor
    {
        a=l;
        p=new int[a];
    }

    Rectangle(Rectangle &o2)
    {
       a=o2.a;
       //p=o2.p; //Not Working
       p=new int[a];
    }

    ~Rectangle(){
    cout<<"Deallocated";
    }
};
int main()
{
    Rectangle o1(5),o2(o1);
    return 0;
}
To download raw file Click Here

Output

DeallocatedDeallocated

Basic Programs


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



Learn All in Tamil © Designed & Developed By Tutor Joes