3.20 Structs and Unions in C++


Structs in C++

The C programming language had the concept of a structure, grouping data together to form a complex data type (for example: complex numbers, Person record). C++ extends this concept by allowing methods to be associated with this data, so for example in C we could:

  
  struct A{
    char* someString;
    int someint;
  };

  // use like
  A testA;
  A *ptrtoA = new A;

  testA.someString = "something";
  ptrtoA->someint = 4;
  

In C++ we can add methods:

  struct Account{
      Account( ... );
      virtual void makeLodgement( ... ); //etc..
    private:
      int theAccountNumber;
      float theBalance;
  };

Structs and Classes are very similar in C++; however, members in a struct are public by default and members in a class are private by default. The 'C' language only allows public member data within structs (there is no concept of private or protected in C).

We can construct any class from a struct and vice-verse. It is a question of style, however a class is more commonly used for a data structure that has associated methods.

Unions in C++

C++ has a structure that allows us to have different types of data within the same variable. A union is particularly memory efficient as it calculates the minimum amount of memory to store the largest element in the structure. Therefore, contained data overlaps in memory.

 #include <iostream>
 using namespace std;

 union StudentID {
      char* byName;    // memory for a pointer OR 
      int byNumber;    // memory for an int
 };

 int main()
 {
    StudentID s;
    s.byNumber = 12345;
    cout << s.byNumber << endl;	//outputs 12345
    s.byName = "Hello";
    cout << s.byName << endl;   //outputs Hello
    cout << s.byNumber << endl; //outputs 4198928
 }



These notes are copyright Dr. Derek Molloy, School of Electronic Engineering, Dublin City University, Ireland 2013-present. Please contact him directly before reproducing any of the content in any way.
Comments