Question

I'm having trouble figuring out how to properly overload the '=' operator to assign one student's information to another's for one of my assignments. I'm new to this, so I could have messed it up big time. Thanks for any help!

#include <iostream>

using namespace std;

class Student
{
    public:
        void input()
        {
            cout << "Please enter student's name: ";
            cin >> name;
            cout << "Please enter the number of classes " << name << " is taking: ";
            cin >> numClasses;
            classList = new string[numClasses];
            cout << "Please enter the list of classes " << name << " is taking: ";
            for(int i = 0; i < numClasses; i++)
            {
                cin >> classList[i];
            }
        }
        void print()
        {
            cout << "Student's name: " << name << endl;
            cout << "Number of classes " << name << " is taking: " << numClasses << endl;
            cout << "List of classes " << name << " is taking: " << endl;
            for(int i = 0; i < numClasses; i++)
            {
                cout << classList[i] << endl;
            }
        }
        void resetClasses()
        {
            name.clear();
            numClasses = 0;
            delete [] classList;
        }
        Student operator= (Student s)
        {
            Student temp;
            temp.name = s.name;
            temp.numClasses = s.numClasses;
            temp.classList = s.classList;
            return temp;
        }
    private:
        string name;
        int numClasses;
        string *classList;
};


int main()
{
    Student s1, s2;

    s1.input();
    cout << "Student 1's data:" << endl;
    s1.print();

    s2 = s1;
    cout << endl << "Student 2's data after assignment from student 1: " << endl;
    s2.print();

    s1.resetClasses();
    cout << endl << "Student 1's data after reset:" << endl;
    s1.print();

    cout << endl << "Student 2's data, should still have original classes: " << endl;
    s2.print();
}
Was it helpful?

Solution

The correct way to implement the assignment operator is to use

Student& operator=(const Student& s){
    if (&s != this){
        this->name = s.name;
        /*etc for all members*/
    }
    return *this;
}

A few things to note:

  1. The s to copy is passed by constant reference. That means that it does not take a deep copy nor is allowed to be modified by the function.

  2. Return *this allows you to do multiple assignments: a = b = c;

  3. The if statement circumvents any problems arising from self-assignment.

  4. Pay special attention to the copying of classList. Ensure a deep copy is taken.

But It's far better to use the standard template library containers so you can rely on the compiler-generated assignment operator.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top