union in gcc compiler

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// i use dev c++ 5.6.3
//similar error on code block ide

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

union myu{
string name;
int age;

};


int main()
{
myu uob;
uob.age=35;

cout<<uob.age;
 return 0;
}



built time error:

G:\c-pro\Untitled1.cpp In function 'int main()':
15 5 G:\c-pro\Untitled1.cpp [Error] use of deleted function 'myu::myu()'
6 7 G:\c-pro\Untitled1.cpp [Note] 'myu::myu()' is implicitly deleted because the default definition would be ill-formed:
7 8 G:\c-pro\Untitled1.cpp [Error] union member 'myu::name' with non-trivial 'std::basic_string<_CharT, _Traits, _Alloc>::basic_string() [with _CharT = char; _Traits = std::char_traits<char>; _Alloc = std::allocator<char>]'
15 5 G:\c-pro\Untitled1.cpp [Error] use of deleted function 'myu::~myu()'
6 7 G:\c-pro\Untitled1.cpp [Note] 'myu::~myu()' is implicitly deleted because the default definition would be ill-formed:
7 8 G:\c-pro\Untitled1.cpp [Error] union member 'myu::name' with non-trivial 'std::basic_string<_CharT, _Traits, _Alloc>::~basic_string() [with _CharT = char; _Traits = std::char_traits<char>; _Alloc = std::allocator<char>]'

I think it is related with gcc compiler.
how to declare and access union in gcc compiler?
I need your suggestion.
Last edited on
n3337 ยง9.5.2:

[...] If any non-static data member of a union has a non-trivial default constructor (12.1), copy constructor (12.8), move constructor (12.8), copy assignment operator (12.8), move assignment operator (12.8), or destructor (12.4), the corresponding member function of the union must be user-provided or it will be implicitly deleted (8.4.3) for the union.
this wont run:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include<string>
using namespace std;

union mytypes {
  char c;
  int i;
  float f;
  string st;  
};


int main(){
	mytypes types;
	types.i = 33;
	cout << types.i;
return 0;
}


but it will run if you deactive line 9, //string st;

so, instead std::string you can use char arrray, char ch[20];
Topic archived. No new replies allowed.