Answers for "union in c++"

C++
1

union cpp

union S
{
    std::string str;
    std::vector<int> vec;
    ~S() {} // needs to know which member is active, only possible in union-like class 
};          // the whole union occupies max(sizeof(string), sizeof(vector<int>))
 
Posted by: Guest on June-02-2021
0

union c++

#include <iostream>
#include <cstring>

using namespace std;

union student
{
	int roll_no;
	int phone_number;
	char name[30];
};

int main()
{
	union student p1;
	p1.roll_no = 1;
	p1.phone_number = 1234567822;
	strcpy(p1.name,"Brown");
	cout << "roll_no : " << p1.roll_no << endl;
	cout << "phone_number : " << p1.phone_number << endl;
	cout << "name : " << p1.name << endl;
	return 0;
}
Posted by: Guest on November-26-2021

Browse Popular Code Answers by Language