Please explain and discuss how in C++, data and the operations on that data may be combined into a single unit with the help of classes
Expert Answer
C++ allows to binds the data and operation to manipulate the data in a single unit called class. Class is an abstract data type in which we can declare data as well as operation to be performed on the data. This can be accomplished by the concept of encapsulation. First we discuss about objects and methods.
1) Dividing the problem in subproblems is called structured design. We can identify objects in each subproblem. Object is an instance of a class. Object consists of data and the method to manipulate data.
2) In a class same type of objects can be defined. A class is a collection of objects. The objects with same data type, same behavior can be bundled in a class.
3) Now encapsulation is a concept that bundle the data and the methods to manipulate the data. This can be accomplished by the user defined class. In a class many same objects of same type can be defined so encapsulation is achieved.
4) In a class, encapsulation is used to data hiding. The private data of a class is not accessed directly, they can accessed by the function defined in the data.
For example –
class cube { public: double getVolume(void) { return length * breadth * height; } private: double length; // Length of a box double breadth; // Breadth of a box double height; // Height of a box };
In the given class the length, height and breadth are private variables and can accessed by only the other member or function of the class cube and not by any other part of your program. So encapsulation is achieved. To make part of class public we must use specifier public.
Now we can observe that that variables are declared inside the class in private section. And the operation is declared in public section. So this operation can be used anywhere in the program and this operation takes the data declared in class.
So it is very clear that data and the operations on that data may be combined into a single unit with the help of classes in C++.