A class is an approach to bind the data, describing the entity or an object, and its associated functions together. In C++, a class creates a data-type that is used to create objects of that particular type. Class represents a group of similar objects.

Example:

In the above example, the data describing an account object (i.e. accountno, type and balance) and its associated operations (i.e. deposit and withdraw) are bound together under one name account. Thus, account makes a class. Now multiple instances of the class account can be created.

Declaration of Classes

The general form of a class definition is as given below:

The keyword class specifies that it is a class; class-name is the tag name of the class that acts as a type specifier for it, using which objects of the class-type can be created, as we will see in the forthcoming examples. The braces { and } surround the body of the class.

The class body contains the declaration of its members (i.e. data-members and functions). Access specifier defines the visibility and scope of the class data-members and functions. There are three types of access specifiers in a class: private, public and protected.

  • private: data can be accessed by the members of the class and by friends of the class.
  • public: data can be accessed by anyone irrespective of its position.
  • protected: data can be accessed by the members of the class, friends of the class and a class derived from it.
  • If no access specifier is specified then, by default, members are private.

Example:

Referencing Class Members

A class specification does not define any objects of its type; rather it just defines the properties and structure of a class. To make use of a defined class, a variable of the class-type have to be declared.

The general format for calling a member function is:

Example:

A Class Member Definition

In the above section, we saw how to define and declare a class, now we will look at member function definition. Member functions can be defined in two ways:

  • Outside a class definition
  • Inside a class definition

Outside a class definition

A member function definition, outside a class definition, is much the same as that of a normal function definition. The only difference is that the name of a function will be preceded by a class name. The complete name (also called qualified-name ) of a function is written as:

Where the class-name specifies the ame of the class to which the function belongs and the function-name specifies the name of the member function.

Inside the class definition:

When a member function is defined inside a class, the function definition is just similar to a normal function definition. That is, now you do not need to precede the function-name with a membership label . Functions defined within a class specification are automatically inline.