简体   繁体   中英

What is the difference between these two ways to invoke base class copy assignment?

Suppose I have the following:

class A
{
public:
    A& operator= (A const& other)
    {
        return *this;
    }
};

class B : public A
{
public:
    B& operator= (B const& other)
    {
        static_cast<A&>(*this) = static_cast<A const&>(other);
        // or...
        A::operator=(other);
        return *this;
    }
};

To invoke A 's version of the copy assignment operator, I could do either:

static_cast<A&>(*this) = static_cast<A const&>(other);

Or:

A::operator=(other);

Why would you choose one over the other? What are the differences between the two?

EDIT

My question's initial example was invalid and very far off from what I was intending to ask. My apologies for the mistake. I have updated my example above to be more clear.

static_cast<A&>(*this).foo() still calls the derived version of foo . This is just calling a virtual function through base class reference.

Whereas A::foo() turns off virtual dispatch and calls foo implemented in class A , not in the derived class.


If operator= is not virtual in A , static_cast<A&>(*this) = static_cast<A const&>(other) is another way of saying A::operator=(other) (no need to upcast other because the derived to base reference conversion is implicit). They do the same thing - call A::operator= .

Often though, operator= is implemented in terms of copy constructor followed by swap:

B& B::operator=(B other) { 
    other.swap(*this); 
    return *this;
}

Taking B by value invokes B s copy constructor for us. If B has r-value copy constructor this assignment operator can be used with r-values as well as move-only B (if B , for example, has a std::unique_ptr member).

如果你想要两个类(A和B)的A赋值运算符,只是不要在B类中实现它。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM