[December] 5.

Greetings and salutations!

My first visit here a few weeks ago was very helpful and friendly thanks to dkalita.

I’ve been moving forward on my own since then, but it appears I have run into another dilemma.

I have a short program listed below. It compiles fine.

The problem is that I would like the program to do one more thing, but I am at a loss on how to make it happen.

Here is the problem: I have an overloaded equality operator member function for the Student class. It currently does a fine job comparing the “myStudentId” data member of the two Student objects in the program. When I compare these two student objects, I would like it to compare the “myName” strings that are inherited from the Person class as well. Will someone please show me how I can compare “myName” & “myStudentId” of two Student objects in one fell swoop?

I have an overload equality function in the Person class, but it is currently empty.

Thank you!

// William Byrd II

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

class Person
{
public:
    Person(const string name)
    {
    myName = name;
    }
    
    bool operator==(const Person& p) const;

private:
    string myName;
};

// declares Student class as publicly inheriting from the Person class
class Student : public Person 
{
public:
    // implemented constructor for the Student class
    Student(const string name,
            const int studentId)
    : Person( name )
    {
        myStudentId = studentId;
    }
            
    // implemented overloaded equality operator Student class member function
    bool operator==(const Student& s) const
    {
    if ( myStudentId == s.myStudentId )
         
        return true;
    else
        return false;
    }

private:
    int myStudentId;
};

int main()
{
    Student app1( "William Byrd II", 8765309 );
    Student app2( "William Byrd II", 8765309 );
    
    // test overloaded == operator for Student class
    cout << "app1" << ( ( app1 == app2 ) 
        ? " == " : " != " ) << "app2"
        << " according to the overloaded == operator\n";
    
    system("pause");
    return 0;
}

Dani AI

Generated

A quick summary: gave the right, minimal fix — combine the base-class name comparison with the derived-class id comparison. Below are a few clearer, safer alternatives and best practices that help this pattern scale as your classes grow.

One tidy approach is to keep the base data private, add a read accessor, and compare both members in the derived operator==. Using std::tie keeps the comparison concise and orders the compared fields consistently:

#include <string>
#include <tuple>

class Person {
public:
    explicit Person(const std::string& n) : myName(n) {}
    const std::string& name() const { return myName; }
    virtual ~Person() = default;
private:
    std::string myName;
};

class Student : public Person {
public:
    Student(const std::string& n, int id) : Person(n), id_(id) {}
    bool operator==(const Student& s) const {
        return std::tie(name(), id_) == std::tie(s.name(), s.id_);
    }
private:
    int id_;
};

Extra recommendations:

  • Take strings by const std::string& and initialize members in the member initializer list (avoids extra copies).
  • Provide operator!= as return !(*this == other); for completeness.
  • If Person will be used polymorphically, give it a virtual destructor (shown above). For polymorphic equality semantics, prefer a virtual bool equals(const Person&) const pattern rather than making operator== virtual.
  • In modern C++ (C++20), consider defaulting comparisons (bool operator==(const T&) const = default;) when appropriate to reduce boilerplate.

Cautions: keep equality symmetric and transitive. Comparing the base by calling a base routine (as suggested) is fine — just be explicit about which fields belong to which class and avoid slicing by always binding to references.

Recommended Answers

All 5 Replies

Can you call Person::operator==(s) in the derived class and AND the results with your derived class comparison?

so like:

bool operator==(const Student& s) const
    {
    return (myStudentId == s.myStudentId && Person::operator==(s));
    }

EDIT: I did test it out and it seems to work.

[December] 5.

Thanks for your reply, jonsca . I’m not quite sure how to implement that. I tried.

If you or someone has the time, please copy and paste my program and insert what it is missing.

If I can see the complete, finished version, I will be able to learn from it. I just need to see it.

Thank you.

// William Byrd II

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

class Person
{
public:
    Person(const string name)
    {
    myName = name;
    }
    
    bool operator==(const Person& p) const
    {
	return (myName == p.myName);
    }

private:
    string myName;
};

// declares Student class as publicly inheriting from the Person class
class Student : public Person 
{
public:
    // implemented constructor for the Student class
    Student(const string name,
            const int studentId)
    : Person( name )
    {
        myStudentId = studentId;
    }
            
    // implemented overloaded equality operator Student class member function
    bool operator==(const Student& s) const
    {
    return (myStudentId == s.myStudentId && Person::operator==(s));
        //since we want a boolean anyway we don't need the if/else
    }

private:
    int myStudentId;
};

int main()
{
    Student app1( "William Byrd II", 8765309 );
    Student app2( "William Byrd II", 8765309 );
    
    // test overloaded == operator for Student class
    cout << "app1" << ( ( app1 == app2 ) 
        ? " == " : " != " ) << "app2"
        << " according to the overloaded == operator\n";
    
    cin.get();  //changed this from your system call
    return 0;
}

I had forgotten to mention that I fleshed out your base class == sorry about that

[December] 5.

Thanks, jonsca . I was going to edit my post and tell you that I figured it out thanks to your original post, but you beat me to it.

I appreciate your help. Thanks for looking out.

Never a prob. Good luck with it.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.