WHAT IS COPY CONSTRUCTOR IN C++

 Que - What is copy constructor?

Ans- Copy constructor is a member function that initializes an object using another object of the same class. 



Example of copy constructor:-

#include<iostream>
using namespace std;

class krishna
{
   int num1 ;
   public:
   void getdata (int x)
   {
     num1=x;
   }
  
   void display ()
   {
       cout<<"entered number is:- "<<num1<<endl;
   }
};
int main ()
{
   int num1 ;
   cout<<"enter a number:- ";
   cin>>num1;
  krishna ob1 ;
  ob1.getdata(num1);
  ob1.display();

  krishna ob2 (ob1); // copy constructor
  ob2.display ();
  
    return 0;
}

Result:-


When is the copy constructor called? 
In C++, a Copy Constructor may be called in the following cases: When an object of the class is returned by value. 

  • When an object of the class is passed (to a function) by value as an argument. 
  • When an object is constructed based on another object of the same class. 
  • When the compiler generates a temporary object.
If we don’t define our own copy constructor, the C++ compiler creates a default copy constructor for each class which does a member-wise copy between objects. The compiler-created copy constructor works fine in general. We need to define our own copy constructor only if an object has pointers or any runtime allocation of the resource like file handle, a network connection, etc.

Advantages of copy constructor:-

  1. Copy constructors make it easy to copy objects.
  2.  STL containers require all content to be copied and assigned. 
  3. Copy constructors can be more efficient than copyfrom () solutions because they combine construction and replication.

Disadvantages of copy constructor:-

  1. An implicit copy of an object is one of the sources of error and performance problems in C + +. 
  2. It also reduces the readability of the code and makes it difficult to track the delivery and changes in the object subroutine.




Post a Comment

Previous Post Next Post