Q:

How to assign variables in a derived class based on values of variables in an object of the base class?

Recently at work I came across this code (this is a contrived example, but is fundamentally doing the same thing):
class A
{
public:
    int foo;
};

class B: public A
{
public:
    int bar;
};

int main()
{
    A a;
    a.foo = 1000;

    B b;
    A* a_ptr = &b;
    *a_ptr = a;
}

Above, what is happening is that all member variables in a are being copied into the corresponding member variables in b, since B is derived from A and all objects of type B are guaranteed to have at least all of the same member variables as objects of type A.
In the actual code, A has enough variables that manually assigning each of them would not be ideal.
After struggling with it for a little bit, I was able to make sense of what the code was doing, but the fact that it took me more than a couple seconds seems like a red flag.
Is there another way to do what this code is doing that might be easier to understand, or more in line with C++ common practices? Is it common to see variables assigned in this way?
Edit: It has been suggested that my question is a possible duplicate, and that I am asking what object slicing is. This is not object slicing, as I am not at any point assigning an object of the derived type to an object of the base type. As such, no information is "sliced" or lost anywhere in the code.

A:

I would say using pointer operations like this to do the assignment is in fact uncommon in C++.
An alternate approach would be explicitly spelling out your intention with a cast. I'm not totally sure if it's more readable:
A a;
a.foo = 1000;

B b;
static_cast<A&>(b) = a;

Depending on your specific needs however you might be better served with a child constructor that takes a parent and constructs itself appropriately. That way you don't need to default construct the child and then assign the parent members as a second step.

