In the tradition programming language also called a procedural language, we used to write procedures and functions that contained certain data items and write instructions that used to operate on that data in some way by arithmetical or logical operation, conditions or iterations. We could create containers with similar data types like arrays and with dis-similar data types like structures. To model real life in a better way we also needed to group data and methods/functions together in one envelope. We needed to create templates of this envelope and actual functional entities that were based on these templates. The template that contain the data and methods together were called CLASSES and the functional entities based on these templates were called OBJECTS. for. e.g.
if we need to define area of a square, we need a data item as side of square and method for squaring the side. We would write this as –
class Area
{
int side;
public:
long area_of_square() { return side*side; }
}A1;
Here Area is name of class which is just a template containing data item side and method or function as area_of_square which simply does the job of squaring the side and returns it to the routine which called it.
You will also notice a term A1 along with class declaration. This is actual entity which can be used for physical implementation of class while calling methods and data of the class. This term as declared here is called OBJECT of the class say class name Area here.
Another interesting term you observe is the declaration of some segment of class as public. This means that data and methods in this segment can be called by outside routines whenever needed. For e.g. declaration above public segment will not be callable outside. This provides an inherent way to protect class elements being called directly only when the person declaring the class wants it to.
In brief we can write following major benefits and needs for developing the concept of class.
- Allows to group data and methods/functions together as a single named entity.
- Allows to name just a template with certain data and methods. Actual function can only be carried out by declaring objects based on this template.
- Allows to model real life where give names to definitions and physical entities based on that definition. For example definition Tree would mean a plant which stands tall on ground with stem and leaves. Some physical tree in front of you could be an object based on that definition.
- Allows controlled access to its member by defining private and public segment. There are more access definitions like protected etc. we will study further.