Yolinux.com Tutorial

C++ Data Structure and Union Tutorial

The C++ compiler treats the C data structure like a C++ class. This allows one to use C++ constructs with a "struct" when using the C++ compiler. This is also true for a "C" union with a constructor. Sample code examples with explanations and tips are discussed.

Tutorial Contents:


Related YoLinux tutorials:

°Software development tools

°STL: vector, list

°STL: string

°C++ Memory Corruption and Leaks

°Advanced VI

°Emacs and C/C++

°MS/Visual C++ tips

°C++ Info, links

°Clearcase Commands

°YoLinux Tutorials Index



Free Information Technology Magazine Subscriptions and Document Downloads


Free Information Technology Software and Development Magazine Subscriptions and Document Downloads


C++ Structure example:

Simple example of a program using C++, a structure and a constructor:

// File: struct-test.cpp
//
// This example shows the use of a structure in C++ and how it behaves much
// like a class including the use of a contructor yet maintains the useability
// of a regular C structure.

#include <iostream>
#include <string>

using namespace std;

main()
{
struct DataElement {
string SVal;
int iVal;
bool hasData;

DataElement() // Example of a constructor used in a structure.
{
iVal=-1;
hasData=0;
}
} *RealData;

RealData = new DataElement [ 5 ];

// Assignment
RealData[0].SVal = "Value loaded into first structure element.";
RealData[0].hasData = 1; // True

cout << "First element 0: " << RealData[0].SVal << endl;
cout << " " << RealData[0].hasData << endl;
cout << "Second element 1: " << RealData[1].SVal << endl;
cout << " " << RealData[1].hasData << endl; // Show effect of contructor
cout << " " << RealData[1].iVal << endl; // Show effect of contructor

delete [] RealData; // Or: delete [5] RealData;

}

Compile: g++ struct-test.cpp

[Potential Pitfall]: In Red Hat Linux versions 7.x one could omit the "using namespace std;" statement. Use of this statement is good programming practice and is required in Red Hat 8.0.

[Potential Pitfall]: Red Hat 8.0 requires the reference to "#include <fstream>". Red Hat versions 7.x used "#include <fstream.h>".

Output: ./a.out

First element  0: Value loaded into first structure element.
1
Second element 1:
0
-1

The same example using typedef and a C++ initializer:

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

typedef struct dataElement {
string SVal;
int iVal;
bool hasData;

dataElement() // Example of a constructor used in a structure.
: iVal(-1), hasData(0)
{}
} DataElement;

main()
{
DataElement *RealData;
RealData = new DataElement [ 5 ];

RealData[0].SVal = "Value loaded into first structure element.";
RealData[0].hasData = 1; // True

cout << "First element 0: " << RealData[0].SVal << endl;
cout << " " << RealData[0].hasData << endl;
cout << "Second element 1: " << RealData[1].SVal << endl;
cout << " " << RealData[1].hasData << endl; // Show effect of contructor
cout << " " << RealData[1].iVal << endl; // Show effect of contructor

delete [] RealData; // Or: delete [5] RealData;
}

Identical results as above example.

By contrast the typical "C" structure initialization is as follows:

#include <stdio.h>

typedef struct dataElement {
char *cVal;
int iVal;
} DataElement;

main()
{
DataElement RealData = {"Text goes here", 5 }; // "C" style initialization.

printf("%s \nInteger value=%d\n",RealData.cVal,RealData.iVal);
}
Compile: gcc struct-simple.c -o gcc struct-simple
Run: ./struct-simple
Text goes here
Integer value=5

C++ structure notes:

  • The struct can employ a constructor to initalize variables.
  • The struct can employ a destructor.
  • The structure constructor can not be declared virtual.
  • Structure member variables are public by default.

C++ Union example:

The following example shows how a "C" union can be used with a constructor to initialize data.

#include <stdio.h>

typedef union uAA
{
double dVal;
int iVal[2];

uAA() : dVal(3.22) {}
} UAA;

main()
{
UAA rdata;

printf("Array output: %d %d \nDouble output: %lf \n",
rdata.iVal[0], rdata.iVal[1], rdata.dVal);
}
Compile: g++ union-test.cpp -o union-test
Run: ./union-test
Array output: 1546188227 1074381455
Double output: 3.220000

[Potential Pitfall]: The C++ difference - Structures used with union. A struct can NOT be used with a constructor if it is to be used in a union. The C++ recognition of the constructor in a struct converts it to a C++ class which is not valid in a "C" union.

Typical use of a "C" union:
#include <stdio.h>

typedef struct
{
int iVal1;
int iVal2;
} DataElement;

typedef union
{
DataElement de;
int iVal[2];
} UAA;

main()
{
UAA rdata;

rdata.de.iVal1 = 0;
rdata.de.iVal2 = 1;

printf("Array output: %d %d \n",
rdata.iVal[0], rdata.iVal[1]);
}
Compile: gcc -o union-test union-test.c
Note: Compiles properly with the gcc and g++ compiler.
Run: ./union-test
Array output: 0 1
Use of C++ structure (with constructor) in a union:
#include <stdio.h>

typedef struct dataElement
{
int iVal1;
int iVal2;

dataElement() : iVal1(1), iVal2(2){};
} DataElement;

typedef union
{
DataElement de;
int iVal[2];
} UAA;

main()
{
UAA rdata;

printf("Array output: %d %d \n",
rdata.iVal[0], rdata.iVal[1]);
}

Compile: g++ -o union-test union-test.cpp
union-test.cpp:13: error: member `DataElement ::de' with constructor not allowed in union

C++ union notes:

  • The union can employ a constructor to initalize variables.
  • The union can employ a destructor.
  • Union member functions can NOT be declared virtual.
  • Union member variables are public by default.
  • A union's data members can NOT be declared static.
  • A union can not be used as a base class.

Why a tutorial on such a simple subject? While simple, it has been overlooked by every C++ book I have ever seen. Many programmers I have met didn't know that constructors could be used with a C structure. I didn't know until I was told by another programmer. It was not covered by my professor nor was it in our very thourough C++ text book. This is just an FYI.


Books:

C++ How to Program
by Harvey M. Deitel, Paul J. Deitel
ISBN #0131857576, Prentice Hall

Fifth edition. The first edition of this book (and Professor Sheely at UTA) taught me to program C++. It is complete and covers all the nuances of the C++ language. It also has good code examples. Good for both learning and reference.

Amazon.com
Dr. Dobb's Journal

Free subscription to the premier resource for professional programmers and software developers. Multi-language and multi-platform with program listings, coding tips, design issue discussions and algorithms. Subscribe here!

Free
Subscription

See http://YoLinux.com for more Linux information and tutorials
Return to YoLinux Tutorial Index

Feedback Form
Copyright © 2001, 2002, 2003, 2007 by Greg Ippolito