Chris Petrus
Chris Petrus

Reputation: 203

How to gracefully copy two dissimilar structures in C++?

I have two dissimilar structures with some common elements.

    typedef struct X {
        struct X *next
        char X1[5];
    }

    typedef struct Y {
        unsigned char Y1;
        int Y2[5];
        bool Y3;
    }Y;

    typedef struct Z {
        unsigned char Z1;
        int Z2;
        X X1;
        Y Y1;
        struct Z *next;
    }Z;


    typedef struct A {
        unsigned char A1;
        char A2[20];
        X X1; 
        Y Y1;
    }


  typedef struct B {
        unsigned char B1;
        char B2[20];
        int B3;
        Z Z1; 
    }

I want to copy A and B but I do not want to use reinterpret_cast as it is risky and the code would be deployed on several machines. Please suggest any graceful method of copying.

P.S. I am not allowed to change the design. :(

Upvotes: 0

Views: 80

Answers (2)

rubikonx9
rubikonx9

Reputation: 1413

I guess the most elegant way would be to define operator= for A and B, like this:

A & operator=(const B & b) {
    this->A1 = b.B1;
    memcpy(this->A2, b.B2, 20);
    // Handle X1, Y1, B3 and Z1 somehow - depending on your needs
}

Then you can call it like this:

A a;
B b;
a = b;

Anyways, you'll need to take care of each element separately. The compiler can't possibly guess how you want to handle the data properties which are of different types.

You can automate the process further, for example by making a constructor for Z which would take instances of X and Y.

Also, remember that's it's a good practice to provide copy constructors along with the assignement operator.

Upvotes: 3

You have to do it element-by-element if you want to be portable.

For example you can just add a constructor to A with signature A(const B& b) and have that constructor copy the individual fields from b to this. Then do the same for the sub-structs.

Upvotes: 1

Related Questions