Reputation: 1146
In this simplified example, my question is: am I doing a legal assignment inside Action::setUser()?
class User {
private:
int age;
public:
int getAge() { return age; }
};
class Action {
private:
User user;
public:
void setUser(User &u) {
user = u;
}
};
int main() {
User u;
Action a;
a.setUser(u);
return 0;
}
What makes me noise is,
I'm worried that I'm doing crazy things with memory because attribute is not being correctly destroyed...
Thank you
Edited on Mon Feb 18, 2013
Thank you so much! I really appreciate all of your responses...
I didn't know the compiler provided a default overloaded assignment operator. Now I that know everything makes perfect sense...
Thanks again.
Upvotes: 2
Views: 1116
Reputation: 42083
class Action {
private:
User user;
}
defines an private member of type User
. It is an object with automatic storage duration, that it constructed while object of type Action
is being constructed. It's lifetime is tied to the lifetime of an object of type Action
.
Now in this method:
void setUser(User &u) {
user = u;
}
u
is a reference to the object whose attributes (members) will be used to set attributes of user
by using the assignment operator.
And if you remove &
here, you will change passing by reference to passing by value, which means that copy of object passed to this method will be created upon its call.
Upvotes: 1
Reputation: 17415
Answers:
&
, you would pass a copy. It doesn't make things wrong or right though.Notes:
Upvotes: 1
Reputation: 490108
Yes, it's fine. It's just assigning from u
that you've defined in main directly to a.user
. The reference parameter avoids making an extra copy to pass to a.setUser
.
When you create an Action
it contains a default-constructed User
object. You're then assigning a value to that User
. This isn't (IMO) the best design (I'd rather see the User
constructed with the correct value) but it's all entirely valid.
The assignment does nothing to create or destroy the existing value. The Action
object will be destroyed when it goes out of scope, and that will destroy the User
object it contains.
Upvotes: 1
Reputation: 272487
what happens to Action's "user" attribute when setUser is called?
The assignment operator (provided by the compiler, as you haven't defined a custom one) is called, which simply performs a member-wise copy from u
to user
.
is it destroyed?
No.
Was it ever constructed?
Yes.
what happens if I call setUser for a second time?
The same thing.
if I remove the "&" symbol in setUser, everything would be fine, right?
As far as the assignment to user
is concerned, this would make no difference. Passing by reference simply means that no copy of the argument is made when the function is called.
Upvotes: 4