Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

when should we make assignment operator private and don’t implement

This is an old examination question which asks us to write assignment operators and copy constructors, destructors when that make sense.

Given the following code:

class U { /* code not specified here */ };
class A { /* code not specified here */ private: U& u_; };

I learned the Answer is: A holds a C++ reference to an instance of U, which can be copied but cannot be reset. Therefore you must:

• Write a copy constructor that initializes its U to the same instance referenced by the A source instance.

• Make its assignment operator private and don’t implement

I know that reference can not be reset. However, does it mean that I can never use assignment operator whenever the class contains a reference member data? Does the following code make any sense? The following code is written by myself(it is not the answer)

  class U{
    public:
        int u;
    };

    class A{
    public:
        A(U& u):u_(u){}
        A& operator=(const A& a){
            u_ = a.u_;
            return *this;
        }
        U& u_;
    };

    int main(){
        U u1;
        U u2;
        A a1(u1);
        A a2(u2);
        a1 = a2;
        a1.u_.u = 1;
        a2.u_.u = 2;
        cout << "a1.u_.u : " << a1.u_.u << endl;
        cout << "a2.u_.u : " <<  a2.u_.u << endl;
    }

Thanks in advance.

like image 957
Gin Avatar asked Mar 22 '26 17:03

Gin


2 Answers

References can't be changed to reference something else. However you can do what you do here because doing :

u_ = a.u_;

in reality changes the value that is referenced. It does note change which value is referenced.

like image 160
fouronnes Avatar answered Mar 25 '26 07:03

fouronnes


A& operator=(const A& a){
    u_ = a.u_;
    return *this;
}

Won't work as expected, the U the reference points to will get assigned.
Of course you can implement an assignment operator even if the class contains a reference, as long as that reference can be assigned (what if the referenced class has operator= only privat?) and the reference isn't const U& (thus can't be assigned).

like image 40
Xeo Avatar answered Mar 25 '26 05:03

Xeo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!