copy base class data from one derived class to another

那年仲夏 提交于 2019-12-12 03:55:15

问题


Suppose I have three classes:

typedef struct base
{
    float A;
    float B;
    ...
    base() : A(1.0f), B(1.0f) {}
} base;

class derived1 : base
{
    int C;
    int D;
};

class derived2 : base
{
    int E;
    int F;
};

And I would like to copy base class data from one derived class object to another.
Is it safe to do the following, to only copy the base class values of A, B, etc... from one object to another?

derived1* object1 = new derived1;
derived2* object2 = new derived2;

void make_object1()
{
    object1->C = 2;
    object1->D = 3;
}

void make_object2()
}
    object2->A = 4;
    object2->B = 5;
    object2->E = 6;
    object2->F = 7;
}

void transfer_base()
{
    *((base*)object1) = *((base*)object2);
}

Assuming my program would need to do this sort of operation often would there be a better (faster code) way to accomplish this? The reason that I'd doing this is I have written a simulation and a graphical renderer. I want to update graphical display objects with only select data from objects in the simulation as efficiently as possible. The simulation is extremely CPU intensive... So far this approach seems to be working however I'm concerned there may be something I'm overlooking...


回答1:


The code

*((base*)object1) = *((base*)object2);

is quite unsafe, because the C style casts can do just about anything. Such as reinterpretation, or casting away constness.

Instead, if you want to invoke base::operator=, then invoke that explicitly. Excplicit = good, implicit = bad.

I.e.,

object1->base::operator=( *object2 );

This is still not “safe”, because the slicing may break the class invariant of the derived class. And anyone trying to get a handle on what happens in this code may be surprised by the sudden change of values in the base class sub-objects, and waste a lot of time trying to ascertain where those values are coming from. But at least it’s not as bad as the C style casting.




回答2:


Instead, why not create your own assignment method in the base class (removing the unneeded C-artifact typedeffing):

struct base
{
    float A;
    float B;
    ...
    base() : A(1.0f), B(1.0f) {}
    base& assign_base(const base& right) { A = right.A; B = right.B; }
};

Then you can just say

der1.assign_base(der2);


来源:https://stackoverflow.com/questions/15672207/copy-base-class-data-from-one-derived-class-to-another

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!