Home > Software engineering >  How to copy data from base class to derived class fastly?
How to copy data from base class to derived class fastly?

Time:11-18

I know move constructor can avoid copy, with a high performance.

but can i use it in copy data from base class to derived class?

for example:

// base.h
class Base {
 public:
  int a;
  char buff[24];
  double bp_[10];
};
// derived.h
class Derived : public Base {
 public:
  int b;
  char buff2[16];
};
// main.cpp
int main() {
  Base b;
  b.a = 1;
  snprintf(b.buff, sizeof(b.buff), "helloworld");
  b.bp_[0] = 100;
  Derived d;
  d.b = 9;
  snprintf(d.buff2, sizeof(d.buff2), "mytest");
  // TODO: how can i move b's data into d with high performance?
}

please see the code, I have a Base object with data, but i want to create a Derived class object, so i need copy data from Base object, is there any good methods like move constructor?

CodePudding user response:

There is no general way to do this, as the layout of the data in the base and derived classes may be different. You'll need to write a specific function to do the copying for each class.

One approach would be to write a template function that takes a base class and a derived class, and uses a static_cast to copy the data:

template <typename Base, typename Derived>
void copy_data(Base& b, Derived& d)
{
    d = static_cast<Derived>(b);
}

This will work if the layout of the data in the base and derived classes is the same. If it's not, you'll need to write a specific function to do the copying.

  • Related