Classes and Objects

Encapsulation refers to the wrapping up of data and its associated meaningful functions into a single entity. One mechanism that allows programmers to encapsulate data is called a class.  Classes are also called abstract data types as they enforce the object-oriented programming concepts of data abstraction and encapsulation.

Once a class is defined, one can create variables from it. A class variable is called an object or an instance. In other words, an object is an identifiable entity having certain characteristics and behaviour as defined by a class.

Taking an example, using C++,

class Name {

   private:

      //data members and methods that remain private i.e. cannot be accessed outside the class

   protected:      //data members and methods that are protected i.e. accessible from members of their same class and also from members of their derived class (see Inheritance)

   public:

    int mem1;    void met1();

    //data members and methods that are public i.e. accessible from anywhere

} Ob1, Ob2;

Here, ‘Name’ is the name of the class and ‘Ob1’ and ‘Ob2’ are its objects. The body of the declaration can contain members, either in the form of data or of function declarations.  These data members and member functions/methods are classified into three categories: private, public and protected. These are reserved words and called access specifiers. As described in the comments, the access specifiers essentially determine where a member of the function can be used in the entire program. By default, all members of a class declared with the class keyword have private access unless otherwise specified.

To access the class methods and data members, objects are used as follows:

Ob1.met1(); //accessing public member function met1() through the first object ‘Ob1’

cin≫ Ob2.mem1; //accessing public data member mem1 through the second object ‘Ob2’

Now how does it work in the memory? For each object of the class Name, a different set of values can be stored. This means mem1 for Ob1 (accessed by Ob1.mem1) can store, say, 4, while mem1 for Ob2 (accessed by Ob2.mem1) can store, say, 20. To relate, one can compare this with a school classroom list – here, the C++ class becomes ‘A’ (for classroom section) and it can hold the names of students, with their roll numbers, personal information, marks in different subjects, etc. Thus, classes can be used to streamline storage of students’ details while selectively privatizing personal information.

See also: Inheritance, Polymorphism, Why Object-Oriented Programming is better?

Leave a Reply

Your email address will not be published. Required fields are marked *