Calling constructor from within member function?

I am trying to make a member function for my class that lets the user input all of the values for the object's variables. When I try to use the constructor inside this function, it does not assign anything new to the variables that were already initialized when the object itself was created. Is there a correct way to do this?

1
2
3
4
5
6
7
8
9
10
11
12
13
 25     void Administrator::get_all_data()
 26     {
 27         string a_name, a_number, a_title, a_department, a_supervisor;
 28         double a_salary;
 29         cout << "\nEnter name: "; cin >> a_name;
 30         cout << "Enter ssn: "; cin >> a_number;
 31         cout << "Enter title: "; cin >> a_title;
 32         cout << "Enter department: "; cin >> a_department;
 33         cout << "Enter supervisor name: "; cin >> a_supervisor;
 34         cout << "Enter weekly salary: "; cin >> a_salary;
 35         Administrator(a_name, a_number, a_salary, a_title, a_department, a_supervisor);
 36         cout << department;
 37     }


for example, when the function gets to line 36, I can see that department has not changed after the constructor call.
You cannot call constructors directly. If you do, you just create a new object (not alter the current one). Just assign the member fields manually one by one.
Ok, thank you webJose.
Another way to do it would be to copy the object:

1
2
3
4
5
void Administrator::get_all_data()
{
    // .. get all that stuff
    *this = Administrator(...);
}


This works by constructing a new temporary Administrator, then copying it to 'this' Adminstrator by using the assignment operator.
closed account (D80DSL3A)
Why do you cin to local variables? Why not cin to the data members directly?
eg: Instead of cout << "Enter department: "; cin >> a_department;
then trying to copy a_department to department
just make the assignment:
cout << "Enter department: "; cin >> department; and likewise for the other data members?

What am I missing here?

Sometimes I write a function that mirrors the constructor so I can conveniently assign the data member values. Two cases where this is useful:
1) An array of objects was allocated using the default constructor.
2) An objects values are to be re-assigned.
One reason to not read into the member variables directly, which is not accounted for in the above code, is to provide a strong exception guarantee.
Topic archived. No new replies allowed.