TCS Placement: Sample Questions 217 - 217 of 502

Get unlimited access to the best preparation resource for competitive exams : get questions, notes, tests, video lectures and more- for all subjects of your exam.

Question 217

Question

MCQ▾

Which constructor function is designed to copy objects of the same class type?

Choices

Choice (4)

a.

Object constructor

b.

Dynamic constructor

c.

Copy constructor

d.

Create constructor

Answer

c.

Explanation

  • Copy constructor copies objects of the same class type
  • A copy constructor is a member function which initializes an object using another object of the same class.
  • Copy constructor is called when a new object is created from an existing object, as a copy of the existing object.
  • Assignment operator is called when an already initialized object is assigned a new value from another existing object.
  • Copy constructor has the following general prototype:

    ClassName (const ClassName &old_obj) ;

  • Example of copy constructor
  1. #include<iostream>
  2. usingnamespacestd;
  3. classPoint
  4. {
  5.     private:
  6.     intx, y;
  7.     public:
  8.     Point(intx1, inty1) { x =x1; y =y1; }
  9.     // Copy constructor
  10.     Point(constPoint &p2) {x =p2.x; y =p2.y; }
  11.     intgetX() { returnx; }
  12.     intgetY() { returny; }
  13. };
  14. intmain()
  15. {
  16.     Pointp1(20, 78); // Normal constructor
  17.     Pointp2 =p1; // Copy constructor
  18.     cout ≪ "p1.x =" ≪ p1.getX() ≪ ", p1.y =" ≪ p1.getY();
  19.     cout ≪ "p2.x =" ≪ p2.getX() ≪ ", p2.y =" ≪ p2.getY();
  20.     return0;
  21. }
  • Output:

p1. x = 20 , p1. y = 15

p1. x = 20 , p1. y = 15

Developed by: