Search code examples
c++memory-managementoperator-overloadingistreamdynamic-allocation

Overloading istream operator with dynamic memory allocation


Hello so I am confused with my istream& operator>>. I have to overload this operator to take input for a class that is using dynamic memory allocation for a C string.

My Employee.h file is

#include <iostream>
using namespace std;

const double MIN_WAGE = 10.25;

class Employee {

int num;
char * name;
double rate;

public:

Employee();
Employee(const Employee&);
Employee operator=(const Employee&);
friend istream& operator>>(istream& is, Employee& employee);
friend ostream& operator<<(ostream& is, const Employee& employee);
friend bool operator>(const Employee& a, const Employee& b);
~Employee();
};

I have a copy constructor which called the assignment operator

Employee::Employee(const Employee & e) {

name = NULL;

*this = e;
}

Employee Employee::operator=(const Employee & e) {

if (this != e) {

    num = e.num;
    rate = e.rate;

    if (name != NULL) delete [] name;

    if (e.name != NULL) {
        name = new char[strlen(e.name) + 1];
        strcpy(name, e.name);
    }

    else name = NULL;
}

return *this;

}

And in the assignment operator I have dynamically assigned memory for the length of the C string I am using. My istream function so far:

istream& operator>>(istream& is, Employee & e) {

int n;
double r;
}

My question is: how do I use the new dynamic memory allocation in my assignment operator in my istream function?


Solution

  • Disclaimer: both solution are for educational purpose and I would not recommend to use it in any real program. If you need to solve homework with strict requirements, then that maybe ok:

    First:

    istream& operator>>(istream& is, Employee & e) {
        Employee tmp;
        tmp.name = new char[1024];
        is >> tmp.num >> tmp.rate >> tmp.name;
        e = tmp;
        return is;
    }
    

    Second - more ugly and more "effective" solution:

    istream& operator>>(istream& is, Employee & e) {
        char buffer[1024];
        Employee tmp;
        tmp.name = buffer;
        is >> tmp.num >> tmp.rate >> tmp.name;
        e = tmp;
        tmp.name = 0;
        return is;
    }
    

    Again both solution created under condition "to use existing assignment operator", real code should be different.

    Note:

    if (name != NULL) delete [] name;
    

    is redundant, write

    delete [] name;
    

    instead