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 { /* definition of class X */ };
struct Y { /* definition of struct Y */ };
union Z { /* definition 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.
void 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.
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 { /* ... */ };
void main()
{
S S,T; // declare two objects of class type S
}
this declaration is equivalent to:
class S { /* ... */ };
void main()
{
S S;
class S T; // keyword class is required
// since variable S hides class type S
}
but is not equivalent to:
class S { /* ... */ };
void 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.
Objects of class types that are not copy restricted can be assigned, passed as arguments to functions, and returned by functions.
![]()
Objects
Scope of Class Names
Union
![]()
Examples of Declaring Class
Objects
![]()
Arrays
Initialization by Constructor
Copying Class Objects
Pointers
References