Beta Carotin
Beta Carotin

Reputation: 1679

Assignment of base class object to derived class object

Why do I get error: no match for ‘operator=’ in ‘y = x’ in the following code?
Cant the a-component of b not just be assigned to like it was a-object = a-object?

struct a {int i;};
struct b : public a {int j;};

int main()
{
    a x;
    b y;

    x.i = 9;
    y.j = 5;

    y = x; // error: no match for ‘operator=’ in ‘y = x’

    // expected: y.i = 9

    return 0;
}

Upvotes: 0

Views: 1393

Answers (3)

Remy Lebeau
Remy Lebeau

Reputation: 595467

You are not explicitly defining any assignment operators, so the compiler will generate its own default operators for each struct. The compiler's default assignment operator in b takes a b as input and will assign both members. And assignment operators are not automatically inherited when using inheritance. That is why you cannot pass an a to a b - there is no assignment operator in b that takes an a as input. If you want to allow that, you need to tell the compiler as much, eg:

struct a
{
    int i;

    a& operator=(const a &rhs)
    {
        i = rhs.i;
        return *this;
    }
};

struct b : public a
{
    int j;

    using a::operator=;

    b& operator=(const b &rhs)
    {
        *this = static_cast<const a&>(rhs);
        j = rhs.j;
        return *this;
    }
};

int main()
{
    a x;
    b y;
    b z;
    ...
    y = x; // OK now
    y = z; // OK as well
    ...    
    return 0;
}

Upvotes: 1

decden
decden

Reputation: 719

As the error states, you need to implement an assignment operator. That is, a function that tells your program how to assign one object to another one. You can find plenty of information on it if you search the web, e.g. on http://www.cplusplus.com/articles/y8hv0pDG/

Upvotes: 0

Some programmer dude
Some programmer dude

Reputation: 409146

No, because even if the classes are related they are different types.

Think about this, even if it was allowed and it would work like you expected, what would the value of y.j be after the assignment?

Upvotes: 0

Related Questions