Reputation: 1763
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.
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.
Upvotes: 3
Views: 2276
Reputation: 92391
You don't even have to make the assignment operator private, as the compiler will know not to generate one if there is a const member or a reference. These can't be reassigned.
Upvotes: 0
Reputation: 55882
References can be seen as pointers. The only difference is that you cannot change where the reference points to once it's been assigned. In your assignment operator, you are copying the content of the references not assigning the location where the reference points to.
For the compiler, the following classes are equivalent, notice that the pointer version derefence the pointers to copy the content:
class A_Ref{
public:
A_Ref(U& u):u_(u){}
A_Ref& operator=(const A_Ref& a){
u_ = a.u_;
return *this;
}
U& u_;
};
class A_Ptr{
public:
A_Ptr(U* u):u_(u){}
A_Ptr& operator=(const A_Ptr& a){
*u_ = *a.u_;
return *this;
}
U* u_;
};
Upvotes: 1
Reputation: 91330
does it mean that I can never use assignment operator whenever the class contains a reference member data?
You can have an assignment operator, you just cannot reassign the reference and therefore need to redefine the expected behavior of an assignment operator.
Upvotes: 1
Reputation: 131907
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).
Upvotes: 2
Reputation: 4048
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.
Upvotes: 2