C++ | Type Keywords
class foo { int x; public: int get_x(); void set_x(int new_x);};class foo; // elaborated type specifier -> forward declarationclass bar { public: bar(foo& f);};void baz();class baz; // another elaborated type specifer; another forward declaration // note: the class has the same name as the function void baz()class foo { bar b; friend class baz; // elaborated type specifier refers to the class, // not the function of the same name public: foo();};template <class T>const T& min(const T& x, const T& y) { return b < a ? b : a;}template <template <class T> class U>// ^^^^^ "class" used in this sense here;// U is a template template parametervoid f() { U<int>::do_it(); U<double>::do_it();}template <class T>class foo {};
foo<class bar> x; // <- bar does not have to have previously appeared.enum class Format { TEXT, PDF, OTHER,};Format f = F::TEXT;enum Direction { UP, LEFT, DOWN, RIGHT};Direction d = UP;In C++11, enum may optionally be followed by class or struct to define a scoped enum. Furthermore, both scoped and unscoped enums can have their underlying type explicitly specified by : T following the enum name, where T refers to an integer type.
enum class Format : char { TEXT, PDF, OTHER }; Format f = Format::TEXT;
enum Language : int { ENGLISH, FRENCH, OTHER };Enumerators in normal enums may also be preceded by the scope operator, although they are still considered to be in the scope the enum was defined in.
Language l1, l2;
l1 = ENGLISH; l2 = Language::OTHER;enum Foo { FOO };void Foo() {}Foo foo = FOO; // ill-formed; Foo refers to the functionenum Foo foo = FOO; // ok; Foo refers to the enum typeenum class Format; // underlying type is implicitly intvoid f(Format f);enum class Format { TEXT, PDF, OTHER,};
enum Direction; // ill-formed; must specify underlying typestruct
Section titled “struct”Interchangeable with class, except for the following differences:
- If a class type is defined using the keyword
struct, then the default accessibility of bases and members ispublicrather thanprivate. structcannot be used to declare a template type parameter or template template parameter; onlyclasscan.
// Example is from POSIXunion sigval { int sival_int; void *sival_ptr;};union foo; // elaborated type specifier -> forward declarationclass bar { public: bar(foo& f);};void baz();union baz; // another elaborated type specifer; another forward declaration // note: the class has the same name as the function void baz()union foo { long l; union baz* b; // elaborated type specifier refers to the class, // not the function of the same name};