Computer Science, asked by roshangupta7547, 1 year ago

What is a copy constructor? Illustrate with a suitable C++ example.

Answers

Answered by shaivaj67
1
heya

here's ur answer

A copy constructor is a member function which initializes an object using another object of the same class. A copy constructor has the following general function prototype

Following is a simple example of copy constructor.

#include<iostream>

using namespace std;

  

class Point

{

private:

    int x, y;

public:

    Point(int x1, int y1) { x = x1; y = y1; }

  

    // Copy constructor

    Point(const Point &p2) {x = p2.x; y = p2.y; }

  

    int getX()            {  return x; }

    int getY()            {  return y; }

};

  

int main()

{

    Point p1(10, 15); // Normal constructor is called here

    Point p2 = p1; // Copy constructor is called here

  

    // Let us access values assigned by constructors

    cout << "p1.x = " << p1.getX() << ", p1.y = " << p1.getY();

    cout << "\np2.x = " << p2.getX() << ", p2.y = " << p2.getY();

  

    return 0;

}

Output:

p1.x = 10, p1.y = 15 p2.x = 10, p2.y = 15

hope it helps

mark me brainliest plss
Answered by khushboo4068
0

Answer:

a copy constructor is a special constructor in c++ used to create a new object as a copy of existing one

Explanation:

example-:

#include <iostream .h>

class school

{

int i,j;

public:

school (school&s)

{

i=s.i;

j=s.j;

}

}

Similar questions