Поделиться через


Composed Derivative Types

This section describes the following composed derivative types:

  • Classes

  • Structures

  • Unions

Information about aggregate types and initialization of aggregate types can be found in Initializing Aggregates.

C++ Classes

Classes are a composite group of member objects, functions to manipulate these members, and (optionally) access-control specifications to member objects and functions.

By grouping composite groups of objects and functions in classes, C++ enables programmers to create derivative types that define not only data but also the behavior of objects.

Class members default to private access and private inheritance. Classes are covered in Classes, Structures, and Unions. Access control is covered in Member-Access Control.

C++ Structures

C++ structures are the same as classes, except that all member data and functions default to public access, and inheritance defaults to public inheritance.

For more information about access control, see Member-Access Control.

C++ Unions

Unions enable programmers to define types capable of containing different kinds of variables in the same memory space. The following code shows how you can use a union to store several different types of variables:

Example

// unions.cpp
#include <stdio.h>
// compile with: /c
// Declare a union that can hold data of types char, int,
// or char *.
union ToPrint {
   char chVar;
   int iVar;
   char *szVar;
};

// Declare an enumerated type that describes what type to print.
enum PrintType { 
   CHAR_T, 
   INT_T, 
   STRING_T
};

void Print( ToPrint Var, PrintType Type ) {
   switch( Type ) {
      case CHAR_T:
         printf_s( "%c", Var.chVar );
      break;
      case INT_T:
         printf_s( "%d", Var.iVar );
      break;
      case STRING_T:
         printf_s( "%s", Var.szVar );
      break;
    }
}

See Also

Reference

Derived Types