A Program based on concept of copy constructor() :-


#include<iostream.h>
#include<conio.h>

class student
{
int roll;
int marks;
public:
student(int m,int n)
{
roll=m;
marks=n;
}
student(student &t);
void showdetails()
{
cout<<" Roll no:"<<roll<<endl;
cout<<" Marks:"<<marks;
}
};
student::student(student &t)
{
roll=t.roll;
marks=t.marks;
}
int main()
{
clrscr();
cout<<"\n Parameterised Constructor Output:"<<endl;
student r(60,130);
r.showdetails();
cout<<endl<<"Copy Constructor Output:"<<endl;
student stu(r);
stu.showdetails();
getch();
}

Output:


Parameterised Constructor Output:
Roll no:60
Marks:130
Copy Constructor Output:
Roll no:60
Marks no:130

			

When is copy constructor called?

In C++, a Copy Constructor may be called in following cases:

1. When an object of the class is returned by value.
2. When an object of the class is passed (to a function) by value as an argument.
3. When an object is constructed based on another object of the same class.
4. When the compiler generates a temporary object.

It is however, not guaranteed that a copy constructor will be called in all these cases, because the C++ Standard allows the compiler to optimize the copy away in certain cases, one example being the return value optimization (sometimes referred to as RVO).

References:-
# Wikipedia (click here)
# Fredosaurus (click here)
Previous Next