2

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...

kkuryllo
  • 340
  • 3
  • 12

2 Answers2

3

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.

Cheers and hth. - Alf
  • 142,714
  • 15
  • 209
  • 331
0

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);
Mark B
  • 95,107
  • 10
  • 109
  • 188