C++ program outputs a very large number instead of object

Viewed 78

This is my homework and I have no clue why it's outputting this number.

This is the program

#include <iostream>
#include <vector>
using namespace std;

class Employee
{
protected:
    long empId;
    string empName;
    string email;
public:
    Employee(){}
    Employee(long i, string n){empName = n; empId = i; email = "Unknown";}
    friend istream& operator>>(istream& in, const Employee& emp);
    friend ostream& operator<<(ostream& out, const Employee& theQ);
};

class Student
{
protected:
    long stId;
    int year;
    string email;
    string schoolName;
public:
    Student(){}
    Student(long i, int y, string sn){stId = i; year = y; email = "Unknown"; schoolName = sn;}
    friend istream& operator>>(istream& in, const Student& stu);
};

template <class T>
class Queue {
    vector<T> theQ;
public:
    void Push(T item)
    {
        theQ.push_back(item);
    }

    T Pop() {
        theQ.pop_back();
    }

    void ReadAnItem()
    {
        T item;
        cout << "Enter the data please." << endl;
        cin >> item;
        Push(item);
    }

    void PrintQ() {
        cout<< "The content of the array is as follows: " << endl;
        for (int i=0; i< theQ.size(); i++)
            cout << theQ[i] << endl;
    }
};

ostream& operator<<(ostream& out, const Employee& emp){

    out << emp.empId << endl;
    out << emp.empName << endl;
    out << emp.email << endl;

    return out;
}

istream& operator>>(istream& in, const Employee& emp) {

    long i;
    string n;
    cout << "Enter employee ID: ";
    in >> i;
    cout << "Enter employee name: ";
    in >> n;
    Employee(i, n);

    return in;
}

istream& operator>>(istream& in, const Student& stu) {

    long i;
    int y;
    string sn;
    cout << "Enter student ID: ";
    in >> i;
    cout << "Enter student year: ";
    in >> y;
    cout << "Enter student school name: ";
    in >> sn;
    Student(i, y, sn);

    return in;
}


int main() {

    Queue<Employee> emp1;
    emp1.ReadAnItem();
    Queue<Student> stu1;
    stu1.ReadAnItem();

    emp1.PrintQ();

    return 0;
}

And the output

The content of the array is as follows:
140734799804080

Outputting the data seems to be working just fine. I have a feeling the error is coming from the operator overloads. I'm not very sure, I've been perplexed for a couple hours now.

Where am I going wrong?

1 Answers

The problem appears to be in your operator>> function. You're not assigning anything to the emp parameter. Try:

istream& operator>>(istream& in, Employee& emp) {

    ...
    emp = Employee(i, n);

    return in;
}

The assignment to emp is required to actually return the data you just constructed. I also had to remove const from your declaration because you need to be able to write to emp.

Related