C++ Copy Constructor


A copy constructor is used when the compiler has to create a temporary object of a class object.

The constructor can have any number of the parameters of the class may have a number of constructors overloaded.

The following situations Copy constructor used:-

  • The initialization of an object by another object of the same class.
  • Return of objects as function value.
  • Stating the object as by value parameter of a function.
C++ copyconstructor

Syntax:

class_name(class_name &ptr)

Example:

#include <iostream>   
using namespace std;  
class circle  
{  
   public:  
    int area;  
    circle(int radius) 
    {  
      area=3.14 * radius * radius;  
    }  
    circle(circle &ci) // copy constructor  
    {  
        area = ci.area;  
    }  
};  
int main()  
{  
    circle c(20);            
    cout << "Area of Circle: " << c.area << endl;
    circle c1(c);   //  Calling the copy constructor.  
    cout << "Area of Circle: " << c1.area;  
    return 0;  
}  



OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.