| 1. |
What is a copy constructor? What is its significance? Which situation is it invoked in? Support your answer with examples. |
|
Answer» The copy constructor is a constructor which creates an object by initializing it with an object of the same class, which has been created previously. The copy constructor is used to: Initialize one object from another of the same type. Copy an object to pass it as an argument to a function. Copy an object to return it from a function. #include<iostream.h> #include<conio.h> class Example { int a,b; public: Example(int x,int y){ //Constructor with Argument a=x; b=y; cout<<"\nParameterized Constructor"; } void Display(){ cout<<"\nValues :"<<a<<"\t"<<b; } }; void main () { Example Object(10,20); Example Object2 = Object; //Copy Constructor Object.Display(); // Constructor invoked. Object2.Display(); getch(); } |
|