derived class's virtual assignment operator not being called

后端 未结 2 857
忘了有多久
忘了有多久 2021-01-20 07:20

I\'m pretty new to C++, and am trying to come to grips with virtual assignment. The program below consists of an abstract base class with two data members, and a derived cla

相关标签:
2条回答
  • 2021-01-20 07:56

    This is a bit old, but in case anyone else stumbles upon it:

    To add to Mark's answer, you can do this by implementing

    Derived & operator=(const Abstract & rs);
    

    In this case you may need to use rs by casting it: dynamic_cast<const Derived &>(rs)
    Of course this should only be done carefully. The full implementation would be:

    Derived & Derived::operator=(const Abstract & hs)
    {
        if (this == &hs)
            return *this;
        Abstract::operator=(hs);
        style = new char[std::strlen(dynamic_cast<const Derived &>(hs).style) + 1];
        std::strcpy(style, dynamic_cast<const Derived &>(hs).style);
        return *this;
    }
    
    0 讨论(0)
  • 2021-01-20 07:58

    C++ doesn't let you override virtual functions with covariant parameter types. Your derived operator doesn't override the Abstract assignment operator at all, it defines a totally orthogonal operator related only in that it's the same operator name.

    You have to be careful creating such functions because if the two actual derived types don't agree, almost certainly the assignment will be nonsensical. I would reconsider whether your design need could be served better by an alternate approach.

    0 讨论(0)
提交回复
热议问题