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,
- what happens to Action’s “user” attribute when setUser is called? is it destroyed? was it ever constructed?
- what happens if I call setUser for a second time?
- if I remove the “&” symbol in setUser, everything would be fine, right? because that would be like passing a copy of the parameter, right?
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.
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
utouser.No.
Yes.
The same thing.
As far as the assignment to
useris concerned, this would make no difference. Passing by reference simply means that no copy of the argument is made when the function is called.