Ads block

Banner 728x90px

Class and Object

The most important features of C++ is the "Class". Bjarne Stroustrup initially gave the name "C with classes" to his new language.
A class is an extension of the idea of structure used in C.


We know that one of the unique features of C language is structure.


To understand good about Class, we need a little knowledge of Structure and its some limitations.

Structure is a user defined data-type that contains number of data of different types. But it has some limitations.


To overcome the limitations of C structure "Class" comes in existence.


Limitation of C structure is that they do not permit data hiding. Structure members can be directly accessed by any function anywhere in their scope.


Another reason is that, in C++, by default, the members of a class are Private, while in C language, by default, the members of a structure are Public.


The general form of Class declaration:

class class-name
    {
      Private:
        variable declaration;
        function declaration;
      Public:
        variable declaration;
        function declaration;
    };

The variable declared inside the class are known as data members and the functions are known as members functions.
Only the member functions can have access to the Private data member and private functions. Public member can be accessed from outside the class.


when defining a class we are creating a new abstract data type that can be treated like any other built in data type.



Creating Objects

Once a class has been declared, we can create variables of that type by using the class name for creates a variable x of type item.

Object:
item x; // memory for x is created

In C++ the class variables are known as objects. Therefore, x is called an object of type item.

item x,y,z;

The declaration of an object is similar to that of variable of any basic type. The necessary memory space is allowed to any object at this stage.