Copy constructors
Copy constructors are constantly used whenever the compiler has to create a temporary object of a class object. A copy constructor is used in the subsequent condition:
1. The initialization of an object through another object of the similar class.
2. Return of objects as a function value.
3. Beginning the object as by value parameters of a function
The general form is:
Class_name:: class_name(class_name &ptr)
here class_name is user defined class name and ptr
is a pointer for a class object class_name.
Commonly, the copy constructors take an object of their own class as arguments a produce like an object. A copy constructor generally does not return a function value as constructors cannot return any function values.
// program of fibonacci numbers by using copy constructors
# include<iostream.h>
class fibonacci
{
private:
long int f0,f1,fib;
public:
fibonacci ( )
{
f0 = 0;
f1 = 1;
fib = f0 + f1;
}
fibonacci ( fibonacci &ptr)
{
f0 = ptr.f0;
f1 = ptr.f1;
fib = ptr.fib;
}
void increment( )
{
f0 = f1;
f1 = fib;
fib = f0 + f1;
}
void display ( )
{
cout<<"fibonacci number = "<<fib<<'\t';
}
};
void main(void)
{
fibonacci number;
for (int i = 0; i<=10;++i)
{
number.display( );
number.increment ( );
}
}