Search code examples
c++inheritanceunions

C++ Is there a way how to simulate union behavior between child and parent classes?


is there a way how to simulate union behavior? See following code:

// this is ideal interface, which I would like to simulate
struct IdealInterface{
  union{
    struct{float r,g,b;};
    struct{float x,y,z;};
  };
};

// this is real parent object I should not change
struct Parent{
  float r, g, b;
};

// this interface has ok behavior,
// but sizeof(Child0) != sizeof(Parent)
// which causes problems
struct Child0:public Parent{
  float & x, & y, & z;
  Child0() : Parent(), x(r), y(g), z(b){ };
};

// this has ok size, but interface is different
struct Child1:public Parent{
  float & x(){ return r; }
  float & y(){ return g; }
  float & z(){ return b; }
};

So as described, I should keep Parent class, and I should derive my child class from Parent. I should not create different types and play with the type conversions. Thus, is it possible to create derived class (form Parent) with the same interface as IdealInterface class has?


Solution

  • Answer:

    Firstly, I have some words for commentators. I asked a pretty straight question. What I got? For example answers about sizeof properties, which were not posed (btw, yeah in this case I have guarantee about sizeof - this is c++, not a kind of today common wild language).

    Why I cannot use IdealInterface. Problem is more complex. I want to edit bigger pack of code with introduced constraints and dependencies. Thus this is the question and I cannot redefine question, however it implies simpler solution.

    Answer: NO, it is not possible.

    Why? It is based on properties of anonymous structs and unions.

    Nearest approach: For my purpose, nearest approach is to use memory model as parameter.

    struct BASIC_MEMORY_MODEL{
        float x, y, z;
        BASIC_MEMORY_MODEL() :x(), y(), z(){}
    };
    
    struct ADVANCED_MEMORY_MODEL{
        union{
            struct { float x, y, z; };
            struct { float r, g, b; };
        };
        ADVANCED_MEMORY_MODEL() :x(), y(), z(){}
    };
    
    template<typename MEMORY_MODEL = BASIC_MEMORY_MODEL>
    struct ParentBase : public MEMORY_MODEL{};
    
    typedef ParentBase<> Parent;
    
    struct Child : public ParentBase < ADVANCED_MEMORY_MODEL > {};