开发者

what does ' t ' denote in copy constructor?

开发者 https://www.devze.com 2023-04-02 06:33 出处:网络
#include <iostream> using namespace std; class tester { public: int a; tester( int x ) { a = x; } tester( tester &t ) {
#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 ?


It's a reference to the existing object which is being copied to construct the new one. The copy constructor is expected to read the relevant fields from t as needed.

In your example, you probably want to copy the a field like this:

tester( tester &t ) {
   cout << t.a;
   a = t.a;
}


In copy constructor t is an reference to the object of the type tester.

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.a mean ?
Since t is an reference to the object of the type tester. t.a is the member a insidethe class tester for the object t being passed to the copy constructor.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号