operator overloading abstract class

  abstract, c++, inheritance, operators, overloading

There is an Student abstract class, and two derived class Grad and Undergrad; and I want to overload operator in several ways.

student.h

class Student {
    protected:
    string Name;
    int Stu_num;
 
    public:
    virtual void print() = 0;
    bool operator==(const Student& x) const;

    // constructor...
}

class Grad_Student : public Student {
    private:
    string Lab;

    public:
    void print();
    bool operator==(const Grad_Student& x) const;
 
    // constructor...
}

class Undergrad_Student : public Student {
    private:
    string Major;

    public:
    void print();
    bool operator==(const Undergrad_Student& x) const;
  
    // constructor...
}

student.cpp

bool Student::operator==(const Student& x) const {
    if (this->Name == x.Name && this->Stu_num == x.Stu_num) {
        if (typeid(*this).name() != typeid(x).name()) {
            return false;
        }
        else if (!(strcmp(typeid(*this).name(), "12Grad_Student"))) {
            return *dynamic_cast<const Grad_Student *>(this) == *dynamic_cast<const Grad_Student *>(&x);
        } 
        else {
            return *dynamic_cast<const Undergrad_Student *>(this) == *dynamic_cast<const Undergrad_Student *>(&x);
        }
    } 
    else {
        return false;
    }
}

bool Grad_Student::operator==(const Grad_Student& x) const {
    return this->Lab == x.Lab;
}

bool Undergrad_Student::operator==(const Undergrad_Student& x) const {
    return this->Major== x.Major;
}

To find student object in Student *students[300]
this operation == overloading works and doen’t have problem,
but I want to implement overloading in different way using below.
How can I implement this function??

bool operator==(const Student& x, const Student& y)
{
    // do comparison...
}

Source: Windows Questions C++

LEAVE A COMMENT