2

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.

Jack
  • 16,276
  • 55
  • 159
  • 284
  • 1
    Be aware of object-slicing. Copying and polymorphism don't always play nice, because which copy constructor is called is determined at compile-time. A common solution is to create a virtual clone method, which each derived class overrides as necessary to return the right type of object. – Neil Kirk Sep 06 '15 at 04:05

1 Answers1

2

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)
1201ProgramAlarm
  • 32,384
  • 7
  • 42
  • 56