Search code examples
c++polymorphism

Assigning class to base class, how do do it?


I'm confused about assigning the base object of a derived class. Say I have a type:

class Base {
 // stuff omitted for brevity
}

and a derived class

Derived : public Base {
  // stuff omitted
}

and I have a situation that arises like this:

Derived = Base;

Is this possible? What is this operation called? How would I do such a thing?

Thanks for your help.


Solution

  • This is a perfectly ordinary user-defined assignment that looks enough like "slicing", treating a base class as if it were a member, to confuse the unwary. But it's not slicing. For the situation you have, the two classes might as well not be related, and you define the assignment that way.

    struct d : b {
         d &operator=(const b &b_) { /*do the work here*/; return *this; }
    };
    

    You might be able to use the base class's copy-assignment operator, or you might not:

    struct dx : b {
        dx &operator=(const b &b_)
        {
            this->b::operator=(b_);
            // more work
            return *this;
        }
    };
    

    but the compiler gives this no special treatment, it's the same as any function call.