Keagansed Keagansed - 2 months ago 7
C++ Question

How do I call a child's overloaded operator from a function in the parent class which has a reference to the parent as a parameter?

How do I get an overloaded relational operator in a class to be called from a function in the parent class that is handed a const reference to a base class as a parameter? The following code demonstrates what I would like to do:

class Object
{
public:
virtual ~Object(void);
virtual int compare(Object const& obj) const;
};

int Object::compare(Object const & obj) const {
if(this == &obj)
{
return 0;
}
else if(this < &obj)
{
return -1;
} else{
return 1;
}
}

class Integer: public Object
{
private:
int myInt;
public:
Integer(int i);
bool operator==(const Integer& integer);
};

bool Integer::operator==(Integer const &integer) {
if(myInt == integer.myInt)
{
return true;
}
return false;
}


How do I get the compare function in the base class to call the == operator in the child class, keeping in mind I have other child classes as well?

I have tried dynamic_cast<> but for some reason it wont work.

Answer

You can add another virtual method isEqual to connect with the Integer::operator==.

The only requirement is to keep the Object::isEqual signature in the class Integer. You should also keep in mind that your Object::compare method can be (accidentally) called on objects of different types.

class Object 
{
protected:
    virtual bool isEqual(Object const& obj) const
      { return this == &obj; }
public:
    virtual ~Object(void);
    virtual int compare(Object const& obj) const;
};

int Object::compare(Object const & obj) const {
    if(isEqual(obj))
    {
        return 0;
    }
    else if(this < &obj)
    {
        return -1;
    } else{
        return 1;
    }
}

class Integer: public Object
{
private:
    int myInt;
protected:
    virtual bool isEqual(Object const& obj) const
      { if (!dynamic_cast<const Integer*>(&obj))
          return false;
        return *this == (const Integer&) obj;
      }
public:
    Integer(int i);
    bool operator==(const Integer& integer);
};