#include <iostream>
using namespace std;
class tester {
public:
int a;
tester( int x ) {
a = x;
}
tester( tester &t ) {
cout << t.a;
}
};
int main() {
tester t(10);
tester t_1(t);
}
output : 10
In definition of copy constructor what does t refer to ? From main when i passed t in the argument of t_1,it’s address got stored in the form &t in the copy constructor. What does t.a mean ?
In copy constructor
tis an reference to the object of the typetester.Copy constructor is a copying function.
It creates a copy of an object of an class, So it takes the object of that class an parameter. This copy constructor is called to create temporary copies of object during call by value in function calls etc.
Why this parameter is passed by Reference?
The reason that the parameter is passed as an reference in copy constructor is to avoid the recurssive calling of copy constructor if it was passed by value.(since copy constructor itself is the function which creates that temporary object)
What does
t.amean ?Since
tis an reference to the object of the typetester.t.ais the memberainsidethe classtesterfor the objecttbeing passed to the copy constructor.