Question for reference: Why do I get a compilation error if I don't use the factor as a reference form in the copy generator part?

Asked 2 years ago, Updated 2 years ago, 113 views

class account
{
private:
    int accid;
    int balance;
    char *name;
public:
    account(int id, int money, const char* a)
        :accid(id), balance(money)
    {
        name = new char[strlen(a) + 1];
        strcpy(name, a);
    }
    account(const account &a)
    {
        accid = a.accid;
        balance = a.balance;
        name = new char[strlen(a.name) + 1];
        strcpy(name, a.name);
    }

};

I'm not sure why compilation errors appear if you don't reference the factor in the copy constructor portion of this object

call-by-reference c++

2022-09-20 11:16

1 Answers

The definition of a copy constructor itself must write &. If you don't write & when the definition is like this, the compiler will display an error because it's not what you define.

If the constructor's argument is in the same format as the class and the argument is passed in a reference format (&), it is called a copy constructor.

A similar type is called a move constructor when the constructor's arguments are in the same format as the class and are passed in the rvalue reference format (&&.

If there is no rule that must be specified in reference format, the value of the argument will be passed by value if the author writes it without &. But in general, classes don't store a single variable, they often have multiple variables, so copying these multiple variables by value significantly reduces their performance compared to reference.

For this reason, it is recommended that the class be delivered by reference unless there is a specific reason.


2022-09-20 11:16

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.