You can use a class type to create instances or objects of that class type. For example, you can declare a class, structure, and union with class names X, Y, and Z respectively:
class X {
// members of class X
};
struct Y {
// members of struct Y
};
union Z {
// members of union Z
};
You can then declare objects of each of these class types. Remember that classes, structures, and unions are all types of C++ classes.
int main()
{
X xobj; // declare a class object of class type X
Y yobj; // declare a struct object of class type Y
Z zobj; // declare a union object of class type Z
}
In C++, unlike C, you do not need to precede declarations of class objects with the keywords union, struct, and class unless the name of the class is hidden. For example:
struct Y { /* ... */ };
class X { /* ... */ };
int main ()
{
int X; // hides the class name X
Y yobj; // valid
X xobj; // error, class name X is hidden
class X xobj; // valid
}
When you declare more than one class object in a declaration, the declarators are treated as if declared individually. For example, if you declare two objects of class S in a single declaration:
class S { /* ... */ };
int main()
{
S S,T; // declare two objects of class type S
}
this declaration is equivalent to:
class S { /* ... */ };
int main()
{
S S;
class S T; // keyword class is required
// since variable S hides class type S
}
but is not equivalent to:
class S { /* ... */ };
int main()
{
S S;
S T; // error, S class type is hidden
}
You can also declare references to classes, pointers to classes, and arrays of classes. For example:
class X { /* ... */ };
struct Y { /* ... */ };
union Z { /* ... */ };
int main()
{
X xobj;
X &xref = xobj; // reference to class object of type X
Y *yptr; // pointer to struct object of type Y
Z zarray[10]; // array of 10 union objects of type Z
}
You can initialize classes in external, static, and automatic definitions. The initializer contains an = (equal sign) followed by a brace-enclosed, comma-separated list of values. You do not need to initialize all members of a class.
Objects of class types that are not copy restricted can be assigned, passed as arguments to functions, and returned by functions.
Related information