Alex Rivera | Logout

how to assign base class object to a derived class object?

Asked 2011-01-01T18:55:54.957
12

Assuming I have a base class A and publicly derived class B, how should I assign A object to the A base class subobject of B?

class A {...};
class B : public A {...};
A a(..);
B b(..);
static_cast<A&>(b) = a; ???

Is that doable without writing assignement operator for B? Are there any potential problems with casting b to A&? Is that standard conformant?

Edit
Report

1 Answer

8

That's a really bad idea. A is the base, B is a derived type. By casting B to an A, you are now using A's assignment operator, which isn't going to touch any of the extra derived data. At the end of that assignment, b is still considered to be of type B, even though it now contains an A. This is the opposite of the way inheritance is meant to be used.

Changing the line to b = reinterpret_cast<B&>(a); would be even worse. Then you would be pretending that a is a B when it's not, and you be reading invalid memory.

If you truly want to do this kind of assignment, you want:

class B : public A {
    B& operator= (const A& a) { ... }
};

Then you can write a function to copy the information from the A, and somehow deal with the extra information in the derived type B, plus this would allow you to simply write:

b = a;
answered 2011-01-01T19:06:18.823

Your Answer