Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling superclass method operator== [duplicate]

I'm going through a transition from Java to C++ and am trying to write a simple program.

There's a superclass Animal with the following inteface:

class Animal
{
public:
    Animal(int a, std::string n);

    bool operator==(Animal a);
private:
    int age;
    std::string name;
};

And it's subclass Dog:

class Dog : public Animal
{
public:
    Dog(int a, std::string n, double w);

    bool operator==(Dog d);
private:
    double weight;

};

My question is in regards to the Dog's operator== method, which compares 2 dogs.

Animal's operator== is below.

bool Animal::operator==(Animal a) //overriding of operator ==
{
return (age==a.age) && (name==a.name);
}

Now I want to write the Dog's version using Animal's method.

Like I'd do in Java:

boolean equals(Dog d){
    return (super.equals(d)) && (this.name==d.name); 
}

What I need is the c++ equivalent of (super.equals(d)) . If it was a method with a normal name it would be easy(Animal::equals(d)), but I don't know how to do it for operator==, which has a diferent syntax.

like image 745
Henrique Caldeira Avatar asked Aug 31 '26 19:08

Henrique Caldeira


1 Answers

It's actually surprisingly easy:

return Animal::operator==(d) && name==d.name;

The reason for using the superclass' name rather than super is that in C++ you can have multiple superclasses, so you have to be clear about which one you want.

Alternatively, you can call it via using it's overload:

return ((Animal&)*this)==d && name==d.name;

Since the paramters to operator== in this case would be an Animal& and a Dog&, then it can't match Dog::operator==(Dog d), and so uses Animal::operator==(Animal a) instead.

Note: Your signatures are highly unusual. Instead, use one of these:

bool operator==(const Animal& a) const;
friend bool operator==(const Animal& left, const Animal& right);

These don't make copies of animals each time you compare, and can compare const animals.

like image 146
Mooing Duck Avatar answered Sep 02 '26 10:09

Mooing Duck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!