CMcL
CMcL

Reputation: 1

Derived class =operator taking and returning Base reference

my co-worker and I ran into some old code that has us a bit confused. Essentially it boils down to this.

class Base
{
public:
    Base() = default;
};

class Derived : public Base
{
public:
    Derived() = default;
    std::string m_test;
    
    Base& operator=(const Base& other)
    {
        const Derived *pThat = (Derived*)&other;
        m_test = "Woo";
        return *this;
    }
};

Can the = operator ever get called? Obviously there is the flaw that if it did get called the cast would fail on anything other Base but so far we couldn't think of any situation where this could actually legally be called.

Upvotes: 0

Views: 64

Answers (1)

lorro
lorro

Reputation: 10880

Yes, operator= can be called with any other that is-a Base (and is-not-a Derived, as in that case the default implementation would be called; but it can be any class publicly descending from Base or Base itself). Since pThat is not dereferenced, it's a valid code. Note: regardless of being valid or not, it's very dangerous, as UB can occur when dereferenced.

If pThat were dereferenced (e.g. you wrote pThat->m_whatever), then the code is only valid if other is-a Derived, otherwise it's UB.

Live demo: https://ideone.com/encyK5

Upvotes: 3

Related Questions