jweinst1
8/24/2017 - 9:52 PM

constructor for unions in cpp

constructor for unions in cpp

#include <iostream>

//example about union struct links
//recursive constructors

//basic data object
struct Data
{
  enum
  {
    Int,
    Bool,
    Char,
    Pnt
  } type;
  
  union
  {
    int i;
    char c;
    bool b;
    Data* p;
  };
  //linkages
  Data* next;
  Data* prev;
  
public:
//constructors for each data type in the union
  Data(int i, Data* next = nullptr, Data* prev = nullptr) : i(i), type(Data::Int), next(next), prev(prev)
  {}
  Data(char c, Data* next = nullptr, Data* prev = nullptr) : c(c), type(Data::Char), next(next), prev(prev)
  {}
  Data(bool b, Data* next = nullptr, Data* prev = nullptr) : b(b), type(Data::Bool), next(next), prev(prev)
  {}
  Data(Data* p, Data* next = nullptr, Data* prev = nullptr) : p(p), type(Data::Pnt), next(next), prev(prev)
  {}
};

int main() {
  //sample init
  Data a(3, new Data(4), new Data('r'));
  std::cout <<  a.prev->type << "\n";
  //2
}