DELHI 1998:
2.a) What is a copy constructor? What do you understand by constructer overloading?
Ans: copy constructor is a constructor of the form classname(classname &). The compiler will use the copy constructor whenever you initialize an instance using values of another
instance of same type.
Eg:
Sample S1;
//Default constructor used
Sample S2 = S1;
//Copy constructor used. Also
//Sample S2(S1);
In the above code, for the second statement,the compiler will copy the instance S1 to S2
member by member. If you have not defined a copy constructor, the compiler automatically,
creates it and it is public.
A copy constructor takes a reference to an object of the same class an argument.
Constructor Overloading:
With same constructor name, having several definitions that are differentiable by the number or types of their arguments(ie Parameterized, non-parameterized and copy constructors) is known as an overloaded constructor and this process is known as constructor overloading.Constructor overloading implements polymorphism.
An Example using Constructor Overloading:
#include<iostream.h>
#include<conio.h>
class Circle
{ float r,a; //r and a are private
public:
Circle() //Non parameterized or Default Constructor
{ r=0.0; a=0.0; }
Circle(float rad) //Parameterized Constructor
{ r = rad;
a = 3.1415*r*r;
}
Circle(Circle &obj) //Copy Constructor
{ r = obj.r;
a = obj.a;
}
~Circle()
{ cout<<"\nThe object is being
destroyed...."; }
void take()
{ cout<<"Enter the value of Radius: ";
cin>>r;
}
void calculate()
{ a = 3.1415*r*r; }
void display()
{ cout<<"\nThe Radius of the Circle = "<<r;
cout<<"\nThe Area of the Circle = "<<a;
}
};void main()
{ clrscr();
Circle c1; /*Default Constructor will be called implicitely.ie c1.r = 0.0 and c1.a = 0.0 */
Circle c2(10.3); //Parameterized
//Constructor will be called mplicitely Circle c3(c2);
//Copy Constructor will be called implicitely
c1.take();
c1.calculate();
c1.display();
c2.display();
c3.display();
getch();}
CBSE Computer Science Solved Revision Tour By Mr. Ravi Kiran ( [email protected] )