Copy Constructor in C++

Copy Constructor c++ OPP

    The copy constructor is a constructor that initializes a object with the data values of      another  object is called copy constructor.

    The copy constructor is used to:

  • ·        Copy constructor takes one parameter of its  class &object.
  • ·        Copy an object to pass it as an argument to a function.
  • ·        Copy an object to return it from a function. 

Syntax/ The most common form of copy constructor is shown here −

Class-name (class-name &obj)

{

        // body of copy constructor

}

 

A program that copy constructors is given as follows.

#include<iostream>

using namespace std;

class C {

        private:

      int i;

    public:

       C()      

       {

           i=10;

           cout<<"  Default Constructor!! " <<endl;

        }

       C(C &s)     //Copy constructor

       {

           i=s.i;

          cout<<"The Value of  i = " <<i;

       }

 };

int main(){

        C x;               //constructor call

        C a(x);         // copy constructor call

    // C b=x;         // copy constructor call

}

 

 

Output

Default Constructor!!
The Value of i =10

 

Example No.2  Copy Constructor

#include<iostream>
using namespace std;
class disk {
           private:
      int feet;
      float inch;
    public: 
      disk(){ }
       disk(int f, float in)       
       {
           feet=f; 
           inch=in;
        } 
       disk(disk &s)     //Copy constructor
       {
           feet =s.feet;
          inch = s.inch;
             cout<<"Copy Constructor called!! " <<endl;
       }
        void show(){
          cout<<"The Feet = " <<feet<<endlt;
          cout<<"The inch = " <<inch;
        }
 };
int main(){
        disk d1(5,7) ;               //paramerized constructor call
        disk d2=d1;       // copy constructor call
        d2.show();        
}

 

 

Output

Copy Constructor called!!
The Feet= 5
The inche= 7

 

 

Post a Comment

0 Comments

Close Menu