Copy constructor is a special constructor in C++ which can construct from and existing object. If the class do not declare a copy-constructor then compiler will create one automatically. This constructor is called by compiler whenever a new object is getting created and compiler takes care to pass the existing object in parameter.
Class MainFunda;
MainFunda a1; // Default constructor called
MainFunda a2 = a1; // Copy-Constructor called
MainFunda a3(a1); // Copy-Constructor called
The signature of copy constructor
MainFunda(const MainFunda& rhs);
Two things to be noted regarding parameter rhs (rhis is existing object):
- The parameter rhs is of reference type
- The parameter rhs is of const type
If the parameter rhs is not declared as reference type format and then whenever a copy constructor is called, it will be called using pass-by-value format, which means the parameter rhs will be constructed afresh from existing object on call stack. This is nothing but asking the compiler to call a copy constructor recursively. In this way the copy constructor will call itself endlessly and program will fill the available stack.
Example, a copy constructor like this will generate an error
#include <iostream> //main header
using namespace std; //for namespace
class MainFunda
{
public:
MainFunda( MainFunda rhs)
// parameter is pass by value
{
cout << "MainFunda(copy-constructor)"
<< endl;
}
};
int main()
{
return 0;
}
Compiler error is generated is as follows:
Copy from temporary object : Secondly, the type of rhs is const, this is needed so that copy constructor can be called when creating an object with a temporary object.
Example, the following constructor will throw a compiler error:
MainFunda( MainFunda& rhs) //non-const reference
{
cout << "MainFunda(copy constructor)" << endl;
}
The following initializations still work:
MainFunda a1;
MainFunda a2 = a1; //This will still work
However, in following statement, the function getSomeExistingObject() returns a temporary object of type “MainFunda” and initializations will happen from this temporary object. Therefore, copy-constructor will get reference to temporary object through a non-const parameter. Since, the compiler always treat a temporary object as constant therefore following code will not work:
MainFunda a3 = getSomeExistingObject(); //This will NOT work
The compiler will throw the error: