Class and Object

Class in C++

Class is a group of objects that share common properties and relationships. In C++, a class is a new data type that contains member variables and member functions that operates on the variables.

Classes are the language element in C++ most important to the support object-oriented programming (OOP). A class defines the properties and capacities of an object.

A class is defined with the keyword class. It allows the data to be hidden, if necessary from external use. When we defining a class, we are creating a new abstract data type that can be treated like any other built in data type. Generally a class specification has two parts:

  1. Class declaration :
    • The class declaration describes the type and scope of its members.
  2. Class function definition:
    • The class function definition describes how the class functions are implemented.

Syntax:

class class-name
{
private:
              member_variable declarations;
              member_function declaration ;
public:
              member_variable declarations;
              member_function declaration;
};

The definition begins with the keyword class followed by the class name. The data members and methods are then declared in the subsequent code block. Data members and member functions can belong to any valid type, even to another previously defined class. At the same time, the class members are divided into private , public and protected members.

Here, private members, which cannot be accessed externally and public members, which are available for external access. The use of keywords private is optional. By default, the members of a class are private.

Example:

class item
{
    int member;
    float cost;
public:
    void getldata (int a ,float b);
    void putdata (void);
};

Here, The class item contains two data members and two function members, the data members are private by default while both the functions are public by declaration. The function getdata() can be used to assign values to the member variables member and cost, and putdata() for displaying their values. These functions provide the only access to the data members from outside the class.

Object in C++

Once a class has been declared we can create variables of that type by using the class name. Defining a class also defines a new type for which variables, that is, objects, can be defined. An object is also referred to as an instance of a class.

Syntax:

class_name object_name;

Example:

item x;

The above statement will create a variables x of type item. In C++, the class variables are known as objects. Therefore x is called an object of type item.

Example:

class item
{
-----------
-----------
-----------
}x ,y ,z;
would create the objects x ,y ,z of type item.

Related posts