Defaulted operator== causing recursion

Viewed 86

The following code causes an infinite recursion in the Base::operator== method - I think it is due to the fact that it is defaulted. If i have a trivial return true there, it works just fine. Why is this happening? Any easy way to check what the compiler is doing in terms of the implementation? I think it is calling the base::operator== which causes an infinite recursion.

#include <cstdint>
#include <cstdio>
#include <memory>
#include <vector>
#include <iostream>

class Base;
class Super;

class Base {
public:
    bool operator==(const Base& rhs) const;
    virtual ~Base() = default;

};

class Super : public Base {
public:
    bool operator==(const Super& rhs) const = default;
    // making this the impl works!
    //{
    //    return true;
    //}

};

bool Base::operator==(const Base& rhs) const {
    std::cout << "Called Base==" << std::endl;

    // assume it's Super
    const Super& s1 = dynamic_cast<const Super&>(*this);
    const Super& s2 = dynamic_cast<const Super&>(rhs);
    return s1 == s2;
}

int main() {
    Super a;
    Super b;
    const Base& ab = a;
    const Base& bb = b;

    std::cout << (ab == bb) << std::endl;
}
0 Answers
Related