Search code examples
c++classvisual-c++copy-constructorshallow-copy

Copy all members of a class to current object


Let's assume I have a base class called BaseClass and an object called Foo that inherited from BaseClass. Can I copy all members of a BaseClass instance to current object being created instead of do it manually?

class BaseClass
{
    int a;
    int b;
    int c;
    const char *e;
};

class Foo : BaseClass
{
public:

    Foo(BaseClass* bc, int x, const char *value)
    {
        // copy bc->a to this->a and bc->b to this->b 
        // and so on with all the members of BaseClass class
        this->x = x;
        this->s = value;
    }

    int x;
    const char *s;
};

Can I do this? Another possible solution with memcpy(), not sure if it's ugly or can't work but assuming the members allocated in order, with BaseClass first, ie, this class became something like in memory:

   struct
    {
        // members of BaseClass
        int a;
        int b;
        int c;
        const char *e;
        // members of Foo
        int x;
        const char *s;
    };

Something like this in Foo constructor:

memcpy(this, &bc, sizeof(*bc));

Should copy all members of bc into current object, right? is this dangerouos?

Btw, I'm doing this in a C-style. I don't do much C++. C++-way to do it are very welcome.


Solution

  • Change your declaration of the Foo constructor to include a constructor for the base class:

    Foo(BaseClass* bc, int x, const char *value): BaseClass(*bc)