Structs

Structs are a a type from C that C++ used as a template for classes. We will briefly look at structs since they define data (i.e., data members) the same way as classes do. However, classes also permit us to define methods (i.e, functions).

  1. Single Records
    • Keyword struct used to define structure types; no space allocated for the type
      struct EMPLOYEE {
        int emp_no;
        char name[20];
        char address[40];
      };
      
    • To declare a variable and allocate space:
         struct EMPLOYEE  engineer;
      
    • The "struct" in the declaration is optional
         EMPLOYEE  engineer;
      
    • To initialize
         = {143, "George", "123 Main St."};
      
    • Or, declare a variable by placing it after the end "}" in the struct definition.
    • To access and element of a structure, use the dot notation: Engineer.emp_no = 9999;
  2. Arrays of Records
    • An array of structures is declared as
        rec array[30];
        array[5].i = 8;
      
    • Or a 2-dimensional array
        struct rec array[3][4][2];
        array[2][3][1].i = 9;   /*The last element of the array */
      
  3. Record Structures as Function Arguments
    • Call function with structure elements
        fn1(engineer.emp_no);  // call
        fn1 (int emp_no)	//header
      
    • Call function with entire structure
        fn2 (engineer);	//call
        fn2 (struct employee E) //header
      
    • Default pass by value, use & for pass by reference
    • Return a struct from a function
        Emp = fn3( );		// call
        struct employee fn3 ( )	//header
        	struct employee var;	// decl
        	return (var)		//return
      
  4. Pointers to structures can also be used, and space must be allocated using new
      struct rec {
        int i;
        float f;
        char c;
       };
      rec *rec_ptr;
      rec_ptr = new struct rec;
    
      (*rec_ptr).i = 30;	/* or rec_ptr->i = 30  */
      rec_ptr->f = 1.234;
      rec_ptr->c = 'X';
      delete(rec_ptr);
    
  5. Unions
    • When all elements of a structure are not needed, use a union
         union Number {
         	int i;
         	float f;
         };
      
    • A variable of type union can only be initialized with the first type
         union Number value = { 8};    /* 3.4 would be invalid */
      
    • A variable of type union Number can use only one of the components at a time.
         value.i = 100;
         cout <<  value.i;
         value.f = 123.45;
         cout <<  value.f;
      
  6. Enumerated Types
    • Enumerated types can be declared:
         enum colors = { red, blue, green };
      
    • The enumerated values red == 0, blue ==1, and green == 2
    • Variables can be declared as:
         enum colors rainbow;		OR		COLORS rainbow;