jweinst1
8/28/2017 - 2:12 AM

exmaple of state object using inner enum and union in C++

exmaple of state object using inner enum and union in C++

#include <iostream>

struct RadonObject
{
	enum Type
	{
		// data types
		Int,
		Char,
		Bool,
		List,
		// directives
		RxAdd,
		RxSub
	};
	Type state;

	union
	{
		RadonObject* _list;
		int _int;
		char _char;
		bool _bool;
	};

	RadonObject* next;
	

	//constructors for chained construction
	RadonObject(int i, RadonObject* next = nullptr): state(RadonObject::Int), _int(i), next(next) {}
	
	RadonObject(char ch, RadonObject* next = nullptr): state(RadonObject::Char), _char(ch), next(next) {}
	
	RadonObject(bool b, RadonObject* next = nullptr): state(RadonObject::Bool), _bool(b), next(next) {}
	
	RadonObject(RadonObject* lst, RadonObject* next = nullptr): state(RadonObject::List), _list(lst), next(next) {}

	inline ~RadonObject()
	{
		if(state == RadonObject::List) delete _list;
		delete next;
	}
};

int main() {
  std::cout << sizeof(RadonObject) << "\n";
  RadonObject::Type g = RadonObject::RxAdd;
}