In student.h file
class Student {
protected:
string Name;
int Stu_num;
public:
virtual void print() = 0;
// constructor...
}
class Grad_Student: public Student {
private:
string Lab;
public:
void print();
// constructor...
}
class Undergrad_Student: public Student {
private:
string Major;
public:
void print();
// constructor...
}
in student.cpp file
bool operator == (const Student& x, const Student& y) {
if (typeid(x) != typeid(y)) return false;
else // dosomething..
}
I want to compare child of Student class; Grad and Undergrad. in main.cpp when i comapre two student class, it doesn't work..
Grad_Student grad1 = Grad_Student("Max", 11, "Hubo");
Student *std1 = &grad1;
Grad_Student grad2 = Grad_Student("Max", 11, "Hubo");
Student *std2 = &grad2;
cout << (std1 == std2) << endl; // it always prints 0.
cout << (*std1 == *std2) << endl;
// I think this line should work, but makes error.
// error: invalid operands to binary expression ('Student' and 'Student')
Should i overload operator== in student class? give me a hint...
So, your overloaded equality operator does nothing... You need to compare something in the body and return a boolean
result.
Also, your Undergrad_Student
currently doesn't derive from Student
..
Furthermore, since you're comparing 2 Student
objects you can just make the equality operator overload a member function taking 1 argument.
Something like this:
class Student {
public:
explicit Student( int id )
: id_{ id }
{ }
bool operator==( const Student& other ) const {
return id_ == other.id_;
}
virtual void print() const = 0;
virtual ~Student( ) = default;
protected:
int id_;
};
class Grad: public Student {
public:
explicit Grad( int id )
: Student{ id }
{ }
void print() const override {}
};
class Undergrad : public Student {
public:
explicit Undergrad( int id )
: Student{ id }
{ }
void print() const override {}
};
int main( ) {
Grad s1{ 11 };
Undergrad s2{ 12 };
// Prints false.
std::cout << std::boolalpha << ( s2 == s1 ) << '\n';
Grad s3{ 42 };
Undergrad s4{ 42 };
// Prints true.
std::cout << std::boolalpha << ( s3 == s4 ) << '\n';
}