-1

I haee this small piece of code in which I'm trying to create a struct Employee. The employee can be either a manager or worker. I'm having trouble accessing members of the unions. Here's my code

#include <iostream>
#include <string>
using namespace std;

struct Employee {
 int id;
 union Person {
  struct Manager {
   int level;
  } manager;
  struct Worker {
   string department;
  } worker;
 } company[3];
};


int main() {
 Employee one;
 one.id = 101;
 one.company[0].manager.level = 3;

 Employee two;
 two.id = 102;
 two.company[1].worker.department = "Sales";

 Employee three;
 three.id = 103;
 three.company[2].worker.department = "Marketing";
}

The error I get is

arraOfUnions.cc:13:5: error: member 'Employee::Person::Worker Employee::Person::worker' with constructor not allowed in union
arraOfUnions.cc:13:5: error: member 'Employee::Person::Worker Employee::Person::worker' with destructor not allowed in union
arraOfUnions.cc:13:5: error: member 'Employee::Person::Worker Employee::Person::worker' with copy assignment operator not allowed in union
arraOfUnions.cc:13:5: note: unrestricted unions only available with -std=c++0x or -std=gnu++0x

I'm not sure what I'm doing wrong. Please help Thanks SO

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
Q_A
  • 433
  • 2
  • 6
  • 14

2 Answers2

2

You cannot have a non-POD object in your union, but you can have a pointer to a non PDO object (therefore string* is valid).

What are POD types in C++?

Pehaps a const char* is enough, if all you need is access to those string literals "Sales" & "Marketing"-

Community
  • 1
  • 1
Jts
  • 3,447
  • 1
  • 11
  • 14
0

BTW - you data model is completely wrong. You should not be using a union you need to use a class hierarchy.

You need a base class Employee, and a derived class Manager.

struct Employee {
   int id;
  string department;
};

struct Manager : public Employee
{
  int level;
}

and dont use struct use class

and have better naming for members. like m_company or company_

and dont do using namespace std, say std::string etc

class Employee {
   int _id;
  std::string _department;
};

class Manager : public Employee
{
  int _level;
}
pm100
  • 48,078
  • 23
  • 82
  • 145