Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

copy
constructor
c++
classes

Copy constructor in C++

Educative Answers Team

A copy constructor is a method of a class which initializes an object using another object of the same class. A copy constructor can be called in various scenarios. For example:

  • In the case where an object of a class is returned by value.
  • In the case of an object of a class being passed, by value, ​to a function as an argument.

A copy constructor can also be defined by a user; in this case, the default copy constructor is not called.

A user-defined copy constructor is generally needed when an object owns pointers or non-shareable references to a file (for example).

Syntax

A copy constructor has the following function declaration:

svg viewer

The object to a copy constructor is always passed by reference.

If the object is passed by value, then its copy constructor will be invoked and it would be stuck in an infinite recursion.

Code

The following ​snippet illustrates an example of a copy constructor defined in the class Coordinate.

#include<iostream> 
using namespace std; 

class Coordinate 
{ 
  private: 
    int x_cor, y_cor; 

  public: 

    // default constructor
    Coordinate(int x, int y) 
    { 
      x_cor = x;
      y_cor = y;
    } 

	// Copy constructor 
	Coordinate(const Coordinate &cor) 
  {
    // Note how you can access the private attributes of
    // the object class in the copy constructor,
    x_cor = cor.x_cor;
    y_cor = cor.y_cor;
  } 

	int get_x_cor(){
    return x_cor; 
  }
  	

	int get_y_cor(){
    return y_cor; 
  }
}; 

int main() 
{ 
  // default constructor called here
	Coordinate cor1(2, 4); 

  // Copy constructor is called here 
	Coordinate cor2 = cor1; 

	// Showing results 
	cout << "cor1 = (" << cor1.get_x_cor() << "," << cor1.get_y_cor() << ")" << endl; 
	cout << "cor2 = (" << cor2.get_x_cor() << "," << cor2.get_y_cor() << ")" << endl; 
	

	return 0; 
}

RELATED TAGS

copy
constructor
c++
classes
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring