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;
}
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.
Advantages of copy constructor:-
- Copy constructors make it easy to copy objects.
- STL containers require all content to be copied and assigned.
- Copy constructors can be more efficient than copyfrom () solutions because they combine construction and replication.
Disadvantages of copy constructor:-
- An implicit copy of an object is one of the sources of error and performance problems in C + +.
- It also reduces the readability of the code and makes it difficult to track the delivery and changes in the object subroutine.
Tags
Copy constructor