Classes (C++ only)
A class is a mechanism for creating user-defined data types. It is similar to the C language structure data type. In C, a structure is composed of a set of data members. In C++, a class type is like a C structure, except that a class is composed of a set of data members and a set of operations that can be performed on the class.
union
, struct
,
or class
. A union object can hold any one of a set
of named members. Structure and class objects hold a complete set
of members. Each class type represents a unique set of class members
including data members, member functions, and other type names. The
default access for members depends on the class key: - The members of a class declared with the keyword
class
are private by default. A class is inherited privately by default. - The members of a class declared with the keyword
struct
are public by default. A structure is inherited publicly by default. - The members of a union (declared with the keyword
union
) are public by default. A union cannot be used as a base class in derivation.
class X
{
/* define class members here */
};
int main()
{
X xobject1; // create an object of class type X
X xobject2; // create another object of class type X
}
You may have polymorphic classes in C++. Polymorphism is the ability to use a function name that appears in different classes (related by inheritance), without knowing exactly the class the function belongs to at compile time.
C++ allows you to redefine standard operators and functions through the concept of overloading. Operator overloading facilitates data abstraction by allowing you to use classes as easily as built-in types.